markloom 0.4.0 → 0.5.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 (50) hide show
  1. package/README.md +29 -16
  2. package/ai.md +160 -0
  3. package/collab.md +68 -0
  4. package/dist/ai/index.cjs +4 -3
  5. package/dist/ai/index.d.cts +4 -2
  6. package/dist/ai/index.d.ts +4 -2
  7. package/dist/ai/index.js +3 -2
  8. package/dist/{chunk-VVFIQLVR.cjs → chunk-4TMHVNL6.cjs} +71 -79
  9. package/dist/chunk-6DCI7AL3.js +208 -0
  10. package/dist/chunk-AC5E42NH.cjs +208 -0
  11. package/dist/chunk-GQ2HHRGI.cjs +16 -0
  12. package/dist/{chunk-QXJHFQLJ.js → chunk-JMOJU5EU.js} +4 -2
  13. package/dist/chunk-JS527FDV.cjs +294 -0
  14. package/dist/chunk-LA5SBCGQ.js +16 -0
  15. package/dist/{chunk-ITVAR2UM.js → chunk-LEYAQNJA.js} +5 -3
  16. package/dist/{chunk-J3QWW6CN.js → chunk-MFYF2A6U.js} +5 -13
  17. package/dist/chunk-RLTHVQNQ.js +294 -0
  18. package/dist/{chunk-LNSKDJMF.cjs → chunk-SLRD6FMP.cjs} +27 -25
  19. package/dist/{chunk-VMUJM52A.js → chunk-WUHTCCAE.js} +65 -6
  20. package/dist/{chunk-VSTOMEU2.cjs → chunk-YJAWPRJW.cjs} +400 -341
  21. package/dist/{chunk-HA6XHJUD.cjs → chunk-YXQDCW4Y.cjs} +22 -20
  22. package/dist/client-A0ZQJnyR.d.ts +137 -0
  23. package/dist/client-BNams4wv.d.cts +137 -0
  24. package/dist/collab/index.cjs +19 -0
  25. package/dist/collab/index.d.cts +3 -0
  26. package/dist/collab/index.d.ts +3 -0
  27. package/dist/collab/index.js +19 -0
  28. package/dist/comments-DlExS6f-.d.cts +43 -0
  29. package/dist/comments-PhnR7Gkn.d.ts +43 -0
  30. package/dist/{controller-B_wG2Wh-.d.ts → controller-BkY1VPzc.d.ts} +17 -1
  31. package/dist/{controller-Cd1Dprrk.d.cts → controller-CVIZI--A.d.cts} +17 -1
  32. package/dist/index.cjs +21 -243
  33. package/dist/index.d.cts +5 -7
  34. package/dist/index.d.ts +5 -7
  35. package/dist/index.js +22 -244
  36. package/dist/react/index.cjs +8 -5
  37. package/dist/react/index.d.cts +4 -2
  38. package/dist/react/index.d.ts +4 -2
  39. package/dist/react/index.js +7 -4
  40. package/dist/rebase-batch-8rL_aXEE.d.ts +38 -0
  41. package/dist/rebase-batch-bYnBJpRO.d.cts +38 -0
  42. package/dist/step-BrvHIK7O.d.cts +65 -0
  43. package/dist/step-BrvHIK7O.d.ts +65 -0
  44. package/dist/view/index.cjs +11 -8
  45. package/dist/view/index.d.cts +5 -3
  46. package/dist/view/index.d.ts +5 -3
  47. package/dist/view/index.js +7 -4
  48. package/package.json +10 -3
  49. package/dist/comments-USjT1wYN.d.cts +0 -105
  50. package/dist/comments-USjT1wYN.d.ts +0 -105
package/README.md CHANGED
@@ -16,7 +16,6 @@ import 'markloom/view/theme.css'
16
16
 
17
17
  const ed = new Editor(root, doc, {
18
18
  onChange: d => save(d), // or persist with docToMd(d)
19
- // optional: ai: { stream: yourStreamFn }
20
19
  })
