@blocknote/xl-ai 0.43.0 → 0.44.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.
- package/dist/blocknote-xl-ai.cjs +1 -38
- package/dist/blocknote-xl-ai.cjs.map +1 -1
- package/dist/blocknote-xl-ai.js +414 -27238
- package/dist/blocknote-xl-ai.js.map +1 -1
- package/dist/client-C4uaJa77.js +2228 -0
- package/dist/client-C4uaJa77.js.map +1 -0
- package/dist/client-DrruPiJu.cjs +36 -0
- package/dist/client-DrruPiJu.cjs.map +1 -0
- package/dist/server.cjs +2 -0
- package/dist/server.cjs.map +1 -0
- package/dist/server.js +25 -0
- package/dist/server.js.map +1 -0
- package/dist/webpack-stats.json +1 -1
- package/package.json +14 -7
- package/src/AIExtension.ts +103 -33
- package/src/api/aiRequest/{execute.ts → builder.ts} +31 -44
- package/src/api/aiRequest/index.ts +2 -2
- package/src/api/aiRequest/sendMessageWithAIRequest.ts +66 -0
- package/src/api/aiRequest/types.ts +10 -23
- package/src/api/formats/DocumentStateBuilder.ts +153 -0
- package/src/api/formats/base-tools/createAddBlocksTool.ts +5 -1
- package/src/api/formats/base-tools/createUpdateBlockTool.ts +5 -1
- package/src/api/formats/formats.ts +62 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/Add heading (h1) and code block_1_21c6ffe4ff4bd18e2a782b926b61618c.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add a list (end)_1_d0219ee443d8f6d3563dcffcba160730.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add a new paragraph (empty doc)_1_0737d0ae03c2d0adf101da14bdef2414.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add a new paragraph (end)_1_25717cdb5e0dabfd9e85a28126fc6b5b.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add a new paragraph (start)_1_8fc8e14082d21bf98623cd9ef57bafff.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/Add heading (h1) and code block_1_72b3fb10d4b64ad2c57b7e759fb45ea2.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add a list (end)_1_6330fcc2bc48733981e5337c6f38fe08.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add a new paragraph (empty doc)_1_1df3fb78a5790897b37bfba0ae96be1e.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add a new paragraph (end)_1_13ac6e523b724ec3d4e4113c1f973f7d.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add a new paragraph (start)_1_c7a2f3226a4ee862c75a049c92cea98f.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/Add heading (h1) and code block_1_1d3b032c0f42ea308a1e7a13160bec4b.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add a list (end)_1_e341e2801f875f5ac4e8a4508c274b08.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add a new paragraph (empty doc)_1_42ec272374b0f12670f81c091e9ceaca.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add a new paragraph (end)_1_86ff29befb09692b6ca78454082eb4a9.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add a new paragraph (start)_1_3fd9b56671a58b30eff463b30963b76b.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/Add heading (h1) and code block_1_a7541d4dff5630b127b0284a513d8cb6.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add a list (end)_1_5fa40270f0d516da79eb1a7f58c7f43f.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add a new paragraph (empty doc)_1_42ba165a69a6e53683cb40d6018445bf.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add a new paragraph (end)_1_b5d7570beb28712970433d8b53528829.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add a new paragraph (start)_1_94232233e44ede5453eea20dd949c070.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add and update paragraph_1_2dbe9e9945d6cabc0b02e812a6ba1b93.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add paragraph and update selection_1_039451748eb07d71d3d7f96c97950d62.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add and update paragraph_1_7a6f24c686aeb896da8088bd8ea14089.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add paragraph and update selection_1_a7597ddda3f5117e1572545c53c19414.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add and update paragraph_1_1f86584753177f1b06f2cab6a822316b.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add paragraph and update selection_1_bb81e06e77589983badfe53e3839ab83.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add and update paragraph_1_d6725684f23346e66f8289d5ba72d7c1.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add paragraph and update selection_1_8b11b2a66564f9985f33774d3862cd8c.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Delete/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/delete first block_1_71dfbd70fa9bcd8c2378c0b255360279.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Delete/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/delete first block_1_72e05e8a661b9149b89f8ca9a80a2129.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Delete/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/delete first block_1_00d51791f8357a4bc061a2cf8ce067f1.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Delete/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/delete first block_1_83607282733aee32b5769107be6b9428.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/clear block formatting_1_f3ecead131eac14f117b601ad92bae90.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/drop mark and link and change text within mark_1_6b686110fa540e40d81fd68ee23cde86.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/drop mark and link_1_fee0a33a7c0951dacc8fd9ba02adef0a.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/modify nested content_1_1d18b29fde3a6494f2d1df98d0689bcf.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/modify parent content_1_7d96675c4edc13f69084f42983de6d73.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/plain source block, add mention_1_785d7f53424b53e8b64f4732aa578c61.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/standard update_1_c01c22b2bf79f30908ce9ffb0798a79f.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, remove mark_1_66f540dda8b5f8e8713b9c6f0bdd4d3f.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, remove mention_1_9111f9b26383721d9186c99d035f44e8.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, replace content_1_6a2c68962725ab2dc43dc12b5e9e5d8f.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, update mention prop_1_60f48a7bd81fb6a72b96b284d61c6e53.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, update text_1_284f982ebe3b60bc15c674d63795a879.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in target block, add mark (paragraph)_1_6c8e4ac91518d57e4827481f00ddc38e.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in target block, add mark (word)_1_06f3ae0ab5b505f03cf8e0c6bd654b1e.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/translate selection_1_885e9088214dbb6d50dcda19d0056f3c.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/turn paragraphs into list_1_0e8f14f06679e951d88ec74919c24b90.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/update block prop and content_1_f6c1cfee51cd75204495d3db1d80350e.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/update block prop_1_759983067f25f0daafb42bc9fefcdb64.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/update block type and content_1_e9d9d699bbe4a3b6e754c530ffe56e2c.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/update block type_1_ac405ec31a0cb874515b0c5b6aa2eb2d.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/clear block formatting_1_1b60a2dae45a21cc2916e15e97bfd289.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/drop mark and link and change text within mark_1_a7e99401a3cc86c79b30fdf47b0dc28e.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/drop mark and link_1_75e458d048de9ef0fb1eef34109ec81b.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/modify nested content_1_f81acd3a9fb46c387163c91724ec4c55.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/modify parent content_1_49c9371e221a7966cac554b99ba56b02.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/plain source block, add mention_1_b2be33e4a07122a85e49b521c20f26db.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/standard update_1_08d79a078de070c800627c412f9a0d9f.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, remove mark_1_0d87ce48c7e9e690bde7fc3668fe735b.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, remove mention_1_a96e84a734674ca195c2b40bab34c2fa.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, replace content_1_f5be35337d2ac3c65ec6363d4f347364.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, update mention prop_1_a09c043f6d105b1496a7c79ce34e28d3.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, update text_1_dfc536ede5303a75993dea08764b318e.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in target block, add mark (paragraph)_1_ebbeca51137a25dc54cdb7bafab53bed.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in target block, add mark (word)_1_d6f14d8cecee690c72107e57eee0efbf.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/translate selection_1_1e9c30fa14f61508e6d90cbfa4d9b891.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/turn paragraphs into list_1_50b1aa228a2b2557dea5026daaef2fad.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/update block prop and content_1_4a65e945b3b6fac5d4a0cf8d623486d3.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/update block prop_1_83a73dcfd05a6cf6754e1eb24114c1f1.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/update block type and content_1_7500fd44498888e45aedc9dfa669737c.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/update block type_1_92eb84e55a7b9efe5daf52bef299b4a6.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/clear block formatting_1_c3fe0bb003a4e1d613472af309c46ab0.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/drop mark and link and change text within mark_1_9724ffa3960f9e2f0853ca65fa305d5a.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/drop mark and link_1_ab436caf1e1c8338ab798b9e41f27035.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/modify nested content_1_030d3ad5a7f2e03a8f141379accd970d.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/modify parent content_1_8123bc6c0c42f952c5081494aae87db3.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/plain source block, add mention_1_7740e1127e576e342300ad8ca046c116.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/standard update_1_b940b7342e81fb99f50941824dca6dc9.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, remove mark_1_69370edf5666084e6ab44e3c9a41fa12.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, remove mention_1_73ae7ea818d0050772e68d743b8c8f07.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, replace content_1_493b1cae062778312080cf9e73436d03.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, update mention prop_1_812164c840f1ad02eb52b9b82e8adad1.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, update text_1_28d3f4434e75617be2e5aaffcb5c1ca7.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in target block, add mark (paragraph)_1_2fcc358ab0331d440742d0b28cdbffcd.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in target block, add mark (word)_1_d51e7544c0fcb93030a9d4c14970a487.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/translate selection_1_f82bcc59263074bf367562f7380b9cef.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/turn paragraphs into list_1_34265b84999198d0abed53174f1081a1.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/update block prop and content_1_8a8bb024ac97dfc5a47387ceb86a483f.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/update block prop_1_4a0be63bfbef46eea3c480cd5c20d78b.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/update block type and content_1_2e78a51589c195d5f4a1668482db03c4.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/update block type_1_77c40f25fadd092d83b41c87d2b21055.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/clear block formatting_1_09ce4ed21f35db11e7e8abc53d8e897c.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/drop mark and link and change text within mark_1_1072f99168883f64e55663c24b1b0a0d.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/drop mark and link_1_d0d892fae6bedce4f397e9e70a26c548.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/modify nested content_1_dd6cb439703f9c3f9bad5e2cc1a911c2.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/modify parent content_1_3a1e3c71094e24988b7f754e1d329f94.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/plain source block, add mention_1_19d556214c5ef684a2c65e3a08f14ba1.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/standard update_1_e0e15748dddab0b96d9367062c1ee445.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, remove mark_1_c69996aacaf807f2f988d23570f1829e.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, remove mention_1_86a5a7047cd626ede49fa5336b0cfedf.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, replace content_1_c29ec07799c4f9099789d65b819038e8.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, update mention prop_1_0355ff1065aab025d93ccddb0d5a1005.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, update text_1_d2b04758b99475efcd78a137aa91cfe4.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in target block, add mark (paragraph)_1_071517f9f358c0806dd80b49096a405d.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in target block, add mark (word)_1_4bdc947c29ac3c96b95afac6843a6894.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/translate selection_1_94c4e51be42ba73c81d7edc503e92b40.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/turn paragraphs into list_1_63ec354cac388bce6c2b6d324473b48f.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/update block prop and content_1_9290d6b9a47efc6589359e2820ef6702.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/update block prop_1_220afe040247e0efb76c73bf82ed4d4e.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/update block type and content_1_8494a477cce9b50c531800a11a8fd6ef.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/update block type_1_c25f2e6f9ffe088112413cc2ca87e75a.json +15 -0
- package/src/api/formats/html-blocks/htmlBlocks.test.ts +190 -194
- package/src/api/formats/html-blocks/htmlBlocks.ts +22 -25
- package/src/api/formats/index.ts +2 -72
- package/src/api/formats/json/errorHandling.test.ts +30 -41
- package/src/api/formats/json/json.test.ts +1 -5
- package/src/api/formats/json/json.ts +26 -26
- package/src/api/formats/markdown-blocks/markdownBlocks.test.ts +1 -6
- package/src/api/formats/markdown-blocks/markdownBlocks.ts +23 -26
- package/src/api/formats/tests/sharedTestCases.ts +24 -16
- package/src/api/promptHelpers/addCursorPosition.ts +27 -23
- package/src/components/AIMenu/AIMenu.tsx +1 -2
- package/src/components/FormattingToolbar/AIToolbarButton.tsx +6 -5
- package/src/{i18n → hooks}/useAIDictionary.ts +1 -1
- package/src/index.ts +2 -4
- package/src/server.ts +11 -0
- package/src/streamTool/ChunkExecutionError.ts +13 -0
- package/src/streamTool/StreamToolExecutor.ts +23 -21
- package/src/streamTool/filterNewOrUpdatedOperations.ts +1 -0
- package/src/streamTool/index.ts +3 -1
- package/src/streamTool/jsonSchema.ts +10 -0
- package/src/streamTool/preprocess.ts +3 -1
- package/src/streamTool/streamTool.ts +10 -7
- package/src/streamTool/vercelAiSdk/clientside/ClientSideTransport.ts +15 -4
- package/src/streamTool/vercelAiSdk/util/appendableStream.test.ts +247 -0
- package/src/streamTool/vercelAiSdk/util/appendableStream.ts +72 -0
- package/src/streamTool/vercelAiSdk/util/chatHandlers.test.ts +229 -0
- package/src/streamTool/vercelAiSdk/util/chatHandlers.ts +49 -78
- package/src/streamTool/vercelAiSdk/util/injectDocumentStateMessages.ts +79 -0
- package/src/streamTool/vercelAiSdk/util/toolDefinitions.ts +40 -0
- package/src/testUtil/cases/combinedOperationsTestCases.ts +1 -1
- package/src/types.ts +30 -10
- package/src/util/AbortError.ts +9 -0
- package/types/src/AIExtension.d.ts +25 -18
- package/types/src/api/aiRequest/builder.d.ts +11 -0
- package/types/src/api/aiRequest/index.d.ts +2 -2
- package/types/src/api/aiRequest/sendMessageWithAIRequest.d.ts +21 -0
- package/types/src/api/aiRequest/types.d.ts +9 -18
- package/types/src/api/formats/DocumentStateBuilder.d.ts +53 -0
- package/types/src/api/formats/formats.d.ts +142 -0
- package/types/src/api/formats/html-blocks/htmlBlocks.d.ts +4 -16
- package/types/src/api/formats/index.d.ts +2 -166
- package/types/src/api/formats/json/json.d.ts +8 -17
- package/types/src/api/formats/markdown-blocks/markdownBlocks.d.ts +2 -18
- package/types/src/api/promptHelpers/addCursorPosition.d.ts +1 -2
- package/types/src/index.d.ts +2 -4
- package/types/src/server.d.ts +5 -0
- package/types/src/streamTool/ChunkExecutionError.d.ts +8 -0
- package/types/src/streamTool/StreamToolExecutor.d.ts +3 -7
- package/types/src/streamTool/index.d.ts +3 -1
- package/types/src/streamTool/jsonSchema.d.ts +2 -0
- package/types/src/streamTool/streamTool.d.ts +2 -2
- package/types/src/streamTool/vercelAiSdk/clientside/ClientSideTransport.d.ts +12 -0
- package/types/src/streamTool/vercelAiSdk/util/appendableStream.d.ts +13 -0
- package/types/src/streamTool/vercelAiSdk/util/appendableStream.test.d.ts +1 -0
- package/types/src/streamTool/vercelAiSdk/util/chatHandlers.d.ts +3 -4
- package/types/src/streamTool/vercelAiSdk/util/chatHandlers.test.d.ts +1 -0
- package/types/src/streamTool/vercelAiSdk/util/injectDocumentStateMessages.d.ts +2 -0
- package/types/src/streamTool/vercelAiSdk/util/toolDefinitions.d.ts +13 -0
- package/types/src/types.d.ts +24 -7
- package/types/src/util/AbortError.d.ts +6 -0
- package/src/api/aiRequest/defaultAIRequestSender.ts +0 -42
- package/src/api/formats/PromptBuilder.ts +0 -22
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/Add heading (h1) and code block_1_2b1987665a8c6b76ea1cc84255389571.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add a list (end)_1_d09f092a3a86410797b84afbe6a05773.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add a new paragraph (empty doc)_1_ca2502e6ccea5088da25c3f548a88adc.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add a new paragraph (end)_1_97ed001b6f5aed92d99361bc27ca0de9.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add a new paragraph (start)_1_83b238d8e21398ee970fac58c746fe19.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/Add heading (h1) and code block_1_138de1ba18f0c4a7c084805a95d8aced.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add a list (end)_1_e8b5b0d45734575f7ba8e685f6787aca.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add a new paragraph (empty doc)_1_1ac8c5c60083d88192ef7e84254cb786.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add a new paragraph (end)_1_a33718ee9e8c30a7679da0e2ea5443bf.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add a new paragraph (start)_1_9b1a71da901951950261005a76c3444a.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/Add heading (h1) and code block_1_d64b87442b874d6c9d4a16dcc4f0df14.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add a list (end)_1_acd39fdc6762628fe6f6f97d96d70a78.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add a new paragraph (empty doc)_1_3912ffdff061476f701b59e0f28a5515.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add a new paragraph (end)_1_f047b5323417dfe603d6f28a0f063aa2.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add a new paragraph (start)_1_6e56df97b3441430062e0b5d979d53c9.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/Add heading (h1) and code block_1_787274f40054195631a7e1b7f70b88f0.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add a list (end)_1_ac04492f6c52be72c3dc24214a0cf744.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add a new paragraph (empty doc)_1_5b51dd620d4b53f36159ec97780b2929.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add a new paragraph (end)_1_17d834e2d1cae83d1da0998fdfb46c08.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Add/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add a new paragraph (start)_1_fded5061f67d6e01b6704bcaf1181daa.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add and update paragraph_1_c859fc3e363e6b44c406982880adeaf8.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/add paragraph and update selection_1_a721c27bc0944c3390dbcf6cbc4aa30d.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add and update paragraph_1_fc80a600d06d9b0a834b3a8dc062d077.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/add paragraph and update selection_1_ea6525e3996561d49f3baaa53e5f4367.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add and update paragraph_1_a6ed8e1b1d7287f11052e60d21aa3c61.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/add paragraph and update selection_1_3f688e4336780f36c03fe2e06fb38ae1.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add and update paragraph_1_2ac4e99d05838a4666b65cfe9ffceee9.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Combined/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/add paragraph and update selection_1_dafc9c956b17f814f2e5daf2effc4612.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Delete/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/delete first block_1_24119724ddeddbe1d724375ad7546eef.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Delete/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/delete first block_1_fd0a1c180a2d6c7165823af96ca7a444.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Delete/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/delete first block_1_5c60f0de80e4a010dcf6e7b2f534b1d7.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Delete/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/delete first block_1_9ee58319810833bcc30596aa06091958.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/clear block formatting_1_327facc19973ed5bf5dfbb06bc842f58.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/drop mark and link and change text within mark_1_68d51d1950b2878e08616f9effbee616.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/drop mark and link_1_1acc3cfa3a758ee4118f48b99e56f7b5.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/modify nested content_1_9158921bdd72e8f26eed1d4a3ccff6a4.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/modify parent content_1_a2946c73d9c3eeca81e4b4b08213a8a2.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/plain source block, add mention_1_91c94c8501e2f1d5d25c8e9c360dd3d1.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/standard update_1_adde6c9d6144449d4c436ed39a9afcb1.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, remove mark_1_4d2b9b00dc36b2bb12aae561adde829e.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, remove mention_1_06ade1c91064a7b257315d7cfb3dae1c.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, replace content_1_24881d7683d6ecbd852f58f6580259f4.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, update mention prop_1_1c9a4f955e0248798e87ab2412de660d.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in source block, update text_1_9e3a8c2b7c0c40aa89c4b52ccf040007.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in target block, add mark (paragraph)_1_d4c19bfff5993efff243e799e4055cc9.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/styles + ic in target block, add mark (word)_1_e31071ae9ad80a23786ec0afc5106c32.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/translate selection_1_efc8d37a125c48a5d0af15ecaf8e4b20.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/turn paragraphs into list_1_3ba9845d9c519b43ddbadaddb122d431.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/update block prop and content_1_4f6fdb800f1928aed2629f707b95b0da.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/update block prop_1_b25dd6e47055e54d58f1fd1f18feb14d.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/update block type and content_1_de3f09510d3c3eee14653fe5799dbae7.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/update block type_1_d805af33ab12e1bf8f2cb1a055a91fbd.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/clear block formatting_1_3b802465d0bbbdbbcb387b14492eefcc.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/drop mark and link and change text within mark_1_1138449389739970ddab00e2ca2b4bca.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/drop mark and link_1_2f40ee8072a0c34e771a2bd001d04b3a.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/modify nested content_1_3d19c192afee48b2656b6bdf3ac80415.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/modify parent content_1_88d6bccbefaf007c2c02e7e007c0f70b.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/plain source block, add mention_1_89cf6c28cb2ec992330f7c1bdc342068.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/standard update_1_b300195a352d5bddf97a0136eeb314e6.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, remove mark_1_008db1a44c8ee4e4d98c2e62c05f1906.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, remove mention_1_9a1800c42b72be41038a25622ff00709.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, replace content_1_0463e82390d623aec168d4e483a8e7c1.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, update mention prop_1_cf6b0ebb12aa86b848af40e9fa5aa4c6.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in source block, update text_1_2b8a7aa1c2a0945eb657e1784120dabc.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in target block, add mark (paragraph)_1_7f14399291525650d7f05c5015dd3b59.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/styles + ic in target block, add mark (word)_1_710f89bc66a6352e1c21328e600f2536.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/translate selection_1_d2ee0ac3b245b97f7a730d85a4575ac3.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/turn paragraphs into list_1_d2eeb79d3f7120d2c9d698e3b82c7362.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/update block prop and content_1_e22ef915ccf69ed6d2eb9f1a04b86c20.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/update block prop_1_6d4c550d09a7bfdb440308f277b85a11.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/update block type and content_1_2448cba67be91338d1977d4a980761a6.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/update block type_1_88fade9a250bf912d8d65f9db17e6de7.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/clear block formatting_1_67c4abf409c5217946a8fd26353f3d5c.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/drop mark and link and change text within mark_1_4d1645603f58ac95cefa5802e9d0b576.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/drop mark and link_1_8235f32b241ce454e355284db306f2b5.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/modify nested content_1_1e7e3f801e8b2fcad2e947f25b842d59.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/modify parent content_1_06951fbd3511111eb460efd853b4c6ee.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/plain source block, add mention_1_d27b598add3108097cd76a3113395221.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/standard update_1_3e742ef6a27c2a70d6a34483f81b80cd.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, remove mark_1_3157ee5ddce8f578c94b14a1d8ee0694.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, remove mention_1_53046bb3c98a3ecc79d2ccc9f9ee1f88.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, replace content_1_d2aedab8bc5dae6b29a5dd2da56165d7.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, update mention prop_1_fddbbf8781b8c27f9e51a3f0183f370c.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in source block, update text_1_350896c5ea1c2ae3930e8300d37eb670.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in target block, add mark (paragraph)_1_da57da0afcca08a77da5df430ef1db17.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/styles + ic in target block, add mark (word)_1_717f43f6e3302767b191ed31d11b1dd6.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/translate selection_1_0e4c67cc4858f5dfe2f2004e598cdfbd.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/turn paragraphs into list_1_03c3d437686de6faba00429649340a81.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/update block prop and content_1_dd58f52c343818059aa71a9676a172d2.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/update block prop_1_a4f7c3617705406313b619c566afef36.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/update block type and content_1_9b630368d36a8a4420b20bd1e82e455d.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming + generateObject)/update block type_1_5da70d5932f66c0ba6f5b15bbb05f68e.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/clear block formatting_1_ec9d93709e473574521d55108aa27f8f.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/drop mark and link and change text within mark_1_6b7b58db82605ee0f2fe5146738274dd.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/drop mark and link_1_4fa98468d00af0302fb35faba6aa2823.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/modify nested content_1_e761f6071dd9550f02555f17668007d5.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/modify parent content_1_57bc2951494344f4cd0062fefce14e5f.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/plain source block, add mention_1_88263a5a62758f9c809abbab15d1c4c7.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/standard update_1_a68854dc4dee1520292cf8b8816d3bf1.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, remove mark_1_44bcd73901e9f2eef1a454db1dd3a05d.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, remove mention_1_89aa084ced0d3526355fa9ec0a7a0f38.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, replace content_1_3f251996dcb01d2a4adcb6b548554cc5.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, update mention prop_1_61b231ae85994a3eec1c2eaabb2b3e80.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in source block, update text_1_3fd6871badc2f924056864cd76a571c0.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in target block, add mark (paragraph)_1_728e83ee8b26541816af7dcf417e127b.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/styles + ic in target block, add mark (word)_1_abd0a85b8c45cfa0b4449a382dc81602.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/translate selection_1_c0b30a449a94314760b815a202ee6f64.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/turn paragraphs into list_1_cfbaa99fe0298f4754b6bdd81c0a9601.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/update block prop and content_1_a560a1761f87da8f3bdb7b42357ba4ec.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/update block prop_1_d959d9e97f6cf99760b26b7d17c11244.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/update block type and content_1_649d6a7338cc6b674c4b4c38184c1037.json +0 -15
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/update block type_1_9cbb96117eed2b41fee6c0802fe00bb2.json +0 -15
- package/src/api/formats/html-blocks/defaultHTMLPromptBuilder.ts +0 -200
- package/src/api/formats/html-blocks/htmlPromptData.ts +0 -92
- package/src/api/formats/json/defaultJSONPromptBuilder.ts +0 -173
- package/src/api/formats/json/jsonPromptData.ts +0 -97
- package/src/api/formats/markdown-blocks/defaultMarkdownPromptBuilder.ts +0 -172
- package/src/api/formats/markdown-blocks/markdownPromptData.ts +0 -91
- package/src/streamTool/toolDefinitionsToToolSet.ts +0 -24
- package/types/src/api/aiRequest/defaultAIRequestSender.d.ts +0 -4
- package/types/src/api/aiRequest/execute.d.ts +0 -31
- package/types/src/api/formats/PromptBuilder.d.ts +0 -17
- package/types/src/api/formats/html-blocks/defaultHTMLPromptBuilder.d.ts +0 -3
- package/types/src/api/formats/html-blocks/htmlPromptData.d.ts +0 -31
- package/types/src/api/formats/json/defaultJSONPromptBuilder.d.ts +0 -3
- package/types/src/api/formats/json/jsonPromptData.d.ts +0 -76
- package/types/src/api/formats/markdown-blocks/defaultMarkdownPromptBuilder.d.ts +0 -3
- package/types/src/api/formats/markdown-blocks/markdownPromptData.d.ts +0 -52
- package/types/src/streamTool/toolDefinitionsToToolSet.d.ts +0 -9
- /package/types/src/{i18n → hooks}/useAIDictionary.d.ts +0 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client-DrruPiJu.cjs","sources":["../src/util/emptyBlock.ts","../src/util/trimArray.ts","../src/api/promptHelpers/trimEmptyBlocks.ts","../src/api/aiRequest/builder.ts","../src/streamTool/jsonSchema.ts","../src/streamTool/ChunkExecutionError.ts","../src/streamTool/StreamToolExecutor.ts","../src/streamTool/vercelAiSdk/util/injectDocumentStateMessages.ts","../src/streamTool/vercelAiSdk/util/partialObjectStreamUtil.ts","../src/streamTool/vercelAiSdk/util/toolDefinitions.ts","../src/streamTool/vercelAiSdk/clientside/ClientSideTransport.ts","../src/streamTool/vercelAiSdk/util/appendableStream.ts","../src/util/stream.ts","../src/streamTool/filterNewOrUpdatedOperations.ts","../src/streamTool/filterValidOperations.ts","../src/streamTool/toValidatedOperations.ts","../src/streamTool/preprocess.ts","../src/streamTool/vercelAiSdk/util/UIMessageStreamToOperationsResult.ts","../src/streamTool/vercelAiSdk/util/chatHandlers.ts","../src/api/aiRequest/sendMessageWithAIRequest.ts","../src/api/promptHelpers/addCursorPosition.ts","../src/api/promptHelpers/convertBlocks.ts","../src/api/promptHelpers/flattenBlocks.ts","../src/api/promptHelpers/suffixIds.ts","../src/api/formats/DocumentStateBuilder.ts","../src/prosemirror/fragmentUtil.ts","../src/prosemirror/agent.ts","../src/prosemirror/changeset.ts","../src/util/AbortError.ts","../src/api/formats/base-tools/util/validateBlockArray.ts","../src/api/formats/base-tools/createAddBlocksTool.ts","../src/api/formats/base-tools/createUpdateBlockTool.ts","../src/api/formats/base-tools/delete.ts","../src/api/formats/html-blocks/tools/getPartialHTML.ts","../src/prosemirror/rebaseTool.ts","../src/api/formats/html-blocks/tools/rebaseTool.ts","../src/api/formats/html-blocks/tools/validate.ts","../src/api/formats/html-blocks/tools/index.ts","../src/api/formats/html-blocks/htmlBlocks.ts","../src/api/schema/mergeSchema.ts","../src/api/schema/schemaToJSONSchema.ts","../src/api/formats/json/tools/validate.ts","../src/api/formats/json/tools/index.ts","../src/api/formats/json/json.ts","../src/api/formats/markdown-blocks/tools/rebaseTool.ts","../src/api/formats/markdown-blocks/tools/validate.ts","../src/api/formats/markdown-blocks/tools/index.ts","../src/api/formats/markdown-blocks/markdownBlocks.ts","../src/api/formats/formats.ts","../src/api/promptHelpers/index.ts","../src/i18n/dictionary.ts","../src/blocknoteAIClient/client.ts"],"sourcesContent":["import type { PartialBlock } from \"@blocknote/core\";\n\nexport function isEmptyParagraph(block: PartialBlock<any, any, any>) {\n return (\n ((block.type === \"paragraph\" || !block.type) && !block.content) ||\n (Array.isArray(block.content) && block.content.length === 0)\n );\n}\n","export function trimArray<T>(\n arr: T[],\n matchFn: (element: T) => boolean,\n trimStart = true,\n trimEnd = true\n): T[] {\n let start = 0;\n let end = arr.length;\n\n // Find the first non-matching element from the start\n if (trimStart) {\n while (start < end && matchFn(arr[start])) {\n start++;\n }\n }\n\n // Find the first non-matching element from the end\n if (trimEnd) {\n while (end > start && matchFn(arr[end - 1])) {\n end--;\n }\n }\n\n // Slice the array to include only the untrimmed portion\n return arr.slice(start, end);\n}\n","import { Block } from \"@blocknote/core\";\nimport { isEmptyParagraph } from \"../../util/emptyBlock.js\";\nimport { trimArray } from \"../../util/trimArray.js\";\n\nexport function trimEmptyBlocks(\n source: Block<any, any, any>[],\n opts?: {\n trimStart?: boolean;\n trimEnd?: boolean;\n cursorBlockId?: string;\n },\n) {\n // trim empty trailing blocks that don't have the cursor\n // if we don't do this, commands like \"add some paragraphs\"\n // would add paragraphs after the trailing blocks\n const trimmedSource = trimArray(\n source,\n (block) => {\n return isEmptyParagraph(block) && opts?.cursorBlockId !== block.id;\n },\n opts?.trimStart ?? false,\n opts?.trimEnd ?? true,\n );\n\n return trimmedSource;\n}\n","import { BlockNoteEditor } from \"@blocknote/core\";\nimport { isEmptyParagraph } from \"../../util/emptyBlock.js\";\nimport {\n aiDocumentFormats,\n AIRequest,\n DocumentStateBuilder,\n StreamToolsProvider,\n} from \"../index.js\";\nimport { trimEmptyBlocks } from \"../promptHelpers/trimEmptyBlocks.js\";\n\nexport async function buildAIRequest(opts: {\n editor: BlockNoteEditor<any, any, any>;\n useSelection?: boolean;\n deleteEmptyCursorBlock?: boolean;\n streamToolsProvider?: StreamToolsProvider<any, any>;\n onBlockUpdated?: (blockId: string) => void;\n onStart?: () => void;\n documentStateBuilder?: DocumentStateBuilder<any>;\n}): Promise<AIRequest> {\n const {\n useSelection,\n deleteEmptyCursorBlock,\n streamToolsProvider,\n documentStateBuilder,\n onStart,\n } = {\n useSelection: opts.useSelection ?? false,\n deleteEmptyCursorBlock: opts.deleteEmptyCursorBlock ?? true,\n streamToolsProvider:\n opts.streamToolsProvider ??\n aiDocumentFormats.html.getStreamToolsProvider(),\n documentStateBuilder:\n opts.documentStateBuilder ??\n aiDocumentFormats.html.defaultDocumentStateBuilder,\n onStart:\n opts.onStart ??\n (() => {\n // ignore\n }),\n };\n const cursorBlock = useSelection\n ? undefined\n : opts.editor.getTextCursorPosition().block;\n\n const emptyCursorBlockToDelete: string | undefined =\n cursorBlock &&\n deleteEmptyCursorBlock &&\n isEmptyParagraph(cursorBlock) &&\n trimEmptyBlocks(opts.editor.document).length > 0\n ? cursorBlock.id\n : undefined;\n\n const selectionInfo = useSelection\n ? opts.editor.getSelectionCutBlocks()\n : undefined;\n\n const streamTools = streamToolsProvider.getStreamTools(\n opts.editor,\n selectionInfo\n ? {\n from: selectionInfo._meta.startPos,\n to: selectionInfo._meta.endPos,\n }\n : undefined,\n opts.onBlockUpdated,\n );\n\n const ret = {\n editor: opts.editor,\n selectedBlocks: selectionInfo?.blocks,\n streamTools,\n emptyCursorBlockToDelete,\n onStart,\n };\n return {\n ...ret,\n documentState: await documentStateBuilder(ret),\n };\n}\n","import { jsonSchema, ToolSet } from \"ai\";\nimport type { JSONSchema7, JSONSchema7Definition } from \"json-schema\";\nimport isEqual from \"lodash.isequal\";\nimport { StreamTool } from \"./streamTool.js\";\n\nfunction streamToolToJSONSchema(tool: StreamTool<any>): {\n schema: JSONSchema7;\n $defs?: Record<string, JSONSchema7Definition>;\n} {\n // this adds the tool name as the \"type\". (not very clean way to do it)\n const { properties, required, $defs, ...rest } = tool.inputSchema;\n return {\n schema: {\n type: \"object\",\n description: tool.description,\n properties: {\n type: {\n type: \"string\",\n enum: [tool.name],\n },\n ...properties,\n },\n required: [\"type\", ...(required ?? [])],\n additionalProperties: false,\n ...rest,\n },\n $defs,\n };\n}\n\n/**\n * Creates the JSON Schema for an object that can represent a call to one or more StreamTools.\n *\n * E.g., given StreamTools add, delete, update, returns the json schema for an object that conforms to this shape:\n *\n * {\n * \"operations\": [\n * {\n * \"type\": \"add\",\n * ...parameters for add function...\n * },\n * {\n * \"type\": \"delete\",\n * ...parameters for delete function...\n * },\n * ...\n * ]\n * }\n */\nexport function createStreamToolsArraySchema(\n streamTools: StreamTool<any>[],\n): JSONSchema7 {\n const schemas = streamTools.map((tool) => streamToolToJSONSchema(tool));\n\n const $defs: Record<string, JSONSchema7Definition> = {};\n for (const schema of schemas) {\n for (const key in schema.$defs) {\n if ($defs[key] && !isEqual($defs[key], schema.$defs[key])) {\n throw new Error(`Duplicate, but different definition for ${key}`);\n }\n $defs[key] = schema.$defs[key];\n }\n }\n\n return {\n type: \"object\",\n properties: {\n operations: {\n //description:\n // \"Operations to apply to the document. Put all operations in this array in ONE tool call / function call. DO NOT use multiple operation arrays with parallel tool calls.\",\n type: \"array\",\n items: {\n anyOf: schemas.map((schema) => schema.schema),\n },\n },\n },\n additionalProperties: false,\n required: [\"operations\"] as string[],\n $defs: Object.keys($defs).length > 0 ? $defs : undefined,\n };\n}\n\nexport function streamToolsToToolSet(streamTools: StreamTool<any>[]): ToolSet {\n return {\n applyDocumentOperations: {\n inputSchema: jsonSchema(createStreamToolsArraySchema(streamTools)),\n outputSchema: jsonSchema({ type: \"object\" }),\n },\n };\n}\n","export class ChunkExecutionError extends Error {\n public readonly aborted: boolean;\n\n constructor(\n message: string,\n public readonly chunk: any,\n options?: { cause?: unknown; aborted?: boolean },\n ) {\n super(message, options);\n this.name = \"ChunkExecutionError\";\n this.aborted = options?.aborted ?? false;\n }\n}\n","import { getErrorMessage } from \"@ai-sdk/provider-utils\";\nimport { parsePartialJson } from \"ai\";\nimport { ChunkExecutionError } from \"./ChunkExecutionError.js\";\nimport { StreamTool, StreamToolCall } from \"./streamTool.js\";\n\n/**\n * The Operation types wraps a StreamToolCall with metadata on whether\n * it's an update to an existing and / or or a possibly partial (i.e.: incomplete, streaming in progress) operation\n */\ntype Operation<T extends StreamTool<any>[] | StreamTool<any>> = {\n /**\n * The StreamToolCall (parameters representing a StreamTool invocation)\n */\n operation: StreamToolCall<T>;\n /**\n * Whether this operation is an update to the previous operation\n * (i.e.: the previous operation was a partial operation for which we now have additional data)\n */\n isUpdateToPreviousOperation: boolean;\n /**\n * Whether this operation is a partial operation\n * (i.e.: incomplete, streaming in progress)\n */\n isPossiblyPartial: boolean;\n\n metadata: any;\n};\n\n/**\n * The StreamToolExecutor can apply StreamToolCalls to an editor.\n *\n * It accepts StreamToolCalls as JSON strings or already parsed and validated Operations.\n * Note: When passing JSON strings, the executor will parse and validate them into Operations.\n * When passing Operations, they're expected to have been validated by the StreamTool instances already.\n * (StreamTool.validate)\n *\n * Applying the operations is delegated to the StreamTool instances.\n *\n * @example see the `manual-execution` example\n */\nexport class StreamToolExecutor<T extends StreamTool<any>[]> {\n private readonly stream: TransformStream<\n string | Operation<T>,\n {\n status: \"ok\";\n chunk: Operation<T>;\n }\n > & {\n finishPromise: Promise<void>;\n };\n\n /**\n * @param streamTools - The StreamTools to use to apply the StreamToolCalls\n * @param abortSignal - Optional AbortSignal to cancel ongoing operations\n */\n constructor(\n private streamTools: T,\n private abortSignal?: AbortSignal,\n ) {\n this.stream = this.createStream();\n }\n\n private createStream() {\n let lastParsedResult: Operation<T> | undefined;\n const stream = new TransformStream<string | Operation<T>, Operation<T>>({\n transform: async (chunk, controller) => {\n const operation =\n typeof chunk === \"string\"\n ? await partialJsonToOperation(\n chunk,\n lastParsedResult?.isPossiblyPartial ?? false,\n this.streamTools,\n )\n : chunk;\n if (operation) {\n // TODO: string operations have been validated, but object-based operations have not.\n // To make this consistent, maybe we should extract the string parser to a separate transformer\n lastParsedResult = operation;\n controller.enqueue(operation);\n }\n },\n\n flush: (controller) => {\n // Check if the stream ended with a partial operation\n if (lastParsedResult?.isPossiblyPartial) {\n controller.error(new Error(\"stream ended with a partial operation\"));\n }\n },\n });\n\n // - internal dummy sink ensures all downstream writes are completed.\n // - pipeline.close() waits for both the first writable to close and the pipe to finish internally, so the consumer doesn’t need to know about internal transforms.\n // - Works regardless of the number of internal transforms.\n // - The readable can still be exposed if the consumer wants it, but they don’t have to consume it for close() to guarantee processing is done.\n\n const secondTransform = stream.readable.pipeThrough(this.createExecutor());\n\n const [internalReadable, externalReadable] = secondTransform.tee();\n\n // internalReadable goes to the dummy sink\n const finishPromise = internalReadable.pipeTo(new WritableStream());\n\n return {\n writable: stream.writable,\n // expose externalReadable to the consumer\n readable: externalReadable,\n finishPromise,\n };\n }\n\n private createExecutor() {\n const executors = this.streamTools.map((tool) => tool.executor());\n\n return new TransformStream<\n Operation<T>,\n { status: \"ok\"; chunk: Operation<T> }\n >({\n transform: async (chunk, controller) => {\n let handled = false;\n for (const executor of executors) {\n try {\n // Pass the signal to executor - it should handle abort internally\n const result = await executor.execute(chunk, this.abortSignal);\n if (result) {\n controller.enqueue({ status: \"ok\", chunk });\n handled = true;\n break;\n }\n } catch (error) {\n controller.error(\n new ChunkExecutionError(\n `Tool execution failed: ${getErrorMessage(error)}`,\n chunk,\n {\n cause: error,\n aborted: this.abortSignal?.aborted ?? false,\n },\n ),\n );\n return;\n }\n }\n if (!handled) {\n const operationType = (chunk.operation as any)?.type || \"unknown\";\n controller.error(\n new Error(\n `No tool could handle operation of type: ${operationType}`,\n ),\n );\n return;\n }\n },\n });\n }\n\n /**\n * Returns a WritableStream that can be used to write StreamToolCalls to the executor.\n *\n * The WriteableStream accepts JSON strings or Operation objects.\n *\n * Make sure to call `close` on the StreamToolExecutor instead of on the writable returned here!\n */\n public get writable() {\n return this.stream.writable;\n }\n\n /**\n * Returns a ReadableStream that can be used to read the results of the executor.\n */\n public get readable() {\n return this.stream.readable;\n }\n\n public async finish() {\n await this.stream.finishPromise;\n }\n\n async executeOperationsArray(source: AsyncIterable<string>) {\n const writer = this.writable.getWriter();\n for await (const chunk of source) {\n const parsed = await parsePartialJson(chunk);\n\n if (\n parsed.state === \"undefined-input\" ||\n parsed.state === \"failed-parse\"\n ) {\n return undefined;\n }\n\n if (!parsed) {\n return;\n }\n\n await writer.write(chunk);\n }\n await writer.close();\n await this.finish();\n }\n\n /**\n * Accepts an async iterable and writes each chunk to the internal stream.\n *\n * (alternative to writing to the writable stream using {@link writable})\n */\n async execute(source: AsyncIterable<string | Operation<T>>): Promise<void> {\n const writer = this.writable.getWriter();\n for await (const chunk of source) {\n await writer.write(chunk);\n }\n await writer.close();\n await this.finish();\n }\n\n /**\n * Accepts a single chunk and processes it using the same logic.\n *\n * (alternative to writing to the writable stream using {@link writable})\n */\n async executeOne(chunk: StreamToolCall<T>): Promise<void> {\n await this.execute(\n (async function* () {\n yield {\n operation: chunk,\n isUpdateToPreviousOperation: false,\n isPossiblyPartial: false,\n metadata: {},\n };\n })(),\n );\n }\n}\n\nasync function partialJsonToOperation<T extends StreamTool<any>[]>(\n chunk: string,\n isUpdateToPreviousOperation: boolean,\n streamTools: T,\n): Promise<Operation<T> | undefined> {\n const parsed = await parsePartialJson(chunk);\n\n if (parsed.state === \"undefined-input\" || parsed.state === \"failed-parse\") {\n return undefined;\n }\n\n if (!parsed) {\n return;\n }\n\n const func = streamTools.find((f) => f.name === (parsed.value as any)?.type);\n\n const validated = func && func.validate(parsed.value);\n\n if (validated?.ok) {\n return {\n operation: validated.value as StreamToolCall<T>,\n isPossiblyPartial: parsed.state === \"repaired-parse\",\n isUpdateToPreviousOperation,\n metadata: undefined,\n };\n } else {\n // no worries, probably a partial operation that's not valid yet\n return;\n }\n}\n","import { UIMessage } from \"ai\";\nimport { DocumentState } from \"../../../api/formats/DocumentStateBuilder.js\";\n\nexport function injectDocumentStateMessages(\n messages: UIMessage[],\n): UIMessage[] {\n return messages.flatMap((message) => {\n if (message.role === \"user\" && (message.metadata as any)?.documentState) {\n const documentState = (message.metadata as any)\n .documentState as DocumentState<any>;\n\n return [\n {\n role: \"assistant\",\n id: \"assistant-document-state-\" + message.id,\n parts: [\n ...(documentState.selection\n ? [\n {\n type: \"text\" as const,\n text: `This is the latest state of the selection (ignore previous selections, you MUST issue operations against this latest version of the selection):`,\n },\n {\n type: \"text\" as const,\n text: JSON.stringify(documentState.selectedBlocks),\n },\n {\n type: \"text\" as const,\n text: `This is the latest state of the entire document (INCLUDING the selected text), \nyou can use this to find the selected text to understand the context (but you MUST NOT issue operations against this document, you MUST issue operations against the selection):`,\n },\n {\n type: \"text\" as const,\n text: JSON.stringify(documentState.blocks),\n },\n ]\n : [\n {\n type: \"text\" as const,\n text:\n `There is no active selection. This is the latest state of the document (ignore previous documents, you MUST issue operations against this latest version of the document). \nThe cursor is BETWEEN two blocks as indicated by cursor: true.\n` +\n (documentState.isEmptyDocument\n ? `Because the document is empty, YOU MUST first update the empty block before adding new blocks.`\n : \"Prefer updating existing blocks over removing and adding (but this also depends on the user's question).\"),\n },\n {\n type: \"text\" as const,\n text: JSON.stringify(documentState.blocks),\n },\n ]),\n // Alternatively, we could explore using dynamic tools to fake document state retrieval:\n // {\n // type: \"dynamic-tool\",\n // toolName: \"getDocument\",\n // input: {},\n // output: documentState.htmlBlocks,\n // state: \"output-available\",\n // toolCallId: \"getDocument-\" + message.id,\n // },\n // {\n // type: \"dynamic-tool\",\n // toolName: \"getDocumentSelection\",\n // input: {},\n // output: documentState.selection\n // ? documentState.htmlSelectedBlocks\n // : \"no selection active\",\n // state: \"output-available\",\n // toolCallId: \"getDocument-\" + message.id,\n // },\n ],\n },\n message,\n ];\n }\n return [message];\n });\n}\n","import { getErrorMessage } from \"@ai-sdk/provider-utils\";\nimport { ObjectStreamPart, UIMessageChunk } from \"ai\";\n\n/**\n * This file contains some helper functions to convert between object generation (streaming and non-streaming)\n * and UI Message streams and vice versa.\n *\n * We convert object streams / generated objects to tool calls in UIMessageStreams because:\n *\n * - it simplifies our codebase (we can just handle everything as tool calls after conversion)\n * - there are some issues with using a TextStream, see below:\n *\n * Normally, the AI SDK uses a TextStream to transport generated objects / object streams.\n * However, this does not work well with error handling\n *\n * See:\n *\n * @see https://github.com/vercel/ai/issues/5027#issuecomment-2701011869\n * @see https://github.com/vercel/ai/issues/5115\n */\n\n/**\n * Transforms a partial object stream to a data stream format.\n * This is needed to pass errors through to the client in a clean way.\n *\n * @param stream - The partial object stream to transform\n * @returns A ReadableStream that emits data stream formatted chunks\n *\n * Based on: https://github.com/vercel/ai/blob/b2469681bd31635a33a4b233d889f122c0b432c9/packages/ai/src/ui/transform-text-to-ui-message-stream.ts#L3\n *\n */\nexport function partialObjectStreamAsToolCallInUIMessageStream<PARTIAL>(\n stream: ReadableStream<ObjectStreamPart<PARTIAL>>,\n toolName: string,\n): ReadableStream<UIMessageChunk> {\n let accumulatedString = \"\";\n return stream.pipeThrough(\n new TransformStream({\n start(controller) {\n controller.enqueue({ type: \"start\" });\n controller.enqueue({ type: \"start-step\" });\n controller.enqueue({\n type: \"tool-input-start\",\n toolCallId: \"call_object_1\",\n toolName,\n });\n // controller.enqueue({ type: \"text-start\", id: \"text-1\" });\n },\n transform(chunk, controller) {\n switch (chunk.type) {\n case \"text-delta\":\n accumulatedString += chunk.textDelta;\n controller.enqueue({\n type: \"tool-input-delta\",\n toolCallId: \"call_object_1\",\n inputTextDelta: chunk.textDelta,\n });\n break;\n case \"object\":\n case \"finish\":\n break;\n case \"error\":\n controller.enqueue({\n type: \"error\",\n errorText: getErrorMessage(chunk.error),\n });\n break;\n default: {\n const _exhaustiveCheck: never = chunk;\n throw new Error(`Unsupported chunk type: ${_exhaustiveCheck}`);\n }\n }\n },\n async flush(controller) {\n // controller.enqueue({ type: \"text-end\", id: \"text-1\" });\n controller.enqueue({\n type: \"tool-input-available\",\n toolCallId: \"call_object_1\",\n toolName,\n input: JSON.parse(accumulatedString),\n });\n controller.enqueue({ type: \"finish-step\" });\n controller.enqueue({ type: \"finish\" });\n },\n }),\n );\n}\n\n// convert a plain object to a UIMessageStream.\nexport function objectAsToolCallInUIMessageStream(\n object: any,\n toolName: string,\n) {\n const stream = new ReadableStream<UIMessageChunk>({\n start(controller) {\n controller.enqueue({ type: \"start\" });\n controller.enqueue({ type: \"start-step\" });\n controller.enqueue({\n type: \"tool-input-start\",\n toolCallId: \"call_object_1\",\n toolName,\n });\n controller.enqueue({\n type: \"tool-input-delta\",\n toolCallId: \"call_object_1\",\n inputTextDelta: JSON.stringify(object),\n });\n controller.enqueue({\n type: \"tool-input-available\",\n toolCallId: \"call_object_1\",\n toolName,\n input: object,\n });\n controller.enqueue({ type: \"finish-step\" });\n controller.enqueue({ type: \"finish\" });\n controller.close();\n },\n });\n return stream;\n}\n","import { asSchema, jsonSchema, JSONSchema7, tool, ToolSet } from \"ai\";\n\n/**\n * A serializable version of a Tool\n */\ntype ToolDefinition = {\n description?: string;\n inputSchema: JSONSchema7;\n outputSchema: JSONSchema7;\n};\n\ntype ToolDefinitions = Record<string, ToolDefinition>;\n\nexport function toolSetToToolDefinitions(toolSet: ToolSet): ToolDefinitions {\n return Object.fromEntries(\n Object.entries(toolSet).map(([name, tool]) => [\n name,\n {\n description: tool.description,\n inputSchema: asSchema(tool.inputSchema).jsonSchema,\n outputSchema: asSchema(tool.outputSchema).jsonSchema,\n },\n ]),\n );\n}\n\nexport function toolDefinitionsToToolSet(\n toolDefinitions: ToolDefinitions,\n): ToolSet {\n return Object.fromEntries(\n Object.entries(toolDefinitions).map(([name, definition]) => [\n name,\n tool({\n ...definition,\n inputSchema: jsonSchema(definition.inputSchema),\n outputSchema: jsonSchema(definition.outputSchema),\n }),\n ]),\n );\n}\n","import {\n ChatTransport,\n LanguageModel,\n ToolSet,\n UIMessage,\n UIMessageChunk,\n convertToModelMessages,\n generateObject,\n generateText,\n streamObject,\n streamText,\n} from \"ai\";\nimport { injectDocumentStateMessages } from \"../util/injectDocumentStateMessages.js\";\nimport {\n objectAsToolCallInUIMessageStream,\n partialObjectStreamAsToolCallInUIMessageStream,\n} from \"../util/partialObjectStreamUtil.js\";\nimport { toolDefinitionsToToolSet } from \"../util/toolDefinitions.js\";\n\nexport const PROVIDER_OVERRIDES = {\n \"mistral.chat\": {\n mode: \"auto\" as const,\n },\n \"google.generative-ai\": {\n mode: \"auto\" as const,\n },\n \"groq.chat\": {\n providerOptions: {\n groq: {\n structuredOutputs: false,\n },\n },\n },\n} as const;\n\nexport function getProviderOverrides(model: Exclude<LanguageModel, string>) {\n return (\n PROVIDER_OVERRIDES[model.provider as keyof typeof PROVIDER_OVERRIDES] || {}\n );\n}\n\nexport class ClientSideTransport<UI_MESSAGE extends UIMessage>\n implements ChatTransport<UI_MESSAGE>\n{\n constructor(\n public readonly opts: {\n /**\n * The language model to use for the LLM call (AI SDK)\n *\n * (when invoking `callLLM` via the `AIExtension` this will default to the\n * model set in the `AIExtension` options)\n *\n * Note: perhaps we want to remove this\n */\n model: LanguageModel;\n\n /**\n * The system prompt to use for the LLM call\n *\n * @default undefined\n */\n systemPrompt?: string;\n\n /**\n * Whether to stream the LLM response or not\n *\n * When streaming, we use the AI SDK stream functions `streamObject` / `streamText,\n * otherwise, we use the AI SDK `generateObject` / `generateText` functions.\n *\n * @default true\n */\n stream?: boolean;\n\n /**\n * Use object generation instead of tool calling\n *\n * @default false\n */\n objectGeneration?: boolean;\n\n /**\n * Additional options to pass to the AI SDK `generateObject` / `streamObject` / `streamText` / `generateText` functions\n */\n _additionalOptions?:\n | Partial<Parameters<typeof generateObject>[0]>\n | Partial<Parameters<typeof streamObject>[0]>\n | Partial<Parameters<typeof generateText>[0]>\n | Partial<Parameters<typeof streamText>[0]>;\n },\n ) {}\n\n /**\n * Calls an LLM with StreamTools, using the `generateObject` of the AI SDK.\n *\n * This is the non-streaming version.\n */\n protected async generateObject(messages: UIMessage[], tools: ToolSet) {\n const { model, _additionalOptions } = this.opts;\n\n if (typeof model === \"string\") {\n throw new Error(\"model must be a LanguageModelV2\");\n }\n\n // (we assume there is only one tool definition passed and that should be used for object generation)\n const toolName = Object.keys(tools)[0];\n const schema = tools[toolName].inputSchema;\n\n const ret = await generateObject<any, any, { operations: any }>({\n output: \"object\" as const,\n schema,\n model,\n mode: \"tool\",\n system: this.opts.systemPrompt,\n messages: convertToModelMessages(injectDocumentStateMessages(messages)),\n ...getProviderOverrides(model),\n ...((_additionalOptions ?? {}) as any),\n });\n\n return objectAsToolCallInUIMessageStream(ret.object, toolName);\n }\n\n /**\n * Calls an LLM with StreamTools, using the `streamObject` of the AI SDK.\n *\n * This is the streaming version.\n */\n protected async streamObject(messages: UIMessage[], tools: ToolSet) {\n const { model, _additionalOptions } = this.opts;\n\n if (typeof model === \"string\") {\n throw new Error(\"model must be a LanguageModelV2\");\n }\n\n // (we assume there is only one tool definition passed and that should be used for object generation)\n const toolName = Object.keys(tools)[0];\n const schema = tools[toolName].inputSchema;\n\n const ret = streamObject({\n output: \"object\" as const,\n schema,\n model,\n mode: \"tool\",\n system: this.opts.systemPrompt,\n messages: convertToModelMessages(injectDocumentStateMessages(messages)),\n ...getProviderOverrides(model),\n ...((_additionalOptions ?? {}) as any),\n });\n\n // Transform the partial object stream to a data stream format\n return partialObjectStreamAsToolCallInUIMessageStream(\n ret.fullStream,\n toolName,\n );\n }\n\n /**\n * Calls an LLM with StreamTools, using the `streamText` of the AI SDK.\n *\n * This is the streaming version.\n */\n protected async streamText(messages: UIMessage[], tools: ToolSet) {\n const { model, _additionalOptions } = this.opts;\n\n const ret = streamText({\n model,\n system: this.opts.systemPrompt,\n messages: convertToModelMessages(injectDocumentStateMessages(messages)),\n tools,\n toolChoice: \"required\",\n // extra options for streamObject\n ...((_additionalOptions ?? {}) as any),\n // activeTools: [\"applyDocumentOperations\"],\n });\n\n return ret.toUIMessageStream();\n }\n\n async sendMessages({\n messages,\n body,\n // metadata,\n }: Parameters<ChatTransport<UI_MESSAGE>[\"sendMessages\"]>[0]): Promise<\n ReadableStream<UIMessageChunk>\n > {\n const stream = this.opts.stream ?? true;\n const toolDefinitions = (body as any).toolDefinitions;\n const tools = toolDefinitionsToToolSet(toolDefinitions);\n\n if (this.opts.objectGeneration) {\n if (stream) {\n return this.streamObject(messages, tools);\n } else {\n return this.generateObject(messages, tools);\n }\n }\n\n if (stream) {\n // this can be used to simulate initial network errors\n // if (Math.random() < 0.5) {\n // throw new Error(\"fake network error\");\n // }\n\n const ret = await this.streamText(messages, tools);\n\n // this can be used to simulate network errors while streaming\n // let i = 0;\n // return ret.pipeThrough(\n // new TransformStream({\n // transform(chunk, controller) {\n // controller.enqueue(chunk);\n\n // if (++i === 200) {\n // console.log(\"cancel stream\");\n // controller.error(new Error(\"fake network error\"));\n // }\n // },\n // }),\n // );\n\n return ret;\n } else {\n // https://github.com/vercel/ai/issues/8380\n throw new Error(\"Not implemented (generateText)\");\n }\n }\n\n reconnectToStream(): Promise<ReadableStream<UIMessageChunk> | null> {\n throw new Error(\"Not implemented\");\n }\n}\n","/**\n * Creates an appendable stream that allows multiple ReadableStreams to be\n * appended sequentially. The streams are processed one after another, and\n * all data is forwarded to a single output ReadableStream.\n *\n * This is useful when you need to combine multiple streams that arrive\n * asynchronously into a single continuous stream.\n */\nexport function createAppendableStream<T>() {\n let controller: ReadableStreamDefaultController<T>;\n let ready = Promise.resolve();\n let canceled = false;\n let onCancel: ((reason: any) => void) | undefined;\n const cancelPromise = new Promise<never>((_, reject) => {\n onCancel = reject;\n });\n // Ensure cancelPromise rejections are always handled to avoid unhandled rejection warnings\n cancelPromise.catch(() => {\n // Rejection is handled by Promise.race in the append function\n });\n\n const output = new ReadableStream({\n start(c) {\n controller = c;\n },\n cancel(reason) {\n canceled = true;\n controller.error(reason);\n onCancel?.(reason);\n },\n });\n\n async function append(readable: ReadableStream<T>) {\n if (canceled) {\n throw new Error(\"Appendable stream canceled, can't append\");\n }\n const reader = readable.getReader();\n\n // Chain appends in sequence\n ready = ready.then(async () => {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n try {\n const { done, value } = await Promise.race([\n reader.read(),\n cancelPromise,\n ]);\n if (done || canceled) {\n break;\n }\n controller.enqueue(value);\n } catch (e) {\n canceled = true;\n controller.error(e);\n break;\n }\n }\n });\n\n return ready;\n }\n\n async function finalize() {\n await ready; // wait for last appended stream to finish\n\n if (!canceled) {\n controller.close(); // only close once no more streams will come\n }\n }\n\n return { output, append, finalize };\n}\n","/**\n * Converts an AsyncIterable to a ReadableStream\n */\nexport function asyncIterableToStream<T>(\n iterable: AsyncIterable<T>,\n): ReadableStream<T> {\n return new ReadableStream({\n async start(controller) {\n try {\n for await (const result of iterable) {\n controller.enqueue(result);\n }\n controller.close();\n } catch (error) {\n controller.error(error);\n }\n },\n });\n}\n\n// https://github.com/vercel/ai/blob/ebec3d3235d7a59bd8de8b0bed010777c1d25b05/packages/ai/core/util/async-iterable-stream.ts\n\n/**\n * A stream that is both an AsyncIterable and a ReadableStream\n */\nexport type AsyncIterableStream<T> = AsyncIterable<T> & ReadableStream<T>;\n\n/**\n * Creates an AsyncIterableStream from a ReadableStream\n */\nexport function createAsyncIterableStream<T>(\n source: ReadableStream<T>,\n): AsyncIterableStream<T> {\n if (source.locked) {\n throw new Error(\n \"Stream (source) is already locked and cannot be iterated.\",\n );\n }\n\n const stream = source.pipeThrough(new TransformStream<T, T>());\n\n (stream as AsyncIterableStream<T>)[Symbol.asyncIterator] = () => {\n if (stream.locked) {\n throw new Error(\"Stream is already locked and cannot be iterated again.\");\n }\n\n const reader = stream.getReader();\n return {\n async next(): Promise<IteratorResult<T>> {\n const { done, value } = await reader.read();\n return done ? { done: true, value: undefined } : { done: false, value };\n },\n };\n };\n\n return stream as AsyncIterableStream<T>;\n}\n\n/**\n * Creates an AsyncIterableStream from an AsyncGenerator\n */\nexport function createAsyncIterableStreamFromAsyncIterable<T>(\n source: AsyncIterable<T>,\n): AsyncIterableStream<T> {\n return createAsyncIterableStream(asyncIterableToStream(source));\n}\n","/**\n * This takes the partialObjectStream from an LLM streaming response.\n *\n * Note that this streams in multiple operations in the operations array, and this will be called with chunks like this:\n *\n * {operations: [op1, op2partial]}\n * {operations: [op1, op2complete, op3, op4]}\n *\n * This function transforms it into a stream of new or updated operations, so the output would be like this:\n *\n * {newOrUpdatedOperations: [op1, op2partial]}\n * {newOrUpdatedOperations: [op2complete, op3, op4]}\n */\nexport async function* filterNewOrUpdatedOperations(\n partialObjectStream: AsyncIterable<{\n operations?: any[];\n }>,\n metadata: any,\n): AsyncGenerator<{\n partialOperation: any;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n metadata: any;\n}> {\n let numOperationsAppliedCompletely = 0;\n let first = true;\n\n let lastOp: any;\n\n for await (const chunk of partialObjectStream) {\n if (!chunk.operations?.length) {\n // yield { newOrUpdatedOperations: [] };\n continue;\n }\n\n for (\n let i = numOperationsAppliedCompletely;\n i < chunk.operations.length;\n i++\n ) {\n const operation = chunk.operations[i];\n lastOp = operation;\n yield {\n partialOperation: operation,\n isUpdateToPreviousOperation:\n i === numOperationsAppliedCompletely && !first,\n isPossiblyPartial: i === chunk.operations.length - 1,\n metadata,\n };\n first = false;\n }\n\n // Update count to exclude the last operation which might be incomplete\n numOperationsAppliedCompletely = chunk.operations.length - 1;\n }\n\n if (!lastOp) {\n // TODO: this should be handled somewhere else\n throw new Error(\"No operations seen\");\n }\n\n // mark final operation as final (by emitting with isPossiblyPartial: false)\n yield {\n partialOperation: lastOp,\n isUpdateToPreviousOperation: true,\n isPossiblyPartial: false,\n metadata,\n };\n}\n","import { Result } from \"./streamTool.js\";\n\n/**\n * Yields only valid operations from the stream.\n *\n * For invalid operations, the `onInvalidOperation` callback is called.\n */\nexport async function* filterValidOperations<T>(\n operationsStream: AsyncIterable<{\n operation: Result<T>;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n metadata: any;\n }>,\n onInvalidOperation?: (chunk: {\n operation: Result<T> & {\n ok: false;\n };\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n metadata: any;\n }) => void,\n): AsyncGenerator<{\n operation: T;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n metadata: any;\n}> {\n let forceNewOperation = false;\n for await (const chunk of operationsStream) {\n const operation = chunk.operation;\n if (operation.ok) {\n yield {\n operation: operation.value,\n isUpdateToPreviousOperation: forceNewOperation\n ? false\n : chunk.isUpdateToPreviousOperation,\n isPossiblyPartial: chunk.isPossiblyPartial,\n metadata: chunk.metadata,\n };\n forceNewOperation = false;\n } else {\n forceNewOperation =\n forceNewOperation || !chunk.isUpdateToPreviousOperation;\n onInvalidOperation?.({\n ...chunk,\n operation,\n });\n }\n }\n}\n","import { Result, StreamTool, StreamToolCall } from \"./streamTool.js\";\n\n/**\n * Transforms the partialObjectStream into a stream of operations (tool calls), or indicates that the operation is invalid.\n *\n * Invalid operations can happen because:\n * a) the LLM produces an invalid result\n * b) the \"partial\" operation doesn't have enough data yet to execute\n */\nexport async function* toValidatedOperations<T extends StreamTool<any>[]>(\n partialObjectStream: AsyncIterable<{\n partialOperation: any;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n metadata: any;\n }>,\n streamTools: T,\n): AsyncGenerator<{\n operation: Result<StreamToolCall<T>>;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n metadata: any;\n}> {\n for await (const chunk of partialObjectStream) {\n const func = streamTools.find(\n (f) => f.name === chunk.partialOperation.type,\n )!;\n\n if (!func) {\n // Skip operations with no matching function\n // console.error(\"no matching function\", chunk.partialOperation);\n yield {\n operation: {\n ok: false,\n error: `No matching function for ${chunk.partialOperation.type}`,\n },\n isUpdateToPreviousOperation: chunk.isUpdateToPreviousOperation,\n isPossiblyPartial: chunk.isPossiblyPartial,\n metadata: chunk.metadata,\n };\n continue;\n }\n\n const operation = func.validate(chunk.partialOperation);\n\n yield {\n operation,\n isUpdateToPreviousOperation: chunk.isUpdateToPreviousOperation,\n isPossiblyPartial: chunk.isPossiblyPartial,\n metadata: chunk.metadata,\n };\n }\n}\n","import { ChunkExecutionError } from \"./ChunkExecutionError.js\";\nimport { filterValidOperations } from \"./filterValidOperations.js\";\nimport { StreamTool, StreamToolCall } from \"./streamTool.js\";\nimport { toValidatedOperations } from \"./toValidatedOperations.js\";\n\nexport type PreprocessOperationResult<T extends StreamTool<any>[]> = {\n operation: StreamToolCall<T>;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n metadata: any;\n};\n\n/**\n * Validates an stream of operations and filters out invalid operations.\n */\nexport async function* preprocessOperationsStreaming<\n T extends StreamTool<any>[],\n>(\n operationsStream: AsyncIterable<{\n partialOperation: any;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n metadata: any;\n }>,\n streamTools: T,\n): AsyncGenerator<PreprocessOperationResult<T>> {\n // from partial operations to valid / invalid operations\n const validatedOperationsStream = toValidatedOperations(\n operationsStream,\n streamTools,\n );\n\n // filter valid operations, invalid partial operations are ignored\n const validOperationsStream = filterValidOperations(\n validatedOperationsStream,\n (chunk) => {\n if (!chunk.isPossiblyPartial) {\n // only throw if the operation is not possibly partial\n \n throw new ChunkExecutionError(\"invalid operation: \" + chunk.operation.error, chunk);\n }\n },\n );\n\n yield* validOperationsStream;\n}\n\n/**\n * Validates an stream of operations and throws an error if an invalid operation is found.\n *\n * TODO: remove\n *\n * @deprecated\n */\nexport async function* preprocessOperationsNonStreaming<\n T extends StreamTool<any>[],\n>(\n operationsStream: AsyncIterable<{\n partialOperation: any;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n metadata: any;\n }>,\n streamTools: T,\n): AsyncGenerator<PreprocessOperationResult<T>> {\n // from partial operations to valid / invalid operations\n const validatedOperationsStream = toValidatedOperations(\n operationsStream,\n streamTools,\n );\n\n // filter valid operations, invalid operations should throw an error\n const validOperationsStream = filterValidOperations(\n validatedOperationsStream,\n (chunk) => {\n throw new Error(\"invalid operation: \" + chunk.operation.error);\n },\n );\n\n // yield results\n yield* validOperationsStream;\n}\n","import { DeepPartial } from \"ai\";\nimport {\n createAsyncIterableStream,\n createAsyncIterableStreamFromAsyncIterable,\n} from \"../../../util/stream.js\";\nimport { filterNewOrUpdatedOperations } from \"../../filterNewOrUpdatedOperations.js\";\nimport { preprocessOperationsStreaming } from \"../../preprocess.js\";\nimport { StreamTool, StreamToolCall } from \"../../streamTool.js\";\n\nimport { AsyncIterableStream } from \"../../../util/stream.js\";\n\n/**\n * Result of an LLM call with stream tools\n */\ntype OperationsResult<T extends StreamTool<any>[]> = AsyncIterableStream<{\n /**\n * The operation the LLM wants to execute\n */\n operation: StreamToolCall<T>;\n /**\n * Whether {@link operation} is an update to the previous operation in the stream.\n *\n * For non-streaming mode, this will always be `false`\n */\n isUpdateToPreviousOperation: boolean;\n /**\n * Whether the {@link operation} is possibly partial (i.e. the LLM is still streaming data about this operation)\n *\n * For non-streaming mode, this will always be `false`\n */\n isPossiblyPartial: boolean;\n\n metadata: any;\n}>;\n\nexport function objectStreamToOperationsResult<T extends StreamTool<any>[]>(\n stream: ReadableStream<DeepPartial<{ operations: StreamToolCall<T>[] }>>,\n streamTools: T,\n chunkMetadata: any,\n): OperationsResult<T> {\n // Note: we can probably clean this up by switching to streams instead of async iterables\n return createAsyncIterableStreamFromAsyncIterable(\n preprocessOperationsStreaming(\n filterNewOrUpdatedOperations(\n createAsyncIterableStream(stream),\n chunkMetadata,\n ),\n streamTools,\n ),\n );\n}\n","import { getErrorMessage } from \"@ai-sdk/provider-utils\";\nimport type { Chat } from \"@ai-sdk/react\";\nimport { DeepPartial, isToolUIPart, UIMessage } from \"ai\";\nimport { ChunkExecutionError } from \"../../ChunkExecutionError.js\";\nimport { Result, StreamTool, StreamToolCall } from \"../../streamTool.js\";\nimport { StreamToolExecutor } from \"../../StreamToolExecutor.js\";\nimport { createAppendableStream } from \"./appendableStream.js\";\nimport { objectStreamToOperationsResult } from \"./UIMessageStreamToOperationsResult.js\";\n\n/**\n * Listens to messages received in the `chat` object and processes tool calls\n * by streaming them to an executor\n *\n * It also listens to the status and error events of the chat object and handles them\n * appropriately.\n *\n * It also waits for all tool calls to be completed and then adds the results to the chat object.\n *\n * NOTE: listening to the `chat` object + error handling is a bit cumbersome. It might have been\n * cleaner to directly listen to the UIMessageStream. However, for that we'd probably\n * need to wrap the transport or chat object in AIExtension\n *\n * The error handling is currently quite convoluted. To properly test this,\n * you can:\n * a) make sure a tool call fails\n * b) make sure the entire request fails (network error)\n *\n */\nexport async function setupToolCallStreaming(\n streamTools: StreamTool<any>[],\n chat: Chat<any>,\n onStart?: () => void,\n abortSignal?: AbortSignal,\n): Promise<Result<void>> {\n /*\n We use a single executor even for multiple tool calls.\n This is because a tool call operation (like Add), might behave differently\n if a block has been added earlier (i.e.: executing tools can keep state, \n and this state is shared across parallel tool calls).\n */\n const executor = new StreamToolExecutor(streamTools, abortSignal);\n\n const appendableStream = createAppendableStream<any>();\n\n const pipeToPromise = appendableStream.output.pipeTo(executor.writable);\n\n const toolCallStreams = new Map<string, ToolCallStreamData>();\n\n let first = true;\n\n // Possible improvement: instead of pushing tool call updates directly,\n // we could make this a readablestream where we return the latest state\n // of the tool call input. This way we don't process all intermediate\n // streaming steps in case downstream consumer (like the StreamToolExecutor)\n // are slower than the producer\n const unsub = chat[\"~registerMessagesCallback\"](() => {\n processToolCallParts(chat, (data) => {\n if (!toolCallStreams.has(data.toolCallId)) {\n const toolCallStreamData = createToolCallStream(\n streamTools,\n data.toolName,\n data.toolCallId,\n );\n appendableStream.append(toolCallStreamData.operationsStream);\n toolCallStreams.set(data.toolCallId, toolCallStreamData);\n if (first) {\n first = false;\n onStart?.();\n }\n }\n return toolCallStreams.get(data.toolCallId)!;\n });\n });\n\n const statusHandler = new Promise<void>((resolve) => {\n const unsub2 = chat[\"~registerStatusCallback\"](() => {\n if (chat.status === \"ready\" || chat.status === \"error\") {\n unsub();\n unsub2();\n if (chat.status !== \"error\") {\n // don't unsubscribe the error listener if chat.status === \"error\"\n // we need to wait for the error event, because only in the error event we can read chat.error\n // (in this status listener, it's still undefined)\n unsub3();\n }\n resolve();\n }\n });\n\n const unsub3 = chat[\"~registerErrorCallback\"](() => {\n if (chat.error) {\n unsub3();\n for (const data of toolCallStreams.values()) {\n if (!data.complete) {\n // this can happen in case of a network error for example\n data.writer.abort(chat.error);\n }\n }\n // reject(chat.error);\n // we intentionally commented out the above line to not reject here\n // instead, we abort (raise an error) in the unfinished tool calls\n }\n });\n });\n\n // wait until all messages have been received\n // (possible improvement(?): we can abort the request if any of the tool calls fail\n // instead of waiting for the entire llm response)\n await statusHandler;\n\n // we're not going to append any more streams from tool calls, because we've seen all tool calls\n await appendableStream.finalize();\n // let all stream executors finish, this can take longer due to artificial delays\n // (e.g. to simulate human typing behaviour)\n const results = await Promise.allSettled([executor.finish(), pipeToPromise]); // awaiting pipeToPromise as well to prevent unhandled promises\n const result = results[0];\n\n if (\n results[1].status === \"rejected\" &&\n (results[0].status !== \"rejected\" ||\n results[0].reason !== results[1].reason)\n ) {\n throw new Error(\n \"unexpected, pipeToPromise rejected but executor.finish() doesn't have same error!?\",\n );\n }\n\n let error: ChunkExecutionError | undefined;\n\n if (result.status === \"rejected\") {\n if (result.reason instanceof ChunkExecutionError) {\n error = result.reason;\n } else {\n if (!chat.error) {\n throw new Error(\n \"Unexpected: no ChunkExecutionError but also no chat.error (network error?)\",\n );\n }\n }\n }\n\n let errorSeen = false;\n // process results\n const toolCalls = Array.from(\n toolCallStreams.values().filter((data) => data.complete),\n );\n toolCalls.forEach((toolCall, index) => {\n const isErrorTool =\n toolCall.toolCallId === error?.chunk.metadata.toolCallId;\n\n if (isErrorTool) {\n errorSeen = true;\n }\n\n // TODO: it would be better to add these tool outputs \"live\" as they occur,\n // possibly including a callback to create checkpoints after applying a tool\n if (!errorSeen) {\n chat.addToolOutput({\n state: \"output-available\",\n tool: toolCalls[index].toolName,\n toolCallId: toolCalls[index].toolCallId,\n\n output: { status: \"ok\" },\n });\n } else {\n chat.addToolOutput({\n tool: toolCalls[index].toolName,\n toolCallId: toolCalls[index].toolCallId,\n state: \"output-error\",\n errorText: JSON.stringify(\n isErrorTool\n ? { status: \"error\", error: getErrorMessage(error) }\n : { status: \"not-executed-previous-tool-errored\" },\n ),\n });\n }\n });\n\n return error\n ? {\n ok: false,\n error,\n }\n : { ok: true, value: void 0 };\n}\n\n// Types for tool call streaming\ntype ToolCallStreamData = {\n // stream: TransformStream<DeepPartial<{ operations: StreamToolCall<any>[] }>>;\n writer: WritableStreamDefaultWriter<\n DeepPartial<{ operations: StreamToolCall<any>[] }>\n >;\n complete: boolean;\n toolName: string;\n toolCallId: string;\n operationsStream: ReadableStream<any>;\n // executor: StreamToolExecutor<any>;\n};\n\n/**\n * Process tool call parts and manage individual streams per toolCallId\n */\nfunction processToolCallParts(\n chat: Chat<UIMessage>,\n getToolCallStreamData: (data: {\n toolName: string;\n toolCallId: string;\n }) => ToolCallStreamData,\n) {\n // TODO: better to check if tool has output instead of hardcoding lastMessage\n for (const part of chat.lastMessage?.parts ?? []) {\n if (!isToolUIPart(part)) {\n continue;\n }\n\n const toolName = part.type.replace(\"tool-\", \"\");\n\n if (toolName !== \"applyDocumentOperations\") {\n // we only process the combined operations tool call\n // in a future improvement we can add more generic support for different tool streaming\n continue;\n }\n\n const toolCallId = part.toolCallId;\n\n const toolCallData = getToolCallStreamData({\n toolName: part.type.replace(\"tool-\", \"\"),\n toolCallId,\n });\n\n processToolCallPart(part, toolCallData);\n }\n}\n\n/**\n * Create a complete stream pipeline for a single toolCallId\n */\nfunction createToolCallStream(\n streamTools: StreamTool<any>[],\n toolName: string,\n toolCallId: string,\n): ToolCallStreamData {\n const stream = new TransformStream<\n DeepPartial<{ operations: StreamToolCall<any>[] }>\n >();\n const operationsStream = objectStreamToOperationsResult(\n stream.readable,\n streamTools,\n { toolCallId },\n );\n\n const writer = stream.writable.getWriter();\n\n return {\n // stream,\n writer,\n complete: false,\n // executor,\n operationsStream,\n toolName,\n toolCallId,\n };\n}\n\n/**\n * Process a single tool call part (streaming or available)\n */\nfunction processToolCallPart(part: any, toolCallData: ToolCallStreamData) {\n if (part.state === \"input-streaming\") {\n const input = part.input;\n if (input !== undefined) {\n toolCallData.writer.write(input as any);\n }\n } else if (part.state === \"input-available\") {\n const input = part.input;\n if (input === undefined) {\n throw new Error(\"input is undefined\");\n }\n if (!toolCallData.complete) {\n toolCallData.complete = true;\n toolCallData.writer.write(input as any);\n toolCallData.writer.close();\n }\n }\n}\n","import { Chat } from \"@ai-sdk/react\";\nimport { UIMessage } from \"ai\";\nimport merge from \"lodash.merge\";\nimport {\n setupToolCallStreaming,\n streamToolsToToolSet,\n toolSetToToolDefinitions,\n} from \"../../streamTool/index.js\";\nimport { AIRequest } from \"./types.js\";\n\n/**\n * Submits a message to the LLM, similar to `chat.sendMessage`, but in addition:\n * - adds the document state to the message metadata\n * - sets up tool call streaming (so that BlockNote tool calls will be applied to the editor)\n *\n * (should not throw any errors)\n *\n * @param chat - the AI SDK Chat instance\n * @param aiRequest - the AI request (create using {@link buildAIRequest})\n * @param message - the message to send to the LLM (optional, defaults to the last message)\n * @param options - the `ChatRequestOptions` to pass to the `chat.sendMessage` method (custom metadata, body, etc)\n * @param abortSignal - Optional AbortSignal to cancel ongoing tool call operations\n *\n * @returns the result of the tool call processing. Consumer should check both `chat.status` and `result.ok`;\n * - `chat.status` indicates if the LLM request succeeeded\n * - `result` will indicate if the BlockNote tool calls were processed successfully\n */\nexport async function sendMessageWithAIRequest(\n chat: Chat<UIMessage>,\n aiRequest: AIRequest,\n message?: Parameters<Chat<UIMessage>[\"sendMessage\"]>[0],\n options?: Parameters<Chat<UIMessage>[\"sendMessage\"]>[1],\n abortSignal?: AbortSignal,\n) {\n const sendingMessage = message ?? chat.lastMessage;\n\n if (!sendingMessage) {\n throw new Error(\"No message to send\");\n }\n\n sendingMessage.metadata = merge(sendingMessage.metadata, {\n documentState: aiRequest.documentState,\n });\n\n const toolCallProcessing = setupToolCallStreaming(\n aiRequest.streamTools,\n chat,\n aiRequest.onStart,\n abortSignal,\n );\n options = merge(options, {\n metadata: {\n source: \"blocknote-ai\",\n },\n body: {\n toolDefinitions: toolSetToToolDefinitions(\n streamToolsToToolSet(aiRequest.streamTools),\n ),\n },\n });\n\n await chat.sendMessage(message, options);\n\n const result = await toolCallProcessing;\n return result;\n}\n","import { BlockNoteEditor } from \"@blocknote/core\";\n\nexport type BlocksWithCursor<T> =\n | {\n id: string;\n block: T;\n }\n | {\n cursor: true;\n };\n\nexport function addCursorPosition<T>(\n editor: BlockNoteEditor<any, any, any>,\n source: Array<{\n id: string;\n block: T;\n }>,\n): Array<BlocksWithCursor<T>> {\n const cursorPosition = editor.getTextCursorPosition();\n const ret: Array<BlocksWithCursor<T>> = [];\n\n for (const block of source) {\n const isBlockWithCursor = block.id === cursorPosition.block.id;\n\n ret.push({\n id: block.id,\n block: block.block,\n });\n\n if (isBlockWithCursor) {\n ret.push({\n cursor: true,\n });\n }\n }\n\n return ret;\n}\n","import { Block } from \"@blocknote/core\";\n\nexport async function convertBlocks<T>(source: Block<any, any, any>[], mapFn: (block: Block<any, any, any>) => Promise<T>): Promise<Array<{\n id: string;\n block: T;\n}>> {\n return await Promise.all(source.map(async (block) => {\n return {\n id: block.id,\n block: await mapFn(block),\n };\n }));\n}","import { Block } from \"@blocknote/core\";\n\nexport function flattenBlocks(\n source: Block<any, any, any>[],\n): Array<Block<any, any, any>> {\n return source.flatMap((block) => [\n {\n ...block,\n children: [],\n },\n ...flattenBlocks(block.children),\n ]);\n}\n","export function suffixIDs<T>(source: Array<T>): Array<T> {\n return source.map((el) => {\n if (typeof el === \"object\" && el && \"id\" in el) {\n return {\n ...el,\n id: `${el.id}$`,\n };\n }\n return el;\n });\n}\n","import { Block, BlockNoteEditor } from \"@blocknote/core\";\nimport { AIRequest } from \"../aiRequest/types.js\";\nimport {\n addCursorPosition,\n BlocksWithCursor,\n} from \"../promptHelpers/addCursorPosition.js\";\nimport { convertBlocks } from \"../promptHelpers/convertBlocks.js\";\nimport { flattenBlocks } from \"../promptHelpers/flattenBlocks.js\";\nimport { suffixIDs } from \"../promptHelpers/suffixIds.js\";\nimport { trimEmptyBlocks } from \"../promptHelpers/trimEmptyBlocks.js\";\n\n/**\n * A serializable version of the document state that can be passed to the backend.\n * This will be used as input to the LLM calls.\n */\nexport type DocumentState<T> =\n | {\n /**\n * No selection is active\n */\n selection: false;\n /**\n * The entire document and cursor position information.\n * Operations should be issued against these blocks and the cursor position can be used to determine the \"attention\" of the user\n * (i.e.: the AI suggestions should probably be made in / around the cursor position)\n */\n blocks: BlocksWithCursor<T>[];\n /**\n * Boolean to indicate if the document is empty\n */\n isEmptyDocument: boolean;\n }\n | {\n /**\n * A selection is active\n */\n selection: true;\n /**\n * The selected blocks. Operations should be issued against these blocks.\n */\n selectedBlocks: { id: string; block: T }[];\n /**\n * The entire document\n */\n blocks: { block: T }[];\n /**\n * Boolean to indicate if the document is empty\n */\n isEmptyDocument: boolean;\n };\n\n/**\n * A function that builds the document state based on the AIRequest.\n *\n * This is split from the PromptBuilder so that for example, you can build the document state on the client side,\n * and run the PromptBuilder on the server side to modify the Messages sent to the LLM.\n */\nexport type DocumentStateBuilder<T> = (\n aiRequest: Omit<AIRequest, \"documentState\">,\n) => Promise<DocumentState<T>>;\n\nexport function makeDocumentStateBuilder<T>(\n convertBlockFn: (\n editor: BlockNoteEditor<any, any, any>,\n block: Block<any, any, any>,\n ) => Promise<T>,\n): DocumentStateBuilder<T> {\n return async (aiRequest: Omit<AIRequest, \"documentState\">) => {\n if (aiRequest.selectedBlocks) {\n return await getDocumentStateWithSelection(\n aiRequest.editor,\n convertBlockFn,\n {\n selectedBlocks: aiRequest.selectedBlocks,\n },\n );\n } else {\n return await getDocumentStateNoSelection(\n aiRequest.editor,\n convertBlockFn,\n {\n excludeBlockIds: aiRequest.emptyCursorBlockToDelete\n ? [aiRequest.emptyCursorBlockToDelete]\n : undefined,\n },\n );\n }\n };\n}\n\nasync function getDocumentStateNoSelection<T>(\n editor: BlockNoteEditor<any, any, any>,\n convertBlockFn: (\n editor: BlockNoteEditor<any, any, any>,\n block: Block<any, any, any>,\n ) => Promise<T>,\n opts: {\n excludeBlockIds?: string[];\n },\n): Promise<DocumentState<T>> {\n const isEmptyDocument = trimEmptyBlocks(editor.document).length === 0;\n const cursorBlockId = editor.getTextCursorPosition().block.id;\n const input = trimEmptyBlocks(editor.document, {\n cursorBlockId,\n });\n const blockArray = await convertBlocks(\n flattenBlocks(input),\n async (block) => {\n return convertBlockFn(editor, block);\n },\n );\n const withCursor = addCursorPosition(editor, blockArray);\n const filtered = withCursor.filter(\n (b) => \"cursor\" in b || !(opts.excludeBlockIds || []).includes(b.id),\n );\n const suffixed = suffixIDs(filtered);\n return {\n selection: false as const,\n blocks: suffixed,\n isEmptyDocument,\n };\n}\n\nasync function getDocumentStateWithSelection<T>(\n editor: BlockNoteEditor<any, any, any>,\n convertBlockFn: (\n editor: BlockNoteEditor<any, any, any>,\n block: Block<any, any, any>,\n ) => Promise<T>,\n opts: {\n selectedBlocks: Block<any, any, any>[];\n },\n): Promise<DocumentState<T>> {\n const isEmptyDocument = trimEmptyBlocks(editor.document).length === 0;\n const blockArray = await convertBlocks(\n flattenBlocks(opts.selectedBlocks),\n async (block) => {\n return convertBlockFn(editor, block);\n },\n );\n const suffixed = suffixIDs(blockArray);\n\n return {\n isEmptyDocument,\n selection: true as const,\n selectedBlocks: suffixed,\n blocks: (\n await convertBlocks(flattenBlocks(editor.document), async (block) => {\n return convertBlockFn(editor, block);\n })\n ).map(({ block }) => ({ block })), // strip ids so LLM can't accidentally issue updates to ids not in selection\n };\n}\n","import { Fragment } from \"prosemirror-model\";\n\n/**\n * helper method to get the index of the first character of a fragment\n */\nexport function getFirstChar(fragment: Fragment) {\n let index: number | undefined = undefined;\n let found = false;\n fragment.descendants((n, pos) => {\n if (found) {\n return false;\n }\n if (n.isText) {\n found = true;\n index = pos;\n }\n return true;\n });\n return index;\n}\n","import { getPmSchema, UnreachableCaseError } from \"@blocknote/core\";\nimport { Slice } from \"prosemirror-model\";\nimport { TextSelection, Transaction } from \"prosemirror-state\";\nimport {\n Mapping,\n ReplaceAroundStep,\n ReplaceStep,\n Step,\n Transform,\n} from \"prosemirror-transform\";\nimport { getFirstChar } from \"./fragmentUtil.js\";\n\nexport type AgentStep = {\n prosemirrorSteps: Step[];\n selection:\n | {\n anchor: number;\n head: number;\n }\n | undefined;\n type: \"select\" | \"replace\" | \"insert\";\n};\n\n/**\n * Takes an array of ReplaceSteps and applies them as a human-like agent.\n * Every step is split into 3 phases:\n * - select the text to be replaced (1 transaction per ReplaceStep)\n * - replace the text with the first character of the replacement (if any) (1 transaction per ReplaceStep)\n * - insert the replacement character by character (strlen-1 transactions per ReplaceStep)\n */\nexport function getStepsAsAgent(inputTr: Transform) {\n const pmSchema = getPmSchema(inputTr);\n\n const { modification } = pmSchema.marks;\n\n const agentSteps: AgentStep[] = [];\n\n const tr = new Transform(inputTr.before);\n\n for (let i = 0; i < inputTr.steps.length; i++) {\n const step = inputTr.steps[i];\n const invertMap = new Mapping(inputTr.mapping.maps.slice(0, i)).invert();\n\n if ((step as any).structure) {\n // Note: for structure changes (e.g.: node type or attr changes) we currently\n // don't trigger any selection\n\n if (step instanceof ReplaceStep) {\n if (\n step.to !== step.from + 1 ||\n step.slice.openStart !== 0 ||\n step.slice.openEnd !== 1 ||\n step.slice.content.size !== 2\n ) {\n throw new Error(\n \"Structure change is not in expected format (ReplaceStep)\",\n );\n }\n } else if (step instanceof ReplaceAroundStep) {\n // we only support ReplaceAroundSteps generated by SetNodeMarkup\n if (\n step.insert !== 1 ||\n step.slice.size !== 2 ||\n step.gapTo !== step.to - 1 ||\n step.gapFrom !== step.from + 1\n ) {\n throw new Error(\n \"Structure change is not in expected format (ReplaceAroundStep)\",\n );\n }\n } else {\n throw new Error(\"Step is not a ReplaceStep or ReplaceAroundStep\");\n }\n\n const from = invertMap.map(step.from);\n const newNode = step.slice.content.firstChild!;\n const oldNode = tr.doc.resolve(tr.mapping.map(from)).nodeAfter!;\n\n let marks = newNode.marks || [];\n\n if (newNode.type !== oldNode.type) {\n marks = modification\n .create({\n type: \"nodeType\",\n previousValue: oldNode.type.name,\n newValue: newNode.type.name,\n })\n .addToSet(marks);\n }\n\n const attrNames = new Set([\n ...Object.keys(newNode.attrs),\n ...Object.keys(oldNode.attrs),\n ]);\n for (const attr of attrNames) {\n if (newNode.attrs[attr] !== oldNode.attrs[attr]) {\n marks = modification\n .create({\n type: \"attr\",\n attrName: attr,\n previousValue: oldNode.attrs[attr],\n newValue: newNode.attrs[attr],\n })\n .addToSet(marks);\n }\n }\n\n const stepIndex = tr.steps.length;\n tr.setNodeMarkup(\n tr.mapping.map(from),\n newNode.type,\n newNode.attrs,\n marks,\n );\n\n agentSteps.push({\n prosemirrorSteps: tr.steps.slice(stepIndex),\n selection: undefined,\n type: \"replace\",\n });\n\n continue;\n }\n\n if (!(step instanceof ReplaceStep)) {\n throw new Error(\"Step is not a ReplaceStep\");\n }\n\n const from = invertMap.map(step.from);\n const to = invertMap.map(step.to);\n\n if (step.slice.openStart > 0 || step.slice.openEnd > 0) {\n // these kind of changes should not be generated by changeset.ts\n throw new Error(\n \"Slice has openStart or openEnd > 0, but structure=false\",\n );\n }\n\n // 1. Select text to be removed/replaced\n agentSteps.push({\n prosemirrorSteps: [],\n selection: {\n anchor: tr.mapping.map(from),\n head: tr.mapping.map(to),\n },\n type: \"select\",\n });\n\n // Replace the content\n const sliceTextContent = step.slice.content.textBetween(0, step.slice.size);\n\n const alreadyHasSameText =\n sliceTextContent ===\n tr.doc.textBetween(tr.mapping.map(from), tr.mapping.map(to));\n\n let sliceTo: number;\n\n if (alreadyHasSameText) {\n sliceTo = step.slice.content.size; // replace all at once, it's probably a mark update\n } else if (sliceTextContent.length === 0) {\n sliceTo = step.slice.content.size; // there's no replacement text, so use entire slice as replacement\n } else {\n // replace with the first character (similar to how a user would do it when selecting text and starting to type)\n const firstCharIndex = getFirstChar(step.slice.content);\n if (firstCharIndex === undefined) {\n // should have been caught by previous if statement\n throw new Error(\"unexpected: no first character found\");\n }\n sliceTo = firstCharIndex + 1;\n }\n\n let replaceEnd = tr.mapping.map(to);\n const replaceFrom = tr.mapping.map(to);\n let first = true;\n\n // Note that below, we don't actually delete content, but we mark it as deleted\n // with a deletion mark. Similarly, we mark inserted content with an insertion mark.\n // It might be cleaner to;\n // a) make this optional\n // b) actually delete / insert the content and let prosemirror-suggest-changes handle the marks\n for (let i = sliceTo; i <= step.slice.content.size; i++) {\n // in the first agent step (first character replacement) we mark existing content (if any) as deleted\n // (step.from !== step.to is used to check for replacements vs inserts)\n const isReplacing = first && from !== to;\n\n const stepIndex = tr.steps.length;\n if (isReplacing) {\n const $pos = tr.doc.resolve(tr.mapping.map(from));\n if ($pos.nodeAfter?.isBlock) {\n // mark the entire node as deleted. This can be needed for inline nodes or table cells\n tr.addNodeMark($pos.pos, pmSchema.mark(\"deletion\", {}));\n }\n tr.addMark($pos.pos, replaceEnd, pmSchema.mark(\"deletion\", {}));\n replaceEnd = tr.mapping.map(to);\n }\n\n // note, instead of inserting one charachter at a time at the end (a, b, c)\n // we're replacing the entire part every time (a, ab, abc)\n // would be cleaner to do just insertions, but didn't get this to work with the add operation\n // (and this kept code relatively simple)\n const replacement = new Slice(step.slice.content.cut(0, i), 0, 0);\n\n tr.replace(replaceFrom, replaceEnd, replacement).addMark(\n replaceFrom,\n replaceFrom + replacement.content.size,\n pmSchema.mark(\"insertion\", {}),\n );\n\n tr.doc.nodesBetween(\n replaceFrom,\n replaceFrom + replacement.content.size,\n (node, pos) => {\n if (\n pos < replaceFrom ||\n pos > replaceFrom + replacement.content.size\n ) {\n return true;\n }\n if (node.isBlock) {\n tr.addNodeMark(pos, pmSchema.mark(\"insertion\", {}));\n }\n return false;\n },\n );\n\n replaceEnd = tr.mapping.slice(stepIndex).map(replaceEnd);\n\n const sel = TextSelection.near(\n tr.doc.resolve(replaceFrom + replacement.content.size),\n -1,\n );\n\n agentSteps.push({\n prosemirrorSteps: tr.steps.slice(stepIndex),\n selection: {\n anchor: sel.from,\n head: sel.from,\n },\n type: isReplacing\n ? \"replace\" // 2. Replace the text with the first character (if any) of the replacement\n : \"insert\", // 3. Insert the replacement character by character\n });\n first = false;\n }\n }\n\n return agentSteps;\n}\n\nexport async function delayAgentStep(step: AgentStep) {\n const jitter = Math.random() * 0.3 + 0.85; // Random between 0.85 and 1.15\n if (step.type === \"select\") {\n await new Promise((resolve) => setTimeout(resolve, 100 * jitter));\n } else if (step.type === \"insert\") {\n await new Promise((resolve) => setTimeout(resolve, 10 * jitter));\n } else if (step.type === \"replace\") {\n await new Promise((resolve) => setTimeout(resolve, 200 * jitter));\n } else {\n throw new UnreachableCaseError(step.type);\n }\n}\n\nexport function applyAgentStep(tr: Transaction, step: AgentStep) {\n tr.setMeta(\"addToHistory\", false);\n\n if (step.selection) {\n tr.setMeta(\"aiAgent\", {\n selection: {\n anchor: step.selection.anchor,\n head: step.selection.head,\n },\n });\n }\n for (const pmStep of step.prosemirrorSteps) {\n const result = tr.maybeStep(pmStep);\n if (result.failed) {\n // this would fail for tables, but has since been fixed using filterTransaction (in AIExtension)\n // other cases have not been encountered so we throw an error here\n\n throw new Error(\"failed to apply step\");\n }\n }\n\n /*\n In getStepsAsAgent, we manually insert the insertion / modification / deletion marks.\n Another approach could be to only issue the change operations, and let prosemirror-suggest-changes\n handle adding the marks. This could be done with changing the getStepsAsAgent, and using\n `withSuggestChanges` like below.\n\n For now, manual approach seems to work well - keeping below as reference.\n\n function fakeDispatch(suggestTr: Transaction) {\n tr = suggestTr;\n }\n\n enableSuggestChanges(editor.prosemirrorState, editor.dispatch);\n if (!isSuggestChangesEnabled(editor.prosemirrorState)) {\n throw new Error(\n \"suggest changes could not be enabled, is the AI / suggestion plugin enabled?\"\n );\n }\n withSuggestChanges(fakeDispatch).bind({\n get state() {\n return editor.prosemirrorState;\n },\n })(tr);\n disableSuggestChanges(editor.prosemirrorState, editor.dispatch);\n */\n\n return tr;\n}\n","import { getNodeById, PartialBlock, updateBlockTr } from \"@blocknote/core\";\nimport {\n Change,\n ChangeSet,\n simplifyChanges,\n TokenEncoder,\n} from \"prosemirror-changeset\";\nimport { Node } from \"prosemirror-model\";\nimport { ReplaceStep, Transform } from \"prosemirror-transform\";\n\ntype CustomChange = Change & {\n type?: \"mark-update\" | \"node-type-or-attr-update\";\n};\n\n/**\n * Adds missing changes to the changes array.\n * This is needed because prosemirror-changeset may miss some changes,\n * such as marks or node attributes.\n *\n * NOTE: we might be able to replace this code with a custom encoder\n * (this didn't exist yet when this was written)\n *\n * @param changes The changes we have so far\n * @param originalDoc The original document, applying the changes should result in the expectedDoc\n * @param expectedDoc The expected document after applying the changes\n * @returns\n */\nfunction addMissingChanges(\n changes: CustomChange[],\n originalDoc: Node,\n expectedDoc: Node,\n) {\n const tr = new Transform(originalDoc);\n // first, apply all changes we already have to the originalTr\n\n for (const change of changes) {\n const step = new ReplaceStep(\n tr.mapping.map(change.fromA),\n tr.mapping.map(change.toA),\n expectedDoc.slice(change.fromB, change.toB),\n );\n\n tr.step(step);\n }\n\n const invertMap = tr.mapping.invert();\n\n // now, see if the doc created by applying all changes is equal to the expected doc\n let diffStart = tr.doc.content.findDiffStart(expectedDoc.content);\n\n // if the docs are not equal, we might be missing changes that have not been detected by prosemirror-changeset,\n // such as marks or node attributes. Let's find and add the missing changes.\n //\n // example, using _ for bold:\n // actual: helloworld!\n // expected: hello_world_!\n //\n // actual: hello_world_!\n // expected: helloworld!\n //\n // note: might be possible to merge this loop with the one at the start of the function\n // but considered ok for now\n while (diffStart !== null) {\n const expectedNode = expectedDoc.resolve(diffStart).nodeAfter;\n const actualNode = tr.doc.resolve(diffStart).nodeAfter;\n\n if (!expectedNode || !actualNode) {\n throw new Error(\"diffNode not found\");\n }\n\n const isNodeAttrChange =\n !expectedNode.isLeaf && expectedNode.content.eq(actualNode.content);\n\n const length = isNodeAttrChange\n ? 1\n : Math.min(expectedNode.nodeSize, actualNode.nodeSize);\n\n const to = diffStart + length;\n const fromA = invertMap.map(diffStart);\n const toA = invertMap.map(to);\n\n // find the position in changes array to insert the new change\n let insertPos = changes.length;\n for (let i = 0; i < changes.length; i++) {\n if (changes[i].fromA >= toA) {\n insertPos = i;\n break;\n }\n }\n\n changes.splice(insertPos, 0, {\n fromA: fromA,\n toA: toA,\n fromB: diffStart,\n toB: to,\n deleted: [],\n inserted: [],\n type: isNodeAttrChange ? \"node-type-or-attr-update\" : \"mark-update\",\n });\n\n // apply the step so we can find the next diff\n // Note: even for node type changes, this works - although maybe a ReplaceAroundStep might be cleaner?\n tr.step(\n new ReplaceStep(\n diffStart,\n to,\n expectedDoc.slice(diffStart, to),\n isNodeAttrChange,\n ),\n );\n const newDiffStart = tr.doc.content.findDiffStart(expectedDoc.content);\n\n if (newDiffStart === diffStart) {\n // prevent infinite loop, should not happen\n throw new Error(\"diffStart not moving\");\n }\n\n diffStart = newDiffStart;\n }\n\n return changes;\n}\n\nconst createEncoder = (doc: Node, updatedDoc: Node) => {\n // this encoder makes sure unchanged table cells stay intact,\n // without this, prosemirror-changeset would too eagerly\n // return changes across table cells (this is covered in test cases).\n // table handling can still be impproved though, see the disabled test cases\n // and https://github.com/ProseMirror/prosemirror-changeset/issues/22\n const tableCellsOld = new Set<string>();\n const tableCellsNew = new Set<string>();\n doc.descendants((node) => {\n if (node.type.name === \"tableCell\") {\n tableCellsOld.add(JSON.stringify(node.toJSON()));\n }\n });\n\n updatedDoc.descendants((node) => {\n if (node.type.name === \"tableCell\") {\n tableCellsNew.add(JSON.stringify(node.toJSON()));\n }\n });\n\n const tableCells = new Set(\n [...tableCellsOld].filter((cell) => tableCellsNew.has(cell)),\n );\n\n const encoder: TokenEncoder<any> = {\n encodeCharacter: (char) => char,\n encodeNodeStart: (node) => {\n if (node.type.name === \"tableCell\") {\n const str = JSON.stringify(node.toJSON());\n if (tableCells.has(str)) {\n // Two equal table cells in before / after are given a unique Encoding, to nudge prosemirror-changeset to keep them intact.\n return str;\n }\n return node.type.name;\n }\n return node.type.name;\n },\n encodeNodeEnd: (node) => {\n if (node.type.name === \"tableCell\") {\n const str = JSON.stringify(node.toJSON());\n if (tableCells.has(str)) {\n return str;\n }\n return -1;\n }\n return -1;\n },\n compareTokens: (a, b) => {\n return a === b;\n },\n };\n return encoder;\n};\n\n/**\n * This turns a single update `op` (that is, an update that could affect different parts of a block)\n * into more granular steps (that is, each step only affects a single part of the block), by using a diffing algorithm.\n *\n * @param editor the editor to apply the update to (only used for schema info)\n * @param op the update operation to apply\n * @param doc the document to apply the update to\n * @param dontReplaceContentAtEnd whether to not replace content at the end of the block (set to true processing \"partial updates\")\n * @param updateFromPos the position to start the update from (can be used for selections)\n * @param updateToPos the position to end the update at (can be used for selections)\n * @returns the granular steps to apply to the editor to get to the updated doc\n */\nexport function updateToReplaceSteps(\n op: {\n id: string;\n block: PartialBlock<any, any, any>;\n },\n doc: Node,\n dontReplaceContentAtEnd = false,\n updateFromPos?: number,\n updateToPos?: number,\n) {\n const blockPos = getNodeById(op.id, doc)!;\n const updatedTr = new Transform(doc);\n updateBlockTr(\n updatedTr,\n blockPos.posBeforeNode,\n op.block,\n updateFromPos,\n updateToPos,\n );\n\n let updatedDoc = updatedTr.doc;\n\n let changeset = ChangeSet.create(\n doc,\n undefined,\n createEncoder(doc, updatedDoc),\n );\n\n changeset = changeset.addSteps(updatedDoc, updatedTr.mapping.maps, 0);\n\n // When we're streaming (we sent `dontReplaceContentAtEnd = true`),\n // we need to add back the content that was removed at the end of the block.\n // because maybe this content will not actually be removed by the LLM, but instead,\n // it simply hasn't been streamed in yet.\n // e.g.:\n // actual: hello world! How are you doing?\n // incoming stream: hello world!\n //\n // at this point, the changeset would drop \"How are you doing?\"\n // but we should ignore this, as maybe this will still be in the LLMs yet-to-be-streamed response\n if (dontReplaceContentAtEnd && changeset.changes.length > 0) {\n const lastChange = changeset.changes[changeset.changes.length - 1];\n\n const lengthA = lastChange.toA - lastChange.fromA;\n const lengthB = lastChange.toB - lastChange.fromB;\n\n if (lengthA > lengthB) {\n const endOfBlockToReAdd = doc.slice(\n lastChange.fromA + lengthB,\n lastChange.toA,\n );\n updatedTr.step(\n new ReplaceStep(lastChange.toB, lastChange.toB, endOfBlockToReAdd),\n );\n updatedDoc = updatedTr.doc;\n changeset = ChangeSet.create(\n changeset.startDoc,\n undefined,\n createEncoder(changeset.startDoc, updatedDoc),\n );\n changeset = changeset.addSteps(updatedDoc, updatedTr.mapping.maps, 0);\n }\n }\n\n const steps = [];\n\n // `changes` holds the changes that can be made to the cleaned doc to get to the updated doc\n const changes: CustomChange[] = simplifyChanges(\n changeset.changes,\n updatedDoc,\n );\n\n for (let i = 0; i < changes.length; i++) {\n const step = changes[i];\n const replacement = updatedDoc.slice(step.fromB, step.toB);\n\n if (replacement.openEnd === 1 && replacement.openStart === 0) {\n // node attr / type update\n step.type = \"node-type-or-attr-update\";\n\n if (replacement.size > 2) {\n // This change is both a node type and content change\n // we split this in two separate steps so we can handle them separately in \"agent.ts\"\n const typeChange: CustomChange = {\n fromA: step.fromA,\n toA: step.fromA + 1,\n fromB: step.fromB,\n toB: step.fromB + 1,\n deleted: [],\n inserted: [],\n type: \"node-type-or-attr-update\",\n };\n\n const contentChange: CustomChange = {\n fromA: step.fromA + 1,\n toA: step.toA,\n fromB: step.fromB + 1,\n toB: step.toB,\n deleted: [],\n inserted: [],\n };\n\n changes.splice(i, 1, typeChange, contentChange);\n i++;\n }\n }\n }\n\n addMissingChanges(changes, doc, updatedDoc);\n\n for (let i = 0; i < changes.length; i++) {\n const step = changes[i];\n const replacement = updatedDoc.slice(step.fromB, step.toB);\n\n if (replacement.openEnd > 0 && replacement.size > 1) {\n throw new Error(\n \"unexpected, openEnd > 0 and size > 1, this should have been split into two steps\",\n );\n }\n\n if (\n i === changes.length - 1 &&\n dontReplaceContentAtEnd &&\n step.type === \"mark-update\"\n ) {\n // for streaming mode, let's say we update:\n // hello world\n // to:\n // hello <strong>world</strong>\n\n // when we're streaming, we might get\n // hello <strong>wo\n // as a partial update\n\n // it would look weird to apply an update like this mid-world,\n // so in this case, we should not add the update yet and wait for more content\n continue;\n }\n\n steps.push(\n new ReplaceStep(\n step.fromA,\n step.toA,\n replacement,\n step.type === \"node-type-or-attr-update\",\n ),\n );\n }\n\n return steps;\n}\n","export class AbortError extends Error {\n constructor(\n message: string,\n options?: { cause?: unknown; aborted?: boolean },\n ) {\n super(message, options);\n this.name = \"AbortError\";\n }\n}\n","import { DeepPartial } from \"ai\";\nimport { Result } from \"../../../../streamTool/streamTool.js\";\n\nexport function validateBlockArray<U>(\n inputArray: DeepPartial<Array<U>>,\n validateItem: (item: DeepPartial<U>) => Result<U>,\n): Result<U[]> {\n if (!inputArray || !Array.isArray(inputArray) || inputArray.length === 0) {\n return {\n ok: false,\n error: \"blocks is required\",\n };\n }\n\n const validatedBlocks: U[] = [];\n\n for (const item of inputArray) {\n const validationResult = validateItem(item as DeepPartial<U>);\n if (!validationResult.ok) {\n return {\n ok: false,\n error: `Invalid block: ${validationResult.error}`,\n };\n }\n validatedBlocks.push(validationResult.value);\n }\n\n return {\n ok: true,\n value: validatedBlocks,\n };\n}\n","import { BlockNoteEditor, insertBlocks, PartialBlock } from \"@blocknote/core\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport {\n AgentStep,\n applyAgentStep,\n delayAgentStep,\n getStepsAsAgent,\n} from \"../../../prosemirror/agent.js\";\nimport { updateToReplaceSteps } from \"../../../prosemirror/changeset.js\";\nimport { RebaseTool } from \"../../../prosemirror/rebaseTool.js\";\nimport { Result, streamTool } from \"../../../streamTool/streamTool.js\";\nimport { AbortError } from \"../../../util/AbortError.js\";\nimport { isEmptyParagraph } from \"../../../util/emptyBlock.js\";\nimport { validateBlockArray } from \"./util/validateBlockArray.js\";\n\n/**\n * Factory function to create a StreamTool that adds blocks to the document.\n */\nexport function createAddBlocksTool<T>(config: {\n /**\n * The description of the tool\n */\n description: string;\n /**\n * The schema of the tool\n */\n schema:\n | {\n block: JSONSchema7[\"items\"];\n $defs?: JSONSchema7[\"$defs\"];\n }\n | ((editor: BlockNoteEditor<any, any, any>) => {\n block: JSONSchema7[\"items\"];\n $defs?: JSONSchema7[\"$defs\"];\n });\n /**\n * A function that can validate a block\n */\n validateBlock: (\n block: any,\n editor: BlockNoteEditor<any, any, any>,\n ) => Result<T>;\n /**\n * The rebaseTool is used to get a projection of the document that\n * the JSON Tool Calls will be applied to. By using the rebaseTool we can\n * apply operations to a \"projected\" document, and then map them (rebase) to the actual document\n *\n * This is to:\n * - apply operations without suggestion-marks to an editor that has suggestions in it\n * (the projection should have the suggestions applied)\n * - apply operations from a format that doesn't support all Block features (e.g.: markdown)\n * (the projection should be the the BlockNote document without the unsupported features)\n */\n rebaseTool: (\n id: string,\n editor: BlockNoteEditor<any, any, any>,\n ) => Promise<RebaseTool>;\n /**\n * Converts the operation from `AddBlocksToolCall<T>` to `AddBlocksToolCall<PartialBlock<any, any, any>>`\n *\n * When using these factories to create a tool for a different format (e.g.: HTML / MD),\n * the `toJSONToolCall` function is used to convert the operation to a format that we can execute\n */\n toJSONToolCall: (\n editor: BlockNoteEditor<any, any, any>,\n chunk: {\n operation: AddBlocksToolCall<T>;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n },\n ) => Promise<AddBlocksToolCall<PartialBlock<any, any, any>> | undefined>;\n}) {\n return (\n editor: BlockNoteEditor<any, any, any>,\n options: {\n idsSuffixed: boolean;\n withDelays: boolean;\n onBlockUpdate?: (blockId: string) => void;\n },\n ) => {\n const schema =\n typeof config.schema === \"function\"\n ? config.schema(editor)\n : config.schema;\n return streamTool<AddBlocksToolCall<T>>({\n name: \"add\",\n description: config.description,\n inputSchema: {\n type: \"object\",\n properties: {\n referenceId: {\n type: \"string\",\n description: \"MUST be an id of a block in the document\",\n },\n position: {\n type: \"string\",\n enum: [\"before\", \"after\"],\n description:\n \"`after` to add blocks AFTER (below) the block with `referenceId`, `before` to add the block BEFORE (above)\",\n },\n blocks: {\n items: schema.block,\n type: \"array\",\n },\n },\n required: [\"referenceId\", \"position\", \"blocks\"],\n $defs: schema.$defs,\n },\n validate: (operation) => {\n if (operation.type !== \"add\") {\n return {\n ok: false,\n error: \"invalid operation type\",\n };\n }\n\n if (operation.position !== \"before\" && operation.position !== \"after\") {\n return {\n ok: false,\n error: \"invalid position\",\n };\n }\n\n if (!operation.referenceId || !operation.blocks) {\n return {\n ok: false,\n error: \"referenceId and blocks are required\",\n };\n }\n\n let referenceId = operation.referenceId;\n if (options.idsSuffixed) {\n if (!referenceId?.endsWith(\"$\")) {\n return {\n ok: false,\n error: \"referenceId must end with $\",\n };\n }\n\n referenceId = referenceId.slice(0, -1);\n }\n\n const block = editor.getBlock(referenceId);\n\n if (!block) {\n return {\n ok: false,\n error: \"referenceId not found\",\n };\n }\n\n const validatedBlocksResult = validateBlockArray<T>(\n operation.blocks,\n (block) => config.validateBlock(block, editor),\n );\n\n if (!validatedBlocksResult.ok) {\n return validatedBlocksResult;\n }\n\n return {\n ok: true,\n value: {\n type: operation.type,\n referenceId,\n position: operation.position,\n blocks: validatedBlocksResult.value,\n },\n };\n },\n // Note: functionality mostly tested in jsontools.test.ts\n // would be nicer to add a direct unit test\n executor: () => {\n // An add operation has some complexity:\n // - it can add multiple blocks in 1 operation\n // (this is needed because you need an id as reference block - and if you want to insert multiple blocks you can only use an existing block as reference id)\n // - when streaming, the first time we encounter a block to add, it's an \"insert\" operation, but after that (i.e.: more characters are being streamed in)\n // it's an update operation (i.e.: update the previously added block)\n\n // keep track of added block ids to be able to update blocks that have already been added\n let addedBlockIds: string[] = [];\n\n const referenceIdMap: Record<string, string> = {}; // TODO: unit test\n\n return {\n execute: async (chunk, abortSignal?: AbortSignal) => {\n if (!chunk.isUpdateToPreviousOperation) {\n // we have a new operation, reset the added block ids\n addedBlockIds = [];\n }\n\n if (chunk.operation.type !== \"add\") {\n // pass through non-add operations\n return false;\n }\n\n const operation = chunk.operation as AddBlocksToolCall<T>;\n\n const jsonToolCall = await config.toJSONToolCall(editor, {\n ...chunk,\n operation,\n });\n\n if (!jsonToolCall) {\n return true;\n }\n\n if (\n chunk.isPossiblyPartial &&\n isEmptyParagraph(\n jsonToolCall.blocks[jsonToolCall.blocks.length - 1],\n )\n ) {\n // for example, a parsing just \"<ul>\" would first result in an empty paragraph,\n // wait for more content before adding the block\n return true;\n }\n\n for (let i = 0; i < jsonToolCall.blocks.length; i++) {\n const block = jsonToolCall.blocks[i];\n const tr = editor.prosemirrorState.tr;\n\n let agentSteps: AgentStep[] = [];\n if (i < addedBlockIds.length) {\n // we have already added this block, so we need to update it\n const tool = await config.rebaseTool(addedBlockIds[i], editor);\n const steps = updateToReplaceSteps(\n {\n id: addedBlockIds[i],\n block,\n },\n tool.doc,\n false,\n );\n\n const inverted = steps.map((step) => step.map(tool.invertMap)!);\n\n for (const step of inverted) {\n tr.step(step.map(tr.mapping)!);\n }\n agentSteps = getStepsAsAgent(tr);\n // don't spend time \"selecting\" the block as an agent, as we're continuing a previous update\n agentSteps = agentSteps.filter(\n (step) => step.type !== \"select\",\n );\n } else {\n // we are adding a new block, so we need to insert it\n const mappedReferenceId =\n operation.position === \"after\"\n ? referenceIdMap[operation.referenceId]\n : undefined;\n\n const ret = insertBlocks(\n tr,\n [block],\n i > 0\n ? addedBlockIds[i - 1]\n : mappedReferenceId || operation.referenceId,\n i > 0 ? \"after\" : operation.position,\n );\n addedBlockIds.push(...ret.map((r) => r.id));\n agentSteps = getStepsAsAgent(tr);\n }\n\n // if (agentSteps.find((step) => step.type === \"replace\")) {\n // throw new Error(\"unexpected: replace step in add operation\");\n // this is unexpected but we've been able to see this when:\n // adding a list item, because <ul> first gets parsed as paragraph, that then gets turned into a list\n // }\n\n for (const step of agentSteps) {\n if (abortSignal?.aborted) {\n throw new AbortError(\"Operation was aborted\");\n }\n if (options.withDelays) {\n await delayAgentStep(step);\n }\n editor.transact((tr) => {\n applyAgentStep(tr, step);\n });\n options.onBlockUpdate?.(addedBlockIds[i]);\n }\n }\n\n if (!chunk.isPossiblyPartial) {\n if (operation.position === \"after\") {\n referenceIdMap[operation.referenceId] =\n addedBlockIds[addedBlockIds.length - 1];\n }\n }\n\n return true;\n },\n };\n },\n });\n };\n}\n\nexport type AddBlocksToolCall<T> = {\n type: \"add\";\n referenceId: string;\n position: \"before\" | \"after\";\n blocks: T[];\n};\n","import { BlockNoteEditor, PartialBlock, trackPosition } from \"@blocknote/core\";\nimport type { JSONSchema7 } from \"json-schema\";\nimport { Transform } from \"prosemirror-transform\";\nimport {\n applyAgentStep,\n delayAgentStep,\n getStepsAsAgent,\n} from \"../../../prosemirror/agent.js\";\nimport { updateToReplaceSteps } from \"../../../prosemirror/changeset.js\";\nimport { RebaseTool } from \"../../../prosemirror/rebaseTool.js\";\nimport { Result, streamTool } from \"../../../streamTool/streamTool.js\";\nimport { AbortError } from \"../../../util/AbortError.js\";\n\nexport type UpdateBlockToolCall<T> = {\n type: \"update\";\n id: string;\n block: T;\n};\n\n/**\n * Factory function to create a StreamTool that Updates blocks in the document.\n */\nexport function createUpdateBlockTool<T>(config: {\n /**\n * The description of the tool\n */\n description: string;\n /**\n * The schema of the tool\n */\n schema:\n | {\n block: JSONSchema7;\n $defs?: JSONSchema7[\"$defs\"];\n }\n | ((editor: BlockNoteEditor<any, any, any>) => {\n block: JSONSchema7;\n $defs?: JSONSchema7[\"$defs\"];\n });\n /**\n * A function that can validate a block\n */\n validateBlock: (\n block: any,\n editor: BlockNoteEditor<any, any, any>,\n fallbackType?: string,\n ) => Result<T>;\n /**\n * The rebaseTool is used to get a projection of the document that\n * the JSON Tool Calls will be applied to. By using the rebaseTool we can\n * apply operations to a \"projected\" document, and then map them (rebase) to the actual document\n *\n * This is to:\n * - apply operations without suggestion-marks to an editor that has suggestions in it\n * (the projection should have the suggestions applied)\n * - apply operations from a format that doesn't support all Block features (e.g.: markdown)\n * (the projection should be the the BlockNote document without the unsupported features)\n */\n rebaseTool: (\n id: string,\n editor: BlockNoteEditor<any, any, any>,\n ) => Promise<RebaseTool>;\n /**\n * Converts the operation from `AddBlocksToolCall<T>` to `AddBlocksToolCall<PartialBlock<any, any, any>>`\n *\n * When using these factories to create a tool for a different format (e.g.: HTML / MD),\n * the `toJSONToolCall` function is used to convert the operation to a format that we can execute\n */\n toJSONToolCall: (\n editor: BlockNoteEditor<any, any, any>,\n chunk: {\n operation: UpdateBlockToolCall<T>;\n isUpdateToPreviousOperation: boolean;\n isPossiblyPartial: boolean;\n },\n ) => Promise<UpdateBlockToolCall<PartialBlock<any, any, any>> | undefined>;\n}) {\n return (\n editor: BlockNoteEditor<any, any, any>,\n options: {\n idsSuffixed: boolean;\n withDelays: boolean;\n updateSelection?: {\n from: number;\n to: number;\n };\n onBlockUpdate?: (blockId: string) => void;\n },\n ) => {\n const schema =\n typeof config.schema === \"function\"\n ? config.schema(editor)\n : config.schema;\n return streamTool<UpdateBlockToolCall<T>>({\n name: \"update\",\n description: config.description,\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"id of block to update\",\n },\n block: schema.block,\n },\n required: [\"id\", \"block\"],\n $defs: schema.$defs,\n },\n validate: (operation) => {\n if (operation.type !== \"update\") {\n return {\n ok: false,\n error: \"invalid operation type\",\n };\n }\n\n if (!operation.id) {\n return {\n ok: false,\n error: \"id is required\",\n };\n }\n\n let id = operation.id;\n if (options.idsSuffixed) {\n if (!id?.endsWith(\"$\")) {\n return {\n ok: false,\n error: \"id must end with $\",\n };\n }\n\n id = id.slice(0, -1);\n }\n\n if (!operation.block) {\n return {\n ok: false,\n error: \"block is required\",\n };\n }\n\n const block = editor.getBlock(id);\n\n if (!block) {\n // eslint-disable-next-line no-console\n console.error(\"BLOCK NOT FOUND\", id);\n return {\n ok: false,\n error: \"block not found\",\n };\n }\n\n const ret = config.validateBlock(operation.block, editor, block.type);\n\n if (!ret.ok) {\n return ret;\n }\n\n return {\n ok: true,\n value: {\n type: operation.type,\n id,\n block: ret.value,\n },\n };\n },\n // Note: functionality mostly tested in jsontools.test.ts\n // would be nicer to add a direct unit test\n executor: () => {\n const STEP_SIZE = 50;\n let minSize = STEP_SIZE;\n const selectionPositions = options.updateSelection\n ? {\n from: trackPosition(editor, options.updateSelection.from),\n to: trackPosition(editor, options.updateSelection.to),\n }\n : undefined;\n return {\n execute: async (chunk, abortSignal?: AbortSignal) => {\n if (chunk.operation.type !== \"update\") {\n // pass through non-update operations\n return false;\n }\n\n const operation = chunk.operation as UpdateBlockToolCall<T>;\n if (chunk.isPossiblyPartial) {\n const size = JSON.stringify(operation.block).length;\n if (size < minSize) {\n return true;\n } else {\n // increase minSize for next chunk\n minSize = size + STEP_SIZE;\n }\n } else {\n // reset for next chunk\n minSize = STEP_SIZE;\n }\n\n // REC: we could investigate whether we can use a single rebasetool across operations instead of\n // creating a new one every time (possibly expensive)\n const tool = await config.rebaseTool(operation.id, editor);\n\n const fromPos = selectionPositions\n ? tool.invertMap.invert().map(selectionPositions.from())\n : undefined;\n\n const toPos = selectionPositions\n ? tool.invertMap.invert().map(selectionPositions.to())\n : undefined;\n\n const jsonToolCall = await config.toJSONToolCall(editor, {\n ...chunk,\n operation,\n });\n if (!jsonToolCall) {\n return true;\n }\n\n const steps = updateToReplaceSteps(\n jsonToolCall,\n tool.doc,\n chunk.isPossiblyPartial,\n fromPos,\n toPos,\n );\n\n if (steps.length === 1 && chunk.isPossiblyPartial) {\n // when replacing a larger piece of text (try translating a 3 paragraph document), we want to do this as one single operation\n // we don't want to do this \"sentence-by-sentence\"\n\n // if there's only a single replace step to be done and we're partial, let's wait for more content\n\n // REC: unit test this and see if it's still needed even if we pass `dontReplaceContentAtEnd` to `updateToReplaceSteps`\n return true;\n }\n\n const inverted = steps.map((step) => step.map(tool.invertMap)!);\n\n const tr = new Transform(editor.prosemirrorState.doc);\n for (const step of inverted) {\n tr.step(step.map(tr.mapping)!);\n }\n const agentSteps = getStepsAsAgent(tr);\n\n for (const step of agentSteps) {\n if (abortSignal?.aborted) {\n throw new AbortError(\"Operation was aborted\");\n }\n if (options.withDelays) {\n await delayAgentStep(step);\n }\n editor.transact((tr) => {\n applyAgentStep(tr, step);\n });\n options.onBlockUpdate?.(operation.id);\n }\n return true;\n },\n };\n },\n });\n };\n}\n","import { BlockNoteEditor, removeAndInsertBlocks } from \"@blocknote/core\";\nimport {\n applyAgentStep,\n delayAgentStep,\n getStepsAsAgent,\n} from \"../../../prosemirror/agent.js\";\nimport { streamTool } from \"../../../streamTool/streamTool.js\";\n\n/**\n * Factory function to create a StreamTool that deletes a block from the document.\n */\nexport const deleteBlockTool = (\n editor: BlockNoteEditor<any, any, any>,\n options: {\n idsSuffixed: boolean;\n withDelays: boolean;\n onBlockUpdate?: (blockId: string) => void;\n },\n) =>\n streamTool<DeleteBlockToolCall>({\n name: \"delete\",\n description: \"Delete a block\",\n inputSchema: {\n type: \"object\",\n properties: {\n id: {\n type: \"string\",\n description: \"id of block to delete\",\n },\n },\n required: [\"id\"],\n },\n validate: (operation) => {\n if (operation.type !== \"delete\") {\n return {\n ok: false,\n error: \"invalid operation type\",\n };\n }\n\n if (!operation.id) {\n return {\n ok: false,\n error: \"id is required\",\n };\n }\n\n let id = operation.id;\n if (options.idsSuffixed) {\n if (!id?.endsWith(\"$\")) {\n return {\n ok: false,\n error: \"id must end with $\",\n };\n }\n\n id = id.slice(0, -1);\n }\n\n const block = editor.getBlock(id);\n\n if (!block) {\n return {\n ok: false,\n error: \"block not found\",\n };\n }\n\n return {\n ok: true,\n value: {\n type: \"delete\",\n id,\n },\n };\n },\n // Note: functionality mostly tested in jsontools.test.ts\n // would be nicer to add a direct unit test\n executor: () => {\n return {\n execute: async (chunk) => {\n if (chunk.operation.type !== \"delete\") {\n // pass through non-delete operations\n return false;\n }\n\n const operation = chunk.operation as DeleteBlockToolCall;\n\n const tr = editor.prosemirrorState.tr;\n\n removeAndInsertBlocks(tr, [operation.id], []);\n\n const agentSteps = getStepsAsAgent(tr);\n\n for (const step of agentSteps) {\n if (options.withDelays) {\n await delayAgentStep(step);\n }\n editor.transact((tr) => {\n applyAgentStep(tr, step);\n });\n options.onBlockUpdate?.(operation.id);\n }\n return true;\n },\n };\n },\n });\n\nexport type DeleteBlockToolCall = {\n type: \"delete\";\n id: string;\n};\n","/**\n * Completes partial HTML by parsing and correcting incomplete tags.\n * Examples:\n * <p>hello -> <p>hello</p>\n * <p>hello <sp -> <p>hello </p>\n * <p>hello <span -> <p>hello </p>\n * <p>hello <span> -> <p>hello <span></span></p>\n * <p>hello <span>world -> <p>hello <span>world</span></p>\n * <p>hello <span>world</span> -> <p>hello <span>world</span></p>\n *\n * @param html A potentially incomplete HTML string\n * @returns A properly formed HTML string with all tags closed\n */\nexport function getPartialHTML(html: string): string | undefined {\n // Simple check: if the last '<' doesn't have a matching '>',\n // then we have an incomplete tag at the end\n const lastOpenBracket = html.lastIndexOf(\"<\");\n const lastCloseBracket = html.lastIndexOf(\">\");\n\n // Handle incomplete tags by removing everything after the last complete tag\n let htmlToProcess = html;\n if (lastOpenBracket > lastCloseBracket) {\n htmlToProcess = html.substring(0, lastOpenBracket);\n // If nothing remains after removing the incomplete tag, return empty string\n if (!htmlToProcess.trim()) {\n return undefined;\n }\n }\n\n // if we're half-way through an entity tag that isn't closed, we need to remove the entity tag\n const match = htmlToProcess.match(/&[a-zA-Z0-9]*$/);\n if (match) {\n htmlToProcess = htmlToProcess.substring(\n 0,\n htmlToProcess.length - match[0].length,\n );\n }\n\n // Parse the HTML\n const parser = new DOMParser();\n const doc = parser.parseFromString(\n `<div>${htmlToProcess}</div>`,\n \"text/html\",\n );\n const el = doc.body.firstChild as HTMLElement;\n return el ? el.innerHTML : \"\";\n}\n","import { BlockNoteEditor } from \"@blocknote/core\";\nimport { applySuggestions } from \"@blocknote/prosemirror-suggest-changes\";\nimport { Transaction } from \"prosemirror-state\";\nimport { Transform } from \"prosemirror-transform\";\n\n// Helper function to get the transaction that removes all suggestions from the editor.\n//\n// (rebaseTool is usually used with a transaction that removes all suggestions from the editor)\nexport function getApplySuggestionsTr(editor: BlockNoteEditor<any, any, any>) {\n let applySuggestionsTr: Transaction;\n applySuggestions(editor.prosemirrorState, (tr) => {\n applySuggestionsTr = tr;\n });\n\n // @ts-ignore\n if (!applySuggestionsTr) {\n throw new Error(\"applySuggestionsTr is not set\");\n }\n\n return applySuggestionsTr;\n}\n\n/**\n * A helper function to enable rebasing prosemirror operations.\n *\n * The idea is as follows:\n * - There's an update U we want to apply to the editor state E\n * - However, the update U cannot be applied directly to E. For example, because E contains suggestions, or other\n * formatting incompatible with U\n * - We can however apply U to a \"clean\" document E', the projection (one that has no suggestions or other formatting)\n * - We can then use the inverse mapping of E' to E to get U' (the rebased update) which can be applied to E\n *\n * This function takes a `projectionTr`, which is the transaction that turns E into E'\n * It returns a helper object that can be used to rebase operations done to E' onto E\n */\nexport function rebaseTool(\n editor: BlockNoteEditor<any, any, any>,\n projectionTr: Transaction,\n) {\n const invertMap = projectionTr.mapping.invert();\n return {\n doc: projectionTr.doc,\n\n /**\n * Return a new transform that has the projection applied.\n * You can add new operations to this transform and later rebase those on the original document with `rebaseTr`\n */\n tr: () => {\n return new Transform(projectionTr.doc);\n },\n\n /**\n * Invert map created by the projection.\n * You can use this to map positions on the \"clean\" document (the projection) to positions on the original document\n */\n invertMap,\n\n /**\n * Return a new transaction based on the editor state with all the steps you made to `tr`.\n * These steps are rebased on the original document.\n */\n rebaseTr: (tr: Transform) => {\n if (tr.steps.length === 0) {\n throw new Error(\"No steps to apply\");\n }\n let rebasedTr = editor.prosemirrorState.tr;\n for (const step of tr.steps) {\n const mappedStep = step.map(invertMap);\n if (!mappedStep) {\n throw new Error(\"Step is not mapped\");\n }\n rebasedTr = rebasedTr.step(mappedStep);\n }\n return rebasedTr;\n },\n };\n}\n\nexport type RebaseTool = ReturnType<typeof rebaseTool>;\n","import { BlockNoteEditor, getBlock } from \"@blocknote/core\";\nimport { updateToReplaceSteps } from \"../../../../prosemirror/changeset.js\";\nimport {\n getApplySuggestionsTr,\n rebaseTool,\n} from \"../../../../prosemirror/rebaseTool.js\";\n\nexport async function createHTMLRebaseTool(\n id: string,\n editor: BlockNoteEditor<any, any, any>,\n) {\n const tr = getApplySuggestionsTr(editor);\n const block = getBlock(tr.doc, id);\n if (!block) {\n throw new Error(\"block not found\");\n }\n\n const html = await editor.blocksToHTMLLossy([\n {\n ...block,\n children: [],\n },\n ]);\n\n const initialMockID = (window as any).__TEST_OPTIONS?.mockID;\n\n const blocks = await editor.tryParseHTMLToBlocks(html);\n\n // hacky\n if ((window as any).__TEST_OPTIONS) {\n (window as Window & { __TEST_OPTIONS?: any }).__TEST_OPTIONS.mockID =\n initialMockID;\n }\n\n if (blocks.length !== 1) {\n throw new Error(\"html diff invalid block count\");\n }\n\n const htmlBlock = blocks[0];\n htmlBlock.id = id;\n\n const steps = updateToReplaceSteps(\n {\n id,\n block: htmlBlock,\n },\n tr.doc,\n );\n\n if (steps.length) {\n // console.error(\"html diff\", steps);\n throw new Error(\"html diff\");\n }\n\n return rebaseTool(editor, tr);\n}\n","import { Result } from \"../../../../streamTool/streamTool.js\";\n\nexport function validateBlockFunction(block: any): Result<string> {\n if (typeof block !== \"string\") {\n return {\n ok: false,\n error: \"block must be a string\",\n };\n }\n\n return {\n ok: true,\n value: block,\n };\n}\n","import { PartialBlock } from \"@blocknote/core\";\nimport {\n AddBlocksToolCall,\n createAddBlocksTool,\n} from \"../../base-tools/createAddBlocksTool.js\";\nimport {\n createUpdateBlockTool,\n UpdateBlockToolCall,\n} from \"../../base-tools/createUpdateBlockTool.js\";\nimport { deleteBlockTool } from \"../../base-tools/delete.js\";\nimport { getPartialHTML } from \"./getPartialHTML.js\";\nimport { createHTMLRebaseTool } from \"./rebaseTool.js\";\nimport { validateBlockFunction } from \"./validate.js\";\n\nexport const tools = {\n add: createAddBlocksTool<string>({\n description: \"Insert new blocks\",\n schema: {\n block: {\n type: \"string\",\n description: \"html of block (MUST be a single, VALID HTML element)\",\n },\n },\n validateBlock: validateBlockFunction,\n rebaseTool: createHTMLRebaseTool,\n toJSONToolCall: async (editor, chunk) => {\n const initialMockID = (window as any).__TEST_OPTIONS?.mockID;\n\n const blocks = (\n await Promise.all(\n chunk.operation.blocks.map(async (html) => {\n const parsedHtml = chunk.isPossiblyPartial\n ? getPartialHTML(html)\n : html;\n if (!parsedHtml) {\n return [];\n }\n return (await editor.tryParseHTMLToBlocks(parsedHtml)).map(\n (block) => {\n delete (block as any).id;\n return block;\n },\n );\n }),\n )\n ).flat();\n\n // hacky\n if ((window as any).__TEST_OPTIONS) {\n (window as Window & { __TEST_OPTIONS?: any }).__TEST_OPTIONS.mockID =\n initialMockID;\n }\n\n if (blocks.length === 0) {\n return undefined;\n }\n\n return {\n ...chunk.operation,\n blocks,\n } satisfies AddBlocksToolCall<PartialBlock<any, any, any>>;\n },\n }),\n update: createUpdateBlockTool<string>({\n description: \"Update a block\",\n schema: {\n block: {\n type: \"string\",\n description: \"html of block (MUST be a single HTML element)\",\n },\n },\n validateBlock: validateBlockFunction,\n rebaseTool: createHTMLRebaseTool,\n toJSONToolCall: async (editor, chunk) => {\n const html = chunk.isPossiblyPartial\n ? getPartialHTML(chunk.operation.block)\n : chunk.operation.block;\n\n if (!html) {\n return undefined;\n }\n\n const block = (await editor.tryParseHTMLToBlocks(html))[0];\n\n // console.log(\"update\", operation.block);\n // console.log(\"html\", html);\n // hacky\n if ((window as any).__TEST_OPTIONS) {\n (window as Window & { __TEST_OPTIONS?: any }).__TEST_OPTIONS.mockID =\n undefined;\n }\n\n delete (block as any).id;\n\n return {\n ...chunk.operation,\n block,\n } satisfies UpdateBlockToolCall<PartialBlock<any, any, any>>;\n },\n }),\n delete: deleteBlockTool,\n};\n","import { BlockNoteEditor } from \"@blocknote/core\";\nimport { StreamTool } from \"../../../streamTool/streamTool.js\";\nimport { makeDocumentStateBuilder } from \"../DocumentStateBuilder.js\";\nimport {\n StreamToolsConfig,\n StreamToolsProvider,\n StreamToolsResult,\n} from \"../formats.js\";\nimport { tools } from \"./tools/index.js\";\n\nfunction getStreamTools<\n T extends StreamToolsConfig = { add: true; update: true; delete: true },\n>(\n editor: BlockNoteEditor<any, any, any>,\n withDelays: boolean,\n defaultStreamTools?: T,\n selectionInfo?:\n | {\n from: number;\n to: number;\n }\n | boolean,\n onBlockUpdate?: (blockId: string) => void,\n): StreamToolsResult<string, T> {\n if (typeof selectionInfo === \"boolean\") {\n const selection = selectionInfo\n ? editor.getSelectionCutBlocks()\n : undefined;\n\n selectionInfo = selection\n ? {\n from: selection._meta.startPos,\n to: selection._meta.endPos,\n }\n : undefined;\n }\n\n const mergedStreamTools =\n defaultStreamTools ??\n ({\n add: true,\n update: true,\n delete: true,\n } as T);\n\n const streamTools: StreamTool<any>[] = [\n ...(mergedStreamTools.update\n ? [\n tools.update(editor, {\n idsSuffixed: true,\n withDelays,\n updateSelection: selectionInfo,\n onBlockUpdate,\n }),\n ]\n : []),\n ...(mergedStreamTools.add\n ? [tools.add(editor, { idsSuffixed: true, withDelays, onBlockUpdate })]\n : []),\n ...(mergedStreamTools.delete\n ? [tools.delete(editor, { idsSuffixed: true, withDelays, onBlockUpdate })]\n : []),\n ];\n\n return streamTools as StreamToolsResult<string, T>;\n}\n\nconst systemPrompt = `You're manipulating a text document using HTML blocks. \nMake sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $). \nList items are 1 block with 1 list item each, so block content \\`<ul><li>item1</li></ul>\\` is valid, but \\`<ul><li>item1</li><li>item2</li></ul>\\` is invalid. We'll merge them automatically.\nFor code blocks, you can use the \\`data-language\\` attribute on a <code> block (wrapped with <pre>) to specify the language.\n\nIf the user requests updates to the document, use the \"applyDocumentOperations\" tool to update the document.\n---\nIF there is no selection active in the latest state, first, determine what part of the document the user is talking about. You SHOULD probably take cursor info into account if needed.\n EXAMPLE: if user says \"below\" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor. \n EXAMPLE: If you want to insert content AT the cursor position (UNLESS indicated otherwise by the user), then you need \\`referenceId\\` to point to the block before the cursor with position \\`after\\` (or block below and \\`before\\`\n---\n `;\n\nexport const htmlBlockLLMFormat = {\n /**\n * Function to get the stream tools that can apply HTML block updates to the editor\n */\n getStreamToolsProvider: <\n T extends StreamToolsConfig = { add: true; update: true; delete: true },\n >(\n opts: { withDelays?: boolean; defaultStreamTools?: T } = {},\n ): StreamToolsProvider<string, T> => ({\n getStreamTools: (editor, selectionInfo, onBlockUpdate) => {\n return getStreamTools(\n editor,\n opts.withDelays ?? true,\n opts.defaultStreamTools,\n selectionInfo,\n onBlockUpdate,\n );\n },\n }),\n systemPrompt,\n tools,\n\n /**\n * The default DocumentStateBuilder that can take an editor and convert it to a document state that can be passed to the backend\n */\n defaultDocumentStateBuilder: makeDocumentStateBuilder(\n async (editor, block) => {\n return editor.blocksToHTMLLossy([block]);\n },\n ),\n};\n","import type { SimpleJSONObjectSchema } from \"./JSONSchema.js\";\n\n/**\n * Merges schemas that only differ by the \"type\" field.\n * @param schemas The array of schema objects to be processed.\n * @returns A new array with merged schema objects where applicable.\n */\nexport function mergeSchemas(\n schemas: SimpleJSONObjectSchema[],\n): SimpleJSONObjectSchema[] {\n const groupedSchemas: { [signature: string]: string[] } = {};\n const signatureToSchema: { [signature: string]: SimpleJSONObjectSchema } = {};\n\n schemas.forEach((schemaObj) => {\n // Extract the schema properties except for the \"type\" field\n const { type, ...rest } = schemaObj.properties;\n const schemaSignature = JSON.stringify(rest); // Generate a signature for comparison\n\n // If the signature already exists, add the \"type\" to the enum\n if (groupedSchemas[schemaSignature]) {\n groupedSchemas[schemaSignature].push(type.enum[0]);\n } else {\n // Create a new group if it doesn't exist\n groupedSchemas[schemaSignature] = [type.enum[0]];\n signatureToSchema[schemaSignature] = schemaObj;\n }\n });\n\n // Create the new merged schema array\n const mergedSchemas: SimpleJSONObjectSchema[] = Object.keys(\n groupedSchemas,\n ).map((signature) => {\n const baseSchema = signatureToSchema[signature];\n return {\n ...baseSchema,\n properties: {\n ...baseSchema.properties,\n type: {\n type: \"string\",\n enum: groupedSchemas[signature],\n },\n },\n };\n });\n\n return mergedSchemas;\n}\n\n// // Example usage:\n// const exampleSchemas: Schema[] = [\n// {\n// type: \"object\",\n// properties: {\n// type: { type: \"string\", enum: [\"paragraph\"] },\n// content: { $ref: \"#/$defs/inlinecontent\" },\n// props: {\n// type: \"object\",\n// properties: {\n// backgroundColor: { type: \"string\" },\n// textColor: { type: \"string\" },\n// textAlignment: {\n// type: \"string\",\n// enum: [\"left\", \"center\", \"right\", \"justify\"],\n// },\n// },\n// additionalProperties: false,\n// },\n// },\n// additionalProperties: false,\n// required: [\"type\"],\n// },\n// {\n// type: \"object\",\n// properties: {\n// type: { type: \"string\", enum: [\"bulletListItem\"] },\n// content: { $ref: \"#/$defs/inlinecontent\" },\n// props: {\n// type: \"object\",\n// properties: {\n// backgroundColor: { type: \"string\" },\n// textColor: { type: \"string\" },\n// textAlignment: {\n// type: \"string\",\n// enum: [\"left\", \"center\", \"right\", \"justify\"],\n// },\n// },\n// additionalProperties: false,\n// },\n// },\n// additionalProperties: false,\n// required: [\"type\"],\n// },\n// {\n// type: \"object\",\n// properties: {\n// type: { type: \"string\", enum: [\"heading\"] },\n// content: { $ref: \"#/$defs/inlinecontent\" },\n// props: {\n// type: \"object\",\n// properties: {\n// backgroundColor: { type: \"string\" },\n// textColor: { type: \"string\" },\n// textAlignment: {\n// type: \"string\",\n// enum: [\"left\", \"center\", \"right\", \"justify\"],\n// },\n// level: {\n// type: \"number\",\n// enum: [1, 2, 3],\n// },\n// },\n// additionalProperties: false,\n// },\n// },\n// additionalProperties: false,\n// required: [\"type\"],\n// },\n// ];\n\n// const mergedSchemas = mergeSchemas(exampleSchemas);\n// console.log(JSON.stringify(mergedSchemas, null, 2));\n","import {\n BlockNoteSchema,\n BlockSchema,\n InlineContentSchema,\n PropSchema,\n StyleSchema,\n defaultProps,\n} from \"@blocknote/core\";\nimport { SimpleJSONObjectSchema } from \"./JSONSchema.js\";\nimport { mergeSchemas } from \"./mergeSchema.js\";\n/*\n{\n \"$schema\": \"http://json-schema.org/draft-07/schema#\",\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"id\": {\n \"type\": \"string\",\n \"format\": \"uuid\"\n },\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\"paragraph\", \"heading\"]\n },\n \"props\": {\n \"type\": \"object\",\n \"properties\": {\n \"textColor\": {\n \"type\": \"string\",\n \"enum\": [\"default\"]\n },\n \"backgroundColor\": {\n \"type\": \"string\",\n \"enum\": [\"default\"]\n },\n \"textAlignment\": {\n \"type\": \"string\",\n \"enum\": [\"left\"]\n },\n \"level\": {\n \"type\": \"integer\",\n \"minimum\": 1,\n \"maximum\": 6\n }\n },\n \"required\": [\"textColor\", \"backgroundColor\", \"textAlignment\"],\n \"additionalProperties\": false\n },\n \"content\": {\n \"type\": \"array\",\n \"items\": {\n \"type\": \"object\",\n \"properties\": {\n \"type\": {\n \"type\": \"string\",\n \"enum\": [\"text\"]\n },\n \"text\": {\n \"type\": \"string\"\n },\n \"styles\": {\n \"type\": \"object\",\n \"properties\": {\n \"bold\": {\n \"type\": \"boolean\"\n },\n \"italic\": {\n \"type\": \"boolean\"\n }\n },\n \"additionalProperties\": false\n }\n },\n \"required\": [\"type\", \"text\"],\n \"additionalProperties\": false\n }\n }\n },\n \"required\": [\"id\", \"type\", \"props\", \"content\"],\n \"additionalProperties\": false\n }\n }*/\n\nfunction styleSchemaToJSONSchema(schema: StyleSchema): SimpleJSONObjectSchema {\n return {\n type: \"object\",\n properties: Object.fromEntries(\n Object.entries(schema).map(([key, val]) => {\n return [\n key,\n {\n type: val.propSchema,\n },\n ];\n }),\n ),\n additionalProperties: false,\n };\n}\n\nfunction styledTextToJSONSchema() {\n return {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n enum: [\"text\"],\n },\n text: {\n type: \"string\",\n },\n styles: {\n $ref: \"#/$defs/styles\",\n },\n },\n additionalProperties: false,\n required: [\"type\", \"text\"],\n };\n}\n\nexport function propSchemaToJSONSchema(\n propSchema: PropSchema,\n): SimpleJSONObjectSchema {\n return {\n type: \"object\",\n properties: Object.fromEntries(\n Object.entries(propSchema)\n .filter(([_key, val]) => {\n // for now skip optional props\n return val.default !== undefined;\n //&& key !== \"language\";\n })\n .map(([key, val]) => {\n return [\n key,\n {\n type: typeof val.default,\n enum: val.values,\n },\n ];\n }),\n ),\n additionalProperties: false,\n };\n}\n\nfunction inlineContentSchemaToJSONSchema(schema: InlineContentSchema) {\n return {\n type: \"array\",\n items: {\n anyOf: Object.entries(schema).map(([_key, val]) => {\n if (val === \"text\") {\n return {\n $ref: \"#/$defs/styledtext\",\n };\n }\n if (val === \"link\") {\n return {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n enum: [\"link\"],\n },\n content: {\n type: \"array\",\n items: {\n $ref: \"#/$defs/styledtext\",\n },\n },\n href: {\n type: \"string\",\n },\n },\n additionalProperties: false,\n required: [\"type\", \"href\", \"content\"],\n };\n }\n return {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n enum: [val.type],\n },\n content:\n val.content === \"styled\"\n ? {\n type: \"array\",\n items: {\n $ref: \"#/$defs/styledtext\",\n },\n }\n : undefined,\n props: propSchemaToJSONSchema(val.propSchema),\n },\n additionalProperties: false,\n required: [\"type\", ...(val.content === \"styled\" ? [\"content\"] : [])],\n };\n }),\n },\n };\n}\n\nfunction blockSchemaToJSONSchema(schema: BlockSchema) {\n return {\n anyOf: mergeSchemas(\n Object.entries(schema).map(([_key, val]) => {\n return {\n type: \"object\",\n properties: {\n type: {\n type: \"string\",\n enum: [val.type],\n },\n content:\n val.content === \"inline\"\n ? { $ref: \"#/$defs/inlinecontent\" }\n : val.content === \"table\"\n ? { type: \"object\", properties: {} } // TODO\n : undefined,\n // filter out default props (TODO: make option)\n props: propSchemaToJSONSchema(val.propSchema),\n // Object.fromEntries(\n // Object.entries(val.propSchema).filter(\n // (key) => typeof (defaultProps as any)[key[0]] === \"undefined\"\n // )\n // )\n // ),\n },\n additionalProperties: false,\n required: [\"type\"], //, ...(val.content === \"inline\" ? [\"content\"] : [])],\n };\n }),\n ),\n };\n}\n\ntype Writeable<T> = { -readonly [P in keyof T]: T[P] };\n\nfunction schemaOps(\n schema: BlockNoteSchema<BlockSchema, InlineContentSchema, StyleSchema>,\n) {\n const clone: Writeable<typeof schema> = JSON.parse(\n JSON.stringify({\n blockSchema: schema.blockSchema,\n inlineContentSchema: schema.inlineContentSchema,\n styleSchema: schema.styleSchema,\n }),\n );\n return {\n // TODO\n removeFileBlocks() {\n clone.blockSchema = Object.fromEntries(\n Object.entries(clone.blockSchema).filter(\n ([_key, val]) =>\n !schema.blockSpecs[val.type].implementation.meta?.fileBlockAccept,\n ),\n );\n return this;\n },\n removeDefaultProps() {\n clone.blockSchema = Object.fromEntries(\n Object.entries(clone.blockSchema).map(([key, val]) => {\n return [\n key,\n {\n ...val,\n propSchema: Object.fromEntries(\n Object.entries(val.propSchema).filter(\n (key) => typeof (defaultProps as any)[key[0]] === \"undefined\",\n ),\n ) as any,\n },\n ];\n }),\n );\n return this;\n },\n\n get() {\n return clone;\n },\n };\n}\n\nexport function blockNoteSchemaToJSONSchema(\n schema: BlockNoteSchema<any, any, any>,\n) {\n schema = schemaOps(schema)\n .removeFileBlocks()\n .removeDefaultProps()\n .get() as BlockNoteSchema<BlockSchema, InlineContentSchema, StyleSchema>;\n return {\n $defs: {\n styles: styleSchemaToJSONSchema(schema.styleSchema),\n styledtext: styledTextToJSONSchema(),\n inlinecontent: inlineContentSchemaToJSONSchema(\n schema.inlineContentSchema,\n ),\n block: blockSchemaToJSONSchema(schema.blockSchema),\n },\n };\n}\n","import {\n BlockNoteEditor,\n PartialBlock,\n isLinkInlineContent,\n isStyledTextInlineContent,\n} from \"@blocknote/core\";\nimport { Result } from \"../../../../streamTool/streamTool.js\";\n\nfunction validateInlineContent(content: any, editor: any): boolean {\n const inlineContentConfig =\n editor.schema.inlineContentSchema[\n content.type as keyof typeof editor.schema.inlineContentSchema\n ];\n\n if (!inlineContentConfig) {\n return false;\n }\n\n if (isStyledTextInlineContent(content)) {\n if (!(\"text\" in content)) {\n return false;\n }\n }\n\n if (isLinkInlineContent(content)) {\n if (!(\"content\" in content) || !(\"href\" in content)) {\n return false;\n }\n\n return validateInlineContent(content.content, editor);\n }\n\n // TODO: custom ic content\n return true;\n}\n\nexport function validateBlockFunction(\n block: any,\n editor: BlockNoteEditor<any, any, any>,\n fallbackType?: string,\n): Result<PartialBlock<any, any, any>> {\n const type = block.type || fallbackType;\n const blockConfig =\n editor.schema.blockSchema[type as keyof typeof editor.schema.blockSchema];\n\n if (!blockConfig) {\n return {\n ok: false,\n error: \"block type not found in editor\",\n };\n }\n\n if (block.children) {\n // LLM tools are not supposed to edit children at this moment\n // return false; TODO, bringing this back breaks markdown tests\n }\n\n if (blockConfig.content === \"none\") {\n if (block.content) {\n // no content expected for this block\n return {\n ok: false,\n error: \"block content not expected for this block type\",\n };\n }\n } else {\n if (!block.content) {\n // return false;\n return {\n ok: true,\n value: block,\n };\n }\n\n if (!Array.isArray(block.content)) {\n // content expected for this block\n return {\n ok: false,\n error: \"block content must be an array\",\n };\n }\n\n if (blockConfig.content === \"table\") {\n // no validation for table content (TODO)\n return {\n ok: true,\n value: block,\n };\n }\n\n if (\n !(block.content as []).every((content: any) => {\n return validateInlineContent(content, editor);\n })\n ) {\n return {\n ok: false,\n error: \"block content must be an array of inline content\",\n };\n }\n }\n // TODO: validate props\n return {\n ok: true,\n value: block,\n };\n}\n","import { defaultProps, type PartialBlock } from \"@blocknote/core\";\nimport {\n getApplySuggestionsTr,\n rebaseTool,\n} from \"../../../../prosemirror/rebaseTool.js\";\nimport { blockNoteSchemaToJSONSchema } from \"../../../schema/schemaToJSONSchema.js\";\nimport { createAddBlocksTool } from \"../../base-tools/createAddBlocksTool.js\";\nimport { createUpdateBlockTool } from \"../../base-tools/createUpdateBlockTool.js\";\nimport { deleteBlockTool } from \"../../base-tools/delete.js\";\nimport { validateBlockFunction } from \"./validate.js\";\n\nexport const tools = {\n add: createAddBlocksTool<PartialBlock<any, any, any>>({\n description: \"Insert new blocks\",\n schema: (editor) => ({\n block: {\n $ref: \"#/$defs/block\",\n },\n ...(blockNoteSchemaToJSONSchema(editor.schema) as any),\n }),\n validateBlock: validateBlockFunction,\n rebaseTool: async (_id, editor) =>\n rebaseTool(editor, getApplySuggestionsTr(editor)),\n toJSONToolCall: async (_editor, chunk) => {\n return chunk.operation;\n },\n }),\n update: createUpdateBlockTool<PartialBlock<any, any, any>>({\n description:\n \"Update a block, the new block will replace the existing block.\",\n schema: (editor) => ({\n block: {\n $ref: \"#/$defs/block\",\n },\n ...(blockNoteSchemaToJSONSchema(editor.schema) as any),\n }),\n validateBlock: validateBlockFunction,\n rebaseTool: async (_id, editor) =>\n rebaseTool(editor, getApplySuggestionsTr(editor)),\n toJSONToolCall: async (_editor, chunk) => {\n const defaultPropsVals = Object.fromEntries(\n Object.entries(defaultProps).map(([key, val]) => {\n return [key, val.default];\n }),\n );\n\n return {\n ...chunk.operation,\n block: {\n ...chunk.operation.block,\n props: {\n ...defaultPropsVals,\n ...chunk.operation.block.props,\n },\n },\n };\n },\n }),\n delete: deleteBlockTool,\n};\n\nexport type Tools = ReturnType<(typeof tools)[keyof typeof tools]>;\n","import { BlockNoteEditor } from \"@blocknote/core\";\nimport { StreamTool } from \"../../../streamTool/streamTool.js\";\n\nimport { tools } from \"./tools/index.js\";\n\n// Import the tool call types\nimport { StreamToolsProvider } from \"../../index.js\";\n\nimport {\n makeDocumentStateBuilder,\n StreamToolsConfig,\n StreamToolsResult,\n} from \"../index.js\";\n\nfunction getStreamTools<\n T extends StreamToolsConfig = { add: true; update: true; delete: true },\n>(\n editor: BlockNoteEditor<any, any, any>,\n withDelays: boolean,\n defaultStreamTools?: T,\n selectionInfo?:\n | {\n from: number;\n to: number;\n }\n | boolean,\n onBlockUpdate?: (blockId: string) => void,\n): StreamToolsResult<string, T> {\n if (typeof selectionInfo === \"boolean\") {\n const selection = selectionInfo\n ? editor.getSelectionCutBlocks()\n : undefined;\n\n selectionInfo = selection\n ? {\n from: selection._meta.startPos,\n to: selection._meta.endPos,\n }\n : undefined;\n }\n\n const mergedStreamTools =\n defaultStreamTools ??\n ({\n add: true,\n update: true,\n delete: true,\n } as T);\n\n const streamTools: StreamTool<any>[] = [\n ...(mergedStreamTools.update\n ? [\n tools.update(editor, {\n idsSuffixed: true,\n withDelays,\n updateSelection: selectionInfo,\n onBlockUpdate,\n }),\n ]\n : []),\n ...(mergedStreamTools.add\n ? [tools.add(editor, { idsSuffixed: true, withDelays, onBlockUpdate })]\n : []),\n ...(mergedStreamTools.delete\n ? [tools.delete(editor, { idsSuffixed: true, withDelays, onBlockUpdate })]\n : []),\n ];\n\n return streamTools as StreamToolsResult<string, T>;\n}\n\nconst systemPrompt = `You're manipulating a text document using JSON blocks. \nMake sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $). \n\nIf the user requests updates to the document, use the \"applyDocumentOperations\" tool to update the document.\n---\nIF there is no selection active in the latest state, first, determine what part of the document the user is talking about. You SHOULD probably take cursor info into account if needed.\n EXAMPLE: if user says \"below\" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor. \n EXAMPLE: If you want to insert content AT the cursor position (UNLESS indicated otherwise by the user), then you need \\`referenceId\\` to point to the block before the cursor with position \\`after\\` (or block below and \\`before\\`\n---\n `;\n\nexport const jsonBlockLLMFormat = {\n /**\n * Function to get the stream tools that can apply JSON block updates to the editor\n */\n getStreamToolsProvider: <\n T extends StreamToolsConfig = { add: true; update: true; delete: true },\n >(\n opts: { withDelays?: boolean; defaultStreamTools?: T } = {},\n ): StreamToolsProvider<string, T> => ({\n getStreamTools: (editor, selectionInfo, onBlockUpdate) => {\n return getStreamTools(\n editor,\n opts.withDelays ?? true,\n opts.defaultStreamTools,\n selectionInfo,\n onBlockUpdate,\n );\n },\n }),\n\n tools,\n systemPrompt,\n defaultDocumentStateBuilder: makeDocumentStateBuilder(\n async (_editor, block) => {\n return {\n ...block,\n id: undefined, // don't pass id, because LLM should use `jsonSelectedBlocks` for this\n children: undefined,\n };\n },\n ),\n};\n","import { BlockNoteEditor, getBlock } from \"@blocknote/core\";\nimport { Mapping } from \"prosemirror-transform\";\nimport { updateToReplaceSteps } from \"../../../../prosemirror/changeset.js\";\nimport {\n getApplySuggestionsTr,\n rebaseTool,\n} from \"../../../../prosemirror/rebaseTool.js\";\n\nexport async function createMDRebaseTool(\n id: string,\n editor: BlockNoteEditor<any, any, any>,\n) {\n const tr = getApplySuggestionsTr(editor);\n const md = await editor.blocksToMarkdownLossy([getBlock(tr.doc, id)!]);\n const blocks = await editor.tryParseMarkdownToBlocks(md);\n\n const steps = updateToReplaceSteps(\n {\n id,\n block: blocks[0],\n },\n tr.doc,\n );\n\n const stepMapping = new Mapping();\n for (const step of steps) {\n const mapped = step.map(stepMapping);\n if (!mapped) {\n throw new Error(\"Failed to map step\");\n }\n tr.step(mapped);\n stepMapping.appendMap(mapped.getMap());\n }\n return rebaseTool(editor, tr);\n}\n","import { Result } from \"../../../../streamTool/streamTool.js\";\n\nexport function validateBlockFunction(block: any): Result<string> {\n if (typeof block !== \"string\") {\n return {\n ok: false,\n error: \"block must be a string\",\n };\n }\n\n return {\n ok: true,\n value: block,\n };\n}\n","import { PartialBlock } from \"@blocknote/core\";\nimport {\n AddBlocksToolCall,\n createAddBlocksTool,\n} from \"../../base-tools/createAddBlocksTool.js\";\nimport {\n createUpdateBlockTool,\n UpdateBlockToolCall,\n} from \"../../base-tools/createUpdateBlockTool.js\";\nimport { deleteBlockTool } from \"../../base-tools/delete.js\";\nimport { createMDRebaseTool } from \"./rebaseTool.js\";\nimport { validateBlockFunction } from \"./validate.js\";\n\nexport const tools = {\n add: createAddBlocksTool<string>({\n description: \"Insert new blocks\",\n schema: {\n block: {\n $ref: \"#/$defs/block\",\n },\n $defs: {\n block: { type: \"string\", description: \"markdown of block\" },\n },\n },\n validateBlock: validateBlockFunction,\n rebaseTool: createMDRebaseTool,\n toJSONToolCall: async (editor, chunk) => {\n const blocks = await Promise.all(\n chunk.operation.blocks.map(async (md) => {\n const block = (await editor.tryParseMarkdownToBlocks(md.trim()))[0]; // TODO: trim\n delete (block as any).id;\n return block;\n }),\n );\n\n // hacky\n if ((window as any).__TEST_OPTIONS) {\n (window as Window & { __TEST_OPTIONS?: any }).__TEST_OPTIONS.mockID =\n undefined;\n }\n\n return {\n ...chunk.operation,\n blocks,\n } satisfies AddBlocksToolCall<PartialBlock<any, any, any>>;\n },\n }),\n update: createUpdateBlockTool<string>({\n description:\n \"Update a block, the new block will replace the existing block.\",\n schema: {\n block: {\n $ref: \"#/$defs/block\",\n },\n $defs: {\n block: { type: \"string\", description: \"markdown of block\" },\n },\n },\n validateBlock: validateBlockFunction,\n rebaseTool: createMDRebaseTool,\n toJSONToolCall: async (editor, chunk) => {\n const block = (\n await editor.tryParseMarkdownToBlocks(chunk.operation.block.trim())\n )[0];\n\n delete (block as any).id;\n // console.log(\"update\", operation.block);\n // console.log(\"md\", block);\n // hacky\n if ((window as any).__TEST_OPTIONS) {\n (window as Window & { __TEST_OPTIONS?: any }).__TEST_OPTIONS.mockID =\n undefined;\n }\n\n return {\n ...chunk.operation,\n block,\n } satisfies UpdateBlockToolCall<PartialBlock<any, any, any>>;\n },\n }),\n delete: deleteBlockTool,\n};\n","import { BlockNoteEditor } from \"@blocknote/core\";\nimport { StreamTool } from \"../../../streamTool/streamTool.js\";\n\nimport { tools } from \"./tools/index.js\";\n\n// Import the tool call types\nimport { StreamToolsProvider } from \"../../index.js\";\n\nimport {\n makeDocumentStateBuilder,\n StreamToolsConfig,\n StreamToolsResult,\n} from \"../index.js\";\n\nfunction getStreamTools<\n T extends StreamToolsConfig = { add: true; update: true; delete: true },\n>(\n editor: BlockNoteEditor<any, any, any>,\n withDelays: boolean,\n defaultStreamTools?: T,\n selectionInfo?:\n | {\n from: number;\n to: number;\n }\n | boolean,\n onBlockUpdate?: (blockId: string) => void,\n): StreamToolsResult<string, T> {\n if (typeof selectionInfo === \"boolean\") {\n const selection = selectionInfo\n ? editor.getSelectionCutBlocks()\n : undefined;\n\n selectionInfo = selection\n ? {\n from: selection._meta.startPos,\n to: selection._meta.endPos,\n }\n : undefined;\n }\n\n const mergedStreamTools =\n defaultStreamTools ??\n ({\n add: true,\n update: true,\n delete: true,\n } as T);\n\n const streamTools: StreamTool<any>[] = [\n ...(mergedStreamTools.update\n ? [\n tools.update(editor, {\n idsSuffixed: true,\n withDelays,\n updateSelection: selectionInfo,\n onBlockUpdate,\n }),\n ]\n : []),\n ...(mergedStreamTools.add\n ? [tools.add(editor, { idsSuffixed: true, withDelays, onBlockUpdate })]\n : []),\n ...(mergedStreamTools.delete\n ? [tools.delete(editor, { idsSuffixed: true, withDelays, onBlockUpdate })]\n : []),\n ];\n\n return streamTools as StreamToolsResult<string, T>;\n}\n\nconst systemPrompt = `You're manipulating a text document using Markdown blocks. \nMake sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $). \nList items are 1 block with 1 list item each, so block content \\`- item1\\` is valid, but \\`- item1\\n- item2\\` is invalid. We'll merge them automatically.\n\nIf the user requests updates to the document, use the \"applyDocumentOperations\" tool to update the document.\n---\nIF there is no selection active in the latest state, first, determine what part of the document the user is talking about. You SHOULD probably take cursor info into account if needed.\n EXAMPLE: if user says \"below\" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor. \n EXAMPLE: If you want to insert content AT the cursor position (UNLESS indicated otherwise by the user), then you need \\`referenceId\\` to point to the block before the cursor with position \\`after\\` (or block below and \\`before\\`\n---\n `;\n\nexport const markdownBlockLLMFormat = {\n /**\n * Function to get the stream tools that can apply Markdown block updates to the editor\n */\n getStreamToolsProvider: <\n T extends StreamToolsConfig = { add: true; update: true; delete: true },\n >(\n opts: { withDelays?: boolean; defaultStreamTools?: T } = {},\n ): StreamToolsProvider<string, T> => ({\n getStreamTools: (editor, selectionInfo, onBlockUpdate) => {\n return getStreamTools(\n editor,\n opts.withDelays ?? true,\n opts.defaultStreamTools,\n selectionInfo,\n onBlockUpdate,\n );\n },\n }),\n systemPrompt,\n tools,\n\n defaultDocumentStateBuilder: makeDocumentStateBuilder(\n async (editor, block) => {\n return editor.blocksToMarkdownLossy([block]);\n },\n ),\n};\n","import { BlockNoteEditor } from \"@blocknote/core\";\nimport { StreamTool } from \"../../streamTool/streamTool.js\";\nimport { AddBlocksToolCall } from \"./base-tools/createAddBlocksTool.js\";\nimport { UpdateBlockToolCall } from \"./base-tools/createUpdateBlockTool.js\";\nimport { DeleteBlockToolCall } from \"./base-tools/delete.js\";\nimport { DocumentStateBuilder } from \"./DocumentStateBuilder.js\";\nimport { htmlBlockLLMFormat } from \"./html-blocks/htmlBlocks.js\";\nimport { jsonBlockLLMFormat } from \"./json/json.js\";\nimport { markdownBlockLLMFormat } from \"./markdown-blocks/markdownBlocks.js\";\n\n// Define the tool types\nexport type AddTool<T> = StreamTool<AddBlocksToolCall<T>>;\nexport type UpdateTool<T> = StreamTool<UpdateBlockToolCall<T>>;\nexport type DeleteTool = StreamTool<DeleteBlockToolCall>;\n\n// Create a conditional type that maps boolean flags to tool types\nexport type StreamToolsConfig = {\n add?: boolean;\n update?: boolean;\n delete?: boolean;\n};\n\nexport type StreamToolsResult<TT, T extends StreamToolsConfig> = [\n ...(T extends { update: true } ? [UpdateTool<TT>] : []),\n ...(T extends { add: true } ? [AddTool<TT>] : []),\n ...(T extends { delete: true } ? [DeleteTool] : []),\n];\n\nexport type StreamToolsProvider<\n TT,\n T extends StreamToolsConfig = { add: true; update: true; delete: true },\n> = {\n getStreamTools: (\n editor: BlockNoteEditor<any, any, any>,\n selectionInfo?:\n | {\n from: number;\n to: number;\n }\n | boolean,\n onBlockUpdate?: (blockId: string) => void,\n ) => StreamToolsResult<TT, T>;\n};\n\ntype AIDocumentFormat<TT> = {\n /**\n * Function to get the stream tools that can apply HTML block updates to the editor\n */\n getStreamToolsProvider: <T extends StreamToolsConfig>(opts: {\n withDelays?: boolean;\n defaultStreamTools?: T;\n }) => StreamToolsProvider<TT, T>;\n\n systemPrompt: string;\n defaultDocumentStateBuilder: DocumentStateBuilder<any>;\n};\n\nexport const aiDocumentFormats = {\n _experimental_json: jsonBlockLLMFormat,\n _experimental_markdown: markdownBlockLLMFormat,\n html: htmlBlockLLMFormat,\n} satisfies Record<string, AIDocumentFormat<any>>;\n","import { addCursorPosition } from \"./addCursorPosition.js\";\nimport { convertBlocks } from \"./convertBlocks.js\";\nimport { flattenBlocks } from \"./flattenBlocks.js\";\nimport { suffixIDs } from \"./suffixIds.js\";\nimport { trimEmptyBlocks } from \"./trimEmptyBlocks.js\";\n\nexport const promptHelpers = {\n addCursorPosition,\n flattenBlocks,\n suffixIDs,\n trimEmptyBlocks,\n convertBlocks,\n};\n","import type { BlockNoteEditor } from \"@blocknote/core\";\nimport type { en } from \"./locales\";\n\nexport function getAIDictionary(editor: BlockNoteEditor<any, any, any>) {\n if (!(editor.dictionary as any).ai) {\n throw new Error(\"AI dictionary not found\");\n }\n return (editor.dictionary as any).ai as AIDictionary;\n}\n\nexport type AIDictionary = typeof en;\n","export const fetchViaProxy =\n (getUrl: (url: string) => string) =>\n async (input: string | URL | Request, init?: RequestInit) => {\n const request = new Request(input, init);\n\n // console.log(\"fetchViaProxy\", baseURL, provider, request);\n const url = getUrl(request.url);\n const newRequest = new Request(url, {\n headers: request.headers,\n // if we just pass request.body, it's a readablestream which is not visible in chrome inspector,\n // so use init?.body instead if it's available to make debugging easier\n body: init?.body || request.body,\n method: request.method,\n duplex: \"half\",\n } as any);\n\n const resp = await fetch(newRequest);\n return resp;\n };\n"],"names":["isEmptyParagraph","block","trimArray","arr","matchFn","trimStart","trimEnd","start","end","trimEmptyBlocks","source","opts","buildAIRequest","useSelection","deleteEmptyCursorBlock","streamToolsProvider","documentStateBuilder","onStart","aiDocumentFormats","cursorBlock","emptyCursorBlockToDelete","selectionInfo","streamTools","ret","streamToolToJSONSchema","tool","properties","required","$defs","rest","createStreamToolsArraySchema","schemas","schema","key","isEqual","streamToolsToToolSet","jsonSchema","ChunkExecutionError","message","chunk","options","__publicField","StreamToolExecutor","abortSignal","lastParsedResult","stream","controller","operation","partialJsonToOperation","secondTransform","internalReadable","externalReadable","finishPromise","executors","handled","executor","error","getErrorMessage","_a","operationType","_b","writer","parsed","parsePartialJson","isUpdateToPreviousOperation","func","f","validated","injectDocumentStateMessages","messages","documentState","partialObjectStreamAsToolCallInUIMessageStream","toolName","accumulatedString","_exhaustiveCheck","objectAsToolCallInUIMessageStream","object","toolSetToToolDefinitions","toolSet","name","asSchema","toolDefinitionsToToolSet","toolDefinitions","definition","PROVIDER_OVERRIDES","getProviderOverrides","model","ClientSideTransport","tools","_additionalOptions","generateObject","convertToModelMessages","streamObject","streamText","body","createAppendableStream","ready","canceled","onCancel","cancelPromise","_","reject","output","reason","append","readable","reader","done","value","e","finalize","asyncIterableToStream","iterable","result","createAsyncIterableStream","createAsyncIterableStreamFromAsyncIterable","filterNewOrUpdatedOperations","partialObjectStream","metadata","numOperationsAppliedCompletely","first","lastOp","i","filterValidOperations","operationsStream","onInvalidOperation","forceNewOperation","toValidatedOperations","preprocessOperationsStreaming","validatedOperationsStream","objectStreamToOperationsResult","chunkMetadata","setupToolCallStreaming","chat","appendableStream","pipeToPromise","toolCallStreams","unsub","processToolCallParts","data","toolCallStreamData","createToolCallStream","resolve","unsub2","unsub3","results","errorSeen","toolCalls","toolCall","index","isErrorTool","getToolCallStreamData","part","isToolUIPart","toolCallId","toolCallData","processToolCallPart","input","sendMessageWithAIRequest","aiRequest","sendingMessage","merge","toolCallProcessing","addCursorPosition","editor","cursorPosition","isBlockWithCursor","convertBlocks","mapFn","flattenBlocks","suffixIDs","el","makeDocumentStateBuilder","convertBlockFn","getDocumentStateWithSelection","getDocumentStateNoSelection","isEmptyDocument","cursorBlockId","blockArray","filtered","b","suffixed","getFirstChar","fragment","found","n","pos","getStepsAsAgent","inputTr","pmSchema","getPmSchema","modification","agentSteps","tr","Transform","step","invertMap","Mapping","ReplaceStep","ReplaceAroundStep","from","newNode","oldNode","marks","attrNames","attr","stepIndex","to","sliceTextContent","alreadyHasSameText","sliceTo","firstCharIndex","replaceEnd","replaceFrom","isReplacing","$pos","replacement","Slice","node","sel","TextSelection","delayAgentStep","jitter","UnreachableCaseError","applyAgentStep","pmStep","addMissingChanges","changes","originalDoc","expectedDoc","change","diffStart","expectedNode","actualNode","isNodeAttrChange","length","fromA","toA","insertPos","newDiffStart","createEncoder","doc","updatedDoc","tableCellsOld","tableCellsNew","tableCells","cell","char","str","a","updateToReplaceSteps","op","dontReplaceContentAtEnd","updateFromPos","updateToPos","blockPos","getNodeById","updatedTr","updateBlockTr","changeset","ChangeSet","lastChange","lengthA","lengthB","endOfBlockToReAdd","steps","simplifyChanges","typeChange","contentChange","AbortError","validateBlockArray","inputArray","validateItem","validatedBlocks","item","validationResult","createAddBlocksTool","config","referenceId","validatedBlocksResult","addedBlockIds","referenceIdMap","jsonToolCall","inverted","mappedReferenceId","insertBlocks","r","createUpdateBlockTool","id","minSize","selectionPositions","trackPosition","size","fromPos","toPos","deleteBlockTool","removeAndInsertBlocks","getPartialHTML","html","lastOpenBracket","lastCloseBracket","htmlToProcess","match","getApplySuggestionsTr","applySuggestionsTr","applySuggestions","rebaseTool","projectionTr","rebasedTr","mappedStep","createHTMLRebaseTool","getBlock","initialMockID","blocks","htmlBlock","validateBlockFunction","parsedHtml","getStreamTools","withDelays","defaultStreamTools","onBlockUpdate","selection","mergedStreamTools","systemPrompt","htmlBlockLLMFormat","mergeSchemas","groupedSchemas","signatureToSchema","schemaObj","type","schemaSignature","signature","baseSchema","styleSchemaToJSONSchema","val","styledTextToJSONSchema","propSchemaToJSONSchema","propSchema","_key","inlineContentSchemaToJSONSchema","blockSchemaToJSONSchema","schemaOps","clone","defaultProps","blockNoteSchemaToJSONSchema","validateInlineContent","content","isStyledTextInlineContent","isLinkInlineContent","fallbackType","blockConfig","_id","_editor","defaultPropsVals","jsonBlockLLMFormat","createMDRebaseTool","md","stepMapping","mapped","markdownBlockLLMFormat","promptHelpers","getAIDictionary","fetchViaProxy","getUrl","init","request","url","newRequest"],"mappings":"2kBAEO,SAASA,EAAiBC,EAAoC,CACnE,OACIA,EAAM,OAAS,aAAe,CAACA,EAAM,OAAS,CAACA,EAAM,SACtD,MAAM,QAAQA,EAAM,OAAO,GAAKA,EAAM,QAAQ,SAAW,CAE9D,CCPO,SAASC,GACdC,EACAC,EACAC,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mB,EACpC,CCRO,MAAMsM,GACVC,GACD,MAAO9M,EAA+B+M,IAAuB,CAC3D,MAAMC,EAAU,IAAI,QAAQhN,EAAO+M,CAAI,EAGjCE,EAAMH,EAAOE,EAAQ,GAAG,EACxBE,EAAa,IAAI,QAAQD,EAAK,CAClC,QAASD,EAAQ,QAGjB,MAAMD,GAAA,YAAAA,EAAM,OAAQC,EAAQ,KAC5B,OAAQA,EAAQ,OAChB,OAAQ,MAAA,CACF,EAGR,OADa,MAAM,MAAME,CAAU,CAErC"}
|
package/dist/server.cjs
ADDED
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("./client-DrruPiJu.cjs");exports.ClientSideTransport=e.ClientSideTransport;exports.PROVIDER_OVERRIDES=e.PROVIDER_OVERRIDES;exports.StreamToolExecutor=e.StreamToolExecutor;exports._getApplySuggestionsTr=e.getApplySuggestionsTr;exports.aiDocumentFormats=e.aiDocumentFormats;exports.buildAIRequest=e.buildAIRequest;exports.createStreamToolsArraySchema=e.createStreamToolsArraySchema;exports.fetchViaProxy=e.fetchViaProxy;exports.getAIDictionary=e.getAIDictionary;exports.getProviderOverrides=e.getProviderOverrides;exports.injectDocumentStateMessages=e.injectDocumentStateMessages;exports.makeDocumentStateBuilder=e.makeDocumentStateBuilder;exports.objectAsToolCallInUIMessageStream=e.objectAsToolCallInUIMessageStream;exports.objectStreamToOperationsResult=e.objectStreamToOperationsResult;exports.partialObjectStreamAsToolCallInUIMessageStream=e.partialObjectStreamAsToolCallInUIMessageStream;exports.promptHelpers=e.promptHelpers;exports.sendMessageWithAIRequest=e.sendMessageWithAIRequest;exports.setupToolCallStreaming=e.setupToolCallStreaming;exports.streamToolsToToolSet=e.streamToolsToToolSet;exports.toolDefinitionsToToolSet=e.toolDefinitionsToToolSet;exports.toolSetToToolDefinitions=e.toolSetToToolDefinitions;
|
|
2
|
+
//# sourceMappingURL=server.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.cjs","sources":[],"sourcesContent":[],"names":[],"mappings":""}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { C as s, P as t, S as o, g as r, a as l, b as i, d as n, f as m, c as S, h as T, j as c, m as g, o as p, n as u, k as I, p as D, s as d, i as A, e as R, l as b, t as f } from "./client-C4uaJa77.js";
|
|
2
|
+
export {
|
|
3
|
+
s as ClientSideTransport,
|
|
4
|
+
t as PROVIDER_OVERRIDES,
|
|
5
|
+
o as StreamToolExecutor,
|
|
6
|
+
r as _getApplySuggestionsTr,
|
|
7
|
+
l as aiDocumentFormats,
|
|
8
|
+
i as buildAIRequest,
|
|
9
|
+
n as createStreamToolsArraySchema,
|
|
10
|
+
m as fetchViaProxy,
|
|
11
|
+
S as getAIDictionary,
|
|
12
|
+
T as getProviderOverrides,
|
|
13
|
+
c as injectDocumentStateMessages,
|
|
14
|
+
g as makeDocumentStateBuilder,
|
|
15
|
+
p as objectAsToolCallInUIMessageStream,
|
|
16
|
+
u as objectStreamToOperationsResult,
|
|
17
|
+
I as partialObjectStreamAsToolCallInUIMessageStream,
|
|
18
|
+
D as promptHelpers,
|
|
19
|
+
d as sendMessageWithAIRequest,
|
|
20
|
+
A as setupToolCallStreaming,
|
|
21
|
+
R as streamToolsToToolSet,
|
|
22
|
+
b as toolDefinitionsToToolSet,
|
|
23
|
+
f as toolSetToToolDefinitions
|
|
24
|
+
};
|
|
25
|
+
//# sourceMappingURL=server.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"server.js","sources":[],"sourcesContent":[],"names":[],"mappings":";"}
|