21
20
  ```
22
21
 
@@ -46,19 +45,9 @@ This is not “we support export to `.md`.” The model is built so MD and the e
46
45
  - IME handled as a first-class path (composition aligned to the model, not “hope the browser is fine”).
47
46
  - Slash menu, bubble format bar, drag handle, gaps around atoms — product surface without forking the kernel.
48
47
 
49
- ### 4. AI write as a document transaction (not a floating card)
48
+ ### 4. AI write as a document transaction
50
49
 
51
- When you enable AI, generation is still the same tree and history:
52
-
53
- | Step | What happens |
54
- |------|----------------|
55
- | `/ai` or format bar | In-doc prompt shell |
56
- | Enter / stream | **Real top-level blocks** enter the body (faded = uncommitted) |
57
- | Live preview | MD soft-close + `mdToDoc` each frame → rich structure while streaming |
58
- | Accept | Strip draft marks, remove shell — **no second insert** |
59
- | Discard | **`undo` the whole transaction** (one past entry) |
60
-
61
- AI is strong because the rest of the model is strong — ids, Steps, MD, history — not because of a chat overlay.
50
+ One options field: `/ai`, format bar, real draft blocks, accept / undo — same tree and history. Example below; full transports in [ai.md](./ai.md).
62
51
 
63
52
  ### 5. Use the piece you need
64
53
 
@@ -66,6 +55,7 @@ AI is strong because the rest of the model is strong — ids, Steps, MD, history
66
55
  markloom tree, Steps, history, MD, appendText / diffById
67
56
  markloom/view editor + view/theme.css
68
57
  markloom/ai AI controller + stream helper + ai/theme.css
58
+ markloom/collab realtime OT client (pair with worker/)
69
59
  markloom/react optional React wrapper (peer react, optional)
70
60
  ```
71
61
 
@@ -79,25 +69,48 @@ const next = apply(doc, appendText(doc, blockId, token))
79
69
  await save(docToMd(next))
80
70
  ```
81
71
 
82
- **Editor + AI** (product):
72
+ **Editor + AI** (one example; [proxy / provider / custom → ai.md](./ai.md)):
73
+
74
+ ```bash
75
+ npm i markloom ai @ai-sdk/openai
76
+ ```
83
77
 
84
78
  ```ts
79
+ import { docToMd } from 'markloom'
85
80
  import { Editor } from 'markloom/view'
81
+ import { streamText } from 'ai'
82
+ import { createOpenAI } from '@ai-sdk/openai'
86
83
  import 'markloom/view/theme.css'
87
84
  import 'markloom/ai/theme.css'
88
85
 
86
+ const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY! })
87
+
89
88
  new Editor(el, doc, {
90
89
  onChange: d => save(docToMd(d)),
91
90
  ai: {
92
91
  stream: async (input, onToken) => {
93
- // your model or proxy
92
+ const result = streamText({
93
+ model: openai('gpt-4o-mini'),
94
+ prompt: input.context,
95
+ abortSignal: input.signal,
96
+ })
97
+ for await (const t of result.textStream) onToken(t)
94
98
  },
95
99
  },
96
100
  })
97
101
  ```
98
102
 
103
+ **Realtime collab** (one field; [worker + protocol → collab.md](./collab.md)):
104
+
105
+ ```ts
106
+ new Editor(el, doc, {
107
+ collab: { url: 'ws://127.0.0.1:8787', room: 'demo', name: 'Alice' },
108
+ })
109
+ ```
110
+
99
111
  ## Why this stack
100
112
 
113
+
101
114
  | Problem | Typical approach | markloom |
102
115
  |---------|------------------|----------|
103
116
  | MD round-trip ruins formatting | Best-effort export | Isomorphic projection + clean-block spans |
@@ -117,7 +130,7 @@ Preact, `@floating-ui/dom`, unified/mdast GFM (`mdast-util-*`, `micromark-extens
117
130
 
118
131
  ## Limits (honest)
119
132
 
120
- - Collaboration wire protocol (Yjs/OT network) not shipped; `map` / `rebase` foundations are in the kernel.
133
+ - Collaboration: client + Cloudflare Worker shipped (`collab: { url, room }` — see [collab.md](./collab.md)). TP2 / auth / multi-caret chrome still thin.
121
134
  - Tables are **atoms** (full grid model inside; not free nesting in the prose grammar).
122
135
 
123
136
  ## License
package/ai.md ADDED
@@ -0,0 +1,160 @@
1
+ # AI
2
+
3
+ Configure **how tokens arrive**. Slash `/ai`, format-bar continue/rewrite, draft blocks, live MD→structure, accept / undo discard are built in.
4
+
5
+ ```ts
6
+ import { Editor } from 'markloom/view'
7
+ import 'markloom/view/theme.css'
8
+ import 'markloom/ai/theme.css'
9
+ ```
10
+
11
+ Pick **one** transport: `provider` | `endpoint` | `stream`.
12
+
13
+ ---
14
+
15
+ ## Built-in OpenAI-compatible
16
+
17
+ Any host with `POST …/v1/chat/completions` + SSE (OpenAI, xAI, 智谱, …). Needs CORS; prefer a proxy in production.
18
+
19
+ ```ts
20
+ new Editor(el, doc, {
21
+ ai: {
22
+ provider: {
23
+ host: 'https://api.x.ai',
24
+ apiKey: import.meta.env.VITE_AI_KEY,
25
+ model: 'grok-3',
26
+ },
27
+ },
28
+ })
29
+ ```
30
+
31
+ ---
32
+
33
+ ## Same-origin proxy (production)
34
+
35
+ Keys stay on the server. Body from the editor: `{ action, context, docPreview, system, provider? }`. Respond with **SSE** — OpenAI `choices[0].delta.content` or `{ content: "…" }` per `data:` line.
36
+
37
+ ```ts
38
+ new Editor(el, doc, {
39
+ ai: { endpoint: '/api/ai/stream' },
40
+ })
41
+ ```
42
+
43
+ ```ts
44
+ // server: POST /api/ai/stream
45
+ export async function POST(req: Request) {
46
+ const body = await req.json()
47
+ const upstream = await fetch('https://api.x.ai/v1/chat/completions', {
48
+ method: 'POST',
49
+ headers: {
50
+ 'content-type': 'application/json',
51
+ authorization: `Bearer ${process.env.XAI_API_KEY}`,
52
+ },
53
+ body: JSON.stringify({
54
+ model: 'grok-3',
55
+ stream: true,
56
+ messages: [
57
+ { role: 'system', content: body.system },
58
+ {
59
+ role: 'user',
60
+ content: body.action === 'rewrite'
61
+ ? `Rewrite:\n\n${body.context}`
62
+ : `Continue after:\n\n${body.context}`,
63
+ },
64
+ ],
65
+ }),
66
+ })
67
+ return new Response(upstream.body, {
68
+ headers: {
69
+ 'content-type': 'text/event-stream',
70
+ 'cache-control': 'no-cache',
71
+ },
72
+ })
73
+ }
74
+ ```
75
+
76
+ ---
77
+
78
+ ## Vercel AI SDK
79
+
80
+ ```bash
81
+ npm i ai @ai-sdk/openai
82
+ # or @ai-sdk/xai, @ai-sdk/anthropic, …
83
+ ```
84
+
85
+ ```ts
86
+ import { streamText } from 'ai'
87
+ import { createOpenAI } from '@ai-sdk/openai'
88
+
89
+ const openai = createOpenAI({ apiKey: process.env.OPENAI_API_KEY! })
90
+
91
+ new Editor(el, doc, {
92
+ ai: {
93
+ stream: async (input, onToken) => {
94
+ const result = streamText({
95
+ model: openai('gpt-4o-mini'),
96
+ system:
97
+ input.action === 'rewrite'
98
+ ? 'Rewrite clearly. Output body only, no preface.'
99
+ : 'Continue in the same voice. Output body only, no preface.',
100
+ prompt:
101
+ input.action === 'rewrite'
102
+ ? input.context
103
+ : [input.docPreview, input.context].filter(Boolean).join('\n\n'),
104
+ abortSignal: input.signal,
105
+ })
106
+ for await (const delta of result.textStream)
107
+ onToken(delta)
108
+ },
109
+ },
110
+ })
111
+ ```
112
+
113
+ Same `stream` shape works with any SDK provider, agents, or RAG — call `onToken` with text chunks.
114
+
115
+ ---
116
+
117
+ ## Custom backend / agent
118
+
119
+ ```ts
120
+ new Editor(el, doc, {
121
+ ai: {
122
+ stream: async ({ action, context, docPreview, signal }, onToken) => {
123
+ const res = await fetch('/my-agent', {
124
+ method: 'POST',
125
+ headers: { 'content-type': 'application/json' },
126
+ body: JSON.stringify({ action, context, docPreview }),
127
+ signal,
128
+ })
129
+ const reader = res.body!.getReader()
130
+ const dec = new TextDecoder()
131
+ while (true) {
132
+ const { done, value } = await reader.read()
133
+ if (done) break
134
+ onToken(dec.decode(value, { stream: true }))
135
+ }
136
+ },
137
+ },
138
+ })
139
+ ```
140
+
141
+ ---
142
+
143
+ ## Optional knobs
144
+
145
+ ```ts
146
+ ai: {
147
+ provider: { host, apiKey, model }, // or endpoint / stream
148
+ continueSystem: '…',
149
+ rewriteSystem: '…',
150
+ onError: msg => toast.error(msg), // default: window.alert
151
+ onBusy: busy => setSpinner(busy),
152
+ }
153
+ ```
154
+
155
+ Programmatic: `ed.ai?.openAtFocus('continue' | 'rewrite')`, `ed.ai?.stop()`.
156
+
157
+ | You write | Library does |
158
+ |-----------|----------------|
159
+ | `provider` **or** `endpoint` **or** `stream` | Slash, bubble, drafts, MD preview, accept/undo |
160
+ | styles (`view` + `ai` theme) | AI chrome |
package/collab.md ADDED
@@ -0,0 +1,68 @@
1
+ # Collaboration
2
+
3
+ Real-time multiplayer via **centralized OT** (markloom `rebase` / `makeBias`) and a **Cloudflare Worker** Durable Object room (same WebSocket pattern as the chat repo: `acceptWebSocket` + fan-out).
4
+
5
+ ## Client (copy-paste)
6
+
7
+ ```bash
8
+ npm i markloom
9
+ # run the worker (below) or point url at a deployed room host
10
+ ```
11
+
12
+ ```ts
13
+ import { Editor } from 'markloom/view'
14
+ import 'markloom/view/theme.css'
15
+
16
+ new Editor(el, doc, {
17
+ collab: {
18
+ url: 'ws://127.0.0.1:8787', // or wss://your-worker.workers.dev
19
+ room: 'demo-room',
20
+ name: 'Alice',
21
+ },
22
+ })
23
+ ```
24
+
25
+ That is enough: local edits upload as Steps; remote Steps apply through OT. No extension list.
26
+
27
+ Optional: `color`, `seed` (empty room init; default = constructor `doc`).
28
+
29
+ Programmatic: `ed.collab` → `CollabClient` (`peersList`, `close()`).
30
+
31
+ ## Worker
32
+
33
+ ```bash
34
+ cd worker
35
+ bun install # or npm i
36
+ bun run dev # wrangler dev → ws://127.0.0.1:8787
37
+ ```
38
+
39
+ - `GET /room/:id` + WebSocket upgrade → one Durable Object per room name
40
+ - Snapshot persisted in DO storage; op log in memory (stale base → `resync`)
41
+
42
+ Deploy: `bun run deploy` (Cloudflare account + `wrangler login`).
43
+
44
+ ## Protocol (summary)
45
+
46
+ | Direction | Types |
47
+ |-----------|--------|
48
+ | C→S | `join`, `op`, `presence`, `ping` |
49
+ | S→C | `welcome`, `op`, `presence`, `peer-join` / `peer-leave`, `resync`, `error` |
50
+
51
+ See `src/collab/protocol.ts`.
52
+
53
+ ## Limits (honest)
54
+
55
+ - **TP2** (reordered remote undo chains) not proven; server serializes commits so common concurrent typing is covered by TP1 + central order.
56
+ - Local **undo** interleaved with remote may need a later resync.
57
+ - No auth: room id is the capability.
58
+ - Presence is on the wire; rich multi-caret chrome is optional product UI.
59
+
60
+ ## Lab
61
+
62
+ ```bash
63
+ # terminal 1
64
+ cd worker && bun run dev
65
+ # terminal 2
66
+ cd .. && bun run lab
67
+ # open two windows: http://localhost:5181/?room=demo
68
+ ```
package/dist/ai/index.cjs CHANGED
@@ -6,8 +6,9 @@
6
6
 
7
7
 
8
8
 
9
- var _chunkLNSKDJMFcjs = require('../chunk-LNSKDJMF.cjs');
10
- require('../chunk-VVFIQLVR.cjs');
9
+ var _chunkSLRD6FMPcjs = require('../chunk-SLRD6FMP.cjs');
10
+ require('../chunk-4TMHVNL6.cjs');
11
+ require('../chunk-GQ2HHRGI.cjs');
11
12
 
12
13
 
13
14
 
@@ -16,4 +17,4 @@ require('../chunk-VVFIQLVR.cjs');
16
17
 
17
18
 
18
19
 
19
- exports.MarkloomAi = _chunkLNSKDJMFcjs.MarkloomAi; exports.aiInstructionFromQuery = _chunkLNSKDJMFcjs.aiInstructionFromQuery; exports.blockPlainText = _chunkLNSKDJMFcjs.blockPlainText; exports.createAiStream = _chunkLNSKDJMFcjs.createAiStream; exports.focusBlockId = _chunkLNSKDJMFcjs.focusBlockId; exports.precedingPlainText = _chunkLNSKDJMFcjs.precedingPlainText; exports.startAiWrite = _chunkLNSKDJMFcjs.startAiWrite;
20
+ exports.MarkloomAi = _chunkSLRD6FMPcjs.MarkloomAi; exports.aiInstructionFromQuery = _chunkSLRD6FMPcjs.aiInstructionFromQuery; exports.blockPlainText = _chunkSLRD6FMPcjs.blockPlainText; exports.createAiStream = _chunkSLRD6FMPcjs.createAiStream; exports.focusBlockId = _chunkSLRD6FMPcjs.focusBlockId; exports.precedingPlainText = _chunkSLRD6FMPcjs.precedingPlainText; exports.startAiWrite = _chunkSLRD6FMPcjs.startAiWrite;
@@ -1,6 +1,8 @@
1
- export { A as AiConfig, a as AiPromptMode, b as AiProvider, c as AiStreamFn, d as AiStreamInput, e as AiWriteMode, f as AiWriteSession, M as MarkloomAi, g as MarkloomAiOpts, h as blockPlainText, i as createAiStream, j as focusBlockId, s as startAiWrite } from '../controller-Cd1Dprrk.cjs';
2
- import { E as ElementNode } from '../comments-USjT1wYN.cjs';
1
+ export { A as AiConfig, a as AiPromptMode, b as AiProvider, c as AiStreamFn, d as AiStreamInput, e as AiWriteMode, f as AiWriteSession, M as MarkloomAi, g as MarkloomAiOpts, h as blockPlainText, i as createAiStream, j as focusBlockId, s as startAiWrite } from '../controller-CVIZI--A.cjs';
2
+ import { E as ElementNode } from '../step-BrvHIK7O.cjs';
3
3
  import 'preact';
4
+ import '../comments-DlExS6f-.cjs';
5
+ import '../client-BNams4wv.cjs';
4
6
 
5
7
  /** 顶层块 [0, blockIdx) 纯文本拼接(作 /ai 上下文) */
6
8
  declare function precedingPlainText(doc: ElementNode, blockIdx: number): string;
@@ -1,6 +1,8 @@
1
- export { A as AiConfig, a as AiPromptMode, b as AiProvider, c as AiStreamFn, d as AiStreamInput, e as AiWriteMode, f as AiWriteSession, M as MarkloomAi, g as MarkloomAiOpts, h as blockPlainText, i as createAiStream, j as focusBlockId, s as startAiWrite } from '../controller-B_wG2Wh-.js';
2
- import { E as ElementNode } from '../comments-USjT1wYN.js';
1
+ export { A as AiConfig, a as AiPromptMode, b as AiProvider, c as AiStreamFn, d as AiStreamInput, e as AiWriteMode, f as AiWriteSession, M as MarkloomAi, g as MarkloomAiOpts, h as blockPlainText, i as createAiStream, j as focusBlockId, s as startAiWrite } from '../controller-BkY1VPzc.js';
2
+ import { E as ElementNode } from '../step-BrvHIK7O.js';
3
3
  import 'preact';
4
+ import '../comments-PhnR7Gkn.js';
5
+ import '../client-A0ZQJnyR.js';
4
6
 
5
7
  /** 顶层块 [0, blockIdx) 纯文本拼接(作 /ai 上下文) */
6
8
  declare function precedingPlainText(doc: ElementNode, blockIdx: number): string;
package/dist/ai/index.js CHANGED
@@ -6,8 +6,9 @@ import {
6
6
  focusBlockId,
7
7
  precedingPlainText,
8
8
  startAiWrite
9
- } from "../chunk-QXJHFQLJ.js";
10
- import "../chunk-J3QWW6CN.js";
9
+ } from "../chunk-JMOJU5EU.js";
10
+ import "../chunk-MFYF2A6U.js";
11
+ import "../chunk-LA5SBCGQ.js";
11
12
  export {
12
13
  MarkloomAi,
13
14
  aiInstructionFromQuery,