@blocknote/xl-ai 0.44.1 → 0.45.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 -1
- package/dist/blocknote-xl-ai.cjs.map +1 -1
- package/dist/blocknote-xl-ai.js +370 -369
- package/dist/blocknote-xl-ai.js.map +1 -1
- package/dist/{client-C4uaJa77.js → client-B0lU3j7B.js} +60 -29
- package/dist/client-B0lU3j7B.js.map +1 -0
- package/dist/client-CUJscXD0.cjs +36 -0
- package/dist/client-CUJscXD0.cjs.map +1 -0
- package/dist/server.cjs +1 -1
- package/dist/server.js +1 -1
- package/dist/webpack-stats.json +1 -1
- package/package.json +9 -9
- package/src/AIExtension.ts +6 -2
- package/src/api/aiRequest/builder.ts +1 -1
- package/src/api/formats/base-tools/createUpdateBlockTool.ts +5 -3
- package/src/api/formats/base-tools/delete.ts +5 -1
- 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_ed2eea810db5ab73a8478e981735f2a6.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_9d907341d7a5b18529ccaf20cacbbe6f.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_a7100ba9aeac25c6dbfc977b2325ae74.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_b6c3311e72a434273d25e4a6dc74731a.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/anthropic.messages/claude-3-7-sonnet-latest (streaming)/fix spelling mid-word selection_1_ce6692c22eda2a757e123681118a333d.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_1ad7d1a857e525e2d0f5a8c85b645a0e.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/groq.chat/llama-3.3-70b-versatile (streaming)/fix spelling mid-word selection_1_8c47595610a6a2d15e1c5c751528e97a.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_59b3c2f2328276dc62dad98af951d63c.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)/fix spelling mid-word selection_1_a6c5e74c3098077445378d6645e2672e.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_d51b8ed2dc61e8f8e333a3221be46316.json +15 -0
- package/src/api/formats/html-blocks/__snapshots__/htmlBlocks.test.ts/Update/__msw_snapshots__/openai.responses/gpt-4o-2024-08-06 (streaming)/fix spelling mid-word selection_1_d4b4abc5fa45932eec4efcc43bb337bd.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_e4b712a415f8af6f2b49382cac85ae77.json +15 -0
- package/src/api/formats/html-blocks/htmlBlocks.ts +1 -1
- package/src/api/formats/html-blocks/tools/rebaseTool.ts +6 -2
- package/src/api/formats/json/json.ts +1 -1
- package/src/api/formats/json/tools/jsontools.test.ts +12 -2
- package/src/api/formats/markdown-blocks/markdownBlocks.ts +1 -1
- package/src/api/formats/tests/validateTestEnvironment.test.ts +1 -0
- package/src/prosemirror/__snapshots__/agent.test.ts.snap +7 -0
- package/src/prosemirror/__snapshots__/changeset.test.ts.snap +28 -0
- package/src/prosemirror/agent.test.ts +14 -2
- package/src/prosemirror/changeset.test.ts +8 -2
- package/src/prosemirror/rebaseTool.ts +1 -1
- package/src/streamTool/filterValidOperations.ts +1 -0
- package/src/streamTool/preprocess.test.ts +32 -66
- package/src/streamTool/preprocess.ts +8 -38
- package/src/streamTool/toValidatedOperations.ts +12 -0
- package/src/streamTool/vercelAiSdk/util/chatHandlers.ts +2 -0
- package/src/testUtil/cases/combinedOperationsTestCases.ts +1 -1
- package/src/testUtil/cases/editors/simpleEditor.ts +15 -0
- package/src/testUtil/cases/index.ts +6 -1
- package/src/testUtil/cases/updateOperationTestCases.ts +30 -1
- package/src/testUtil/suggestChangesTestUtil.ts +1 -1
- package/types/src/streamTool/preprocess.d.ts +0 -13
- package/types/src/testUtil/cases/editors/simpleEditor.d.ts +268 -0
- package/dist/client-C4uaJa77.js.map +0 -1
- package/dist/client-DrruPiJu.cjs +0 -36
- package/dist/client-DrruPiJu.cjs.map +0 -1
- 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 +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_a7597ddda3f5117e1572545c53c19414.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_bb81e06e77589983badfe53e3839ab83.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_8b11b2a66564f9985f33774d3862cd8c.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_885e9088214dbb6d50dcda19d0056f3c.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_1e9c30fa14f61508e6d90cbfa4d9b891.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_f82bcc59263074bf367562f7380b9cef.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_94c4e51be42ba73c81d7edc503e92b40.json +0 -15
package/dist/client-DrruPiJu.cjs
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
"use strict";var ve=Object.defineProperty;var Pe=(t,e,o)=>e in t?ve(t,e,{enumerable:!0,configurable:!0,writable:!0,value:o}):t[e]=o;var L=(t,e,o)=>Pe(t,typeof e!="symbol"?e+"":e,o);const w=require("ai"),H=require("@ai-sdk/provider-utils"),Oe=require("lodash.merge"),Ee=require("lodash.isequal"),T=require("@blocknote/core"),xe=require("prosemirror-model"),Ce=require("prosemirror-state"),g=require("prosemirror-transform"),U=require("prosemirror-changeset"),Be=require("@blocknote/prosemirror-suggest-changes"),ie=t=>t&&typeof t=="object"&&"default"in t?t:{default:t},K=ie(Oe),Ie=ie(Ee);function z(t){return(t.type==="paragraph"||!t.type)&&!t.content||Array.isArray(t.content)&&t.content.length===0}function Me(t,e,o=!0,r=!0){let n=0,a=t.length;if(o)for(;n<a&&e(t[n]);)n++;if(r)for(;a>n&&e(t[a-1]);)a--;return t.slice(n,a)}function E(t,e){return Me(t,r=>z(r)&&(e==null?void 0:e.cursorBlockId)!==r.id,(e==null?void 0:e.trimStart)??!1,(e==null?void 0:e.trimEnd)??!0)}async function Ne(t){const{useSelection:e,deleteEmptyCursorBlock:o,streamToolsProvider:r,documentStateBuilder:n,onStart:a}={useSelection:t.useSelection??!1,deleteEmptyCursorBlock:t.deleteEmptyCursorBlock??!0,streamToolsProvider:t.streamToolsProvider??R.html.getStreamToolsProvider(),documentStateBuilder:t.documentStateBuilder??R.html.defaultDocumentStateBuilder,onStart:t.onStart??(()=>{})},i=e?void 0:t.editor.getTextCursorPosition().block,s=i&&o&&z(i)&&E(t.editor.document).length>0?i.id:void 0,c=e?t.editor.getSelectionCutBlocks():void 0,d=r.getStreamTools(t.editor,c?{from:c._meta.startPos,to:c._meta.endPos}:void 0,t.onBlockUpdated),u={editor:t.editor,selectedBlocks:c==null?void 0:c.blocks,streamTools:d,emptyCursorBlockToDelete:s,onStart:a};return{...u,documentState:await n(u)}}function _e(t){const{properties:e,required:o,$defs:r,...n}=t.inputSchema;return{schema:{type:"object",description:t.description,properties:{type:{type:"string",enum:[t.name]},...e},required:["type",...o??[]],additionalProperties:!1,...n},$defs:r}}function ce(t){const e=t.map(r=>_e(r)),o={};for(const r of e)for(const n in r.$defs){if(o[n]&&!Ie.default(o[n],r.$defs[n]))throw new Error(`Duplicate, but different definition for ${n}`);o[n]=r.$defs[n]}return{type:"object",properties:{operations:{type:"array",items:{anyOf:e.map(r=>r.schema)}}},additionalProperties:!1,required:["operations"],$defs:Object.keys(o).length>0?o:void 0}}function le(t){return{applyDocumentOperations:{inputSchema:w.jsonSchema(ce(t)),outputSchema:w.jsonSchema({type:"object"})}}}class F extends Error{constructor(o,r,n){super(o,n);L(this,"aborted");this.chunk=r,this.name="ChunkExecutionError",this.aborted=(n==null?void 0:n.aborted)??!1}}class ue{constructor(e,o){L(this,"stream");this.streamTools=e,this.abortSignal=o,this.stream=this.createStream()}createStream(){let e;const o=new TransformStream({transform:async(s,c)=>{const d=typeof s=="string"?await Ae(s,(e==null?void 0:e.isPossiblyPartial)??!1,this.streamTools):s;d&&(e=d,c.enqueue(d))},flush:s=>{e!=null&&e.isPossiblyPartial&&s.error(new Error("stream ended with a partial operation"))}}),r=o.readable.pipeThrough(this.createExecutor()),[n,a]=r.tee(),i=n.pipeTo(new WritableStream);return{writable:o.writable,readable:a,finishPromise:i}}createExecutor(){const e=this.streamTools.map(o=>o.executor());return new TransformStream({transform:async(o,r)=>{var a,i;let n=!1;for(const s of e)try{if(await s.execute(o,this.abortSignal)){r.enqueue({status:"ok",chunk:o}),n=!0;break}}catch(c){r.error(new F(`Tool execution failed: ${H.getErrorMessage(c)}`,o,{cause:c,aborted:((a=this.abortSignal)==null?void 0:a.aborted)??!1}));return}if(!n){const s=((i=o.operation)==null?void 0:i.type)||"unknown";r.error(new Error(`No tool could handle operation of type: ${s}`));return}}})}get writable(){return this.stream.writable}get readable(){return this.stream.readable}async finish(){await this.stream.finishPromise}async executeOperationsArray(e){const o=this.writable.getWriter();for await(const r of e){const n=await w.parsePartialJson(r);if(n.state==="undefined-input"||n.state==="failed-parse"||!n)return;await o.write(r)}await o.close(),await this.finish()}async execute(e){const o=this.writable.getWriter();for await(const r of e)await o.write(r);await o.close(),await this.finish()}async executeOne(e){await this.execute(async function*(){yield{operation:e,isUpdateToPreviousOperation:!1,isPossiblyPartial:!1,metadata:{}}}())}}async function Ae(t,e,o){const r=await w.parsePartialJson(t);if(r.state==="undefined-input"||r.state==="failed-parse"||!r)return;const n=o.find(i=>{var s;return i.name===((s=r.value)==null?void 0:s.type)}),a=n&&n.validate(r.value);if(a!=null&&a.ok)return{operation:a.value,isPossiblyPartial:r.state==="repaired-parse",isUpdateToPreviousOperation:e,metadata:void 0}}function I(t){return t.flatMap(e=>{var o;if(e.role==="user"&&((o=e.metadata)!=null&&o.documentState)){const r=e.metadata.documentState;return[{role:"assistant",id:"assistant-document-state-"+e.id,parts:[...r.selection?[{type:"text",text:"This is the latest state of the selection (ignore previous selections, you MUST issue operations against this latest version of the selection):"},{type:"text",text:JSON.stringify(r.selectedBlocks)},{type:"text",text:`This is the latest state of the entire document (INCLUDING the selected text),
|
|
2
|
-
you 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):`},{type:"text",text:JSON.stringify(r.blocks)}]:[{type:"text",text:`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).
|
|
3
|
-
The cursor is BETWEEN two blocks as indicated by cursor: true.
|
|
4
|
-
`+(r.isEmptyDocument?"Because the document is empty, YOU MUST first update the empty block before adding new blocks.":"Prefer updating existing blocks over removing and adding (but this also depends on the user's question).")},{type:"text",text:JSON.stringify(r.blocks)}]]},e]}return[e]})}function de(t,e){let o="";return t.pipeThrough(new TransformStream({start(r){r.enqueue({type:"start"}),r.enqueue({type:"start-step"}),r.enqueue({type:"tool-input-start",toolCallId:"call_object_1",toolName:e})},transform(r,n){switch(r.type){case"text-delta":o+=r.textDelta,n.enqueue({type:"tool-input-delta",toolCallId:"call_object_1",inputTextDelta:r.textDelta});break;case"object":case"finish":break;case"error":n.enqueue({type:"error",errorText:H.getErrorMessage(r.error)});break;default:{const a=r;throw new Error(`Unsupported chunk type: ${a}`)}}},async flush(r){r.enqueue({type:"tool-input-available",toolCallId:"call_object_1",toolName:e,input:JSON.parse(o)}),r.enqueue({type:"finish-step"}),r.enqueue({type:"finish"})}}))}function pe(t,e){return new ReadableStream({start(r){r.enqueue({type:"start"}),r.enqueue({type:"start-step"}),r.enqueue({type:"tool-input-start",toolCallId:"call_object_1",toolName:e}),r.enqueue({type:"tool-input-delta",toolCallId:"call_object_1",inputTextDelta:JSON.stringify(t)}),r.enqueue({type:"tool-input-available",toolCallId:"call_object_1",toolName:e,input:t}),r.enqueue({type:"finish-step"}),r.enqueue({type:"finish"}),r.close()}})}function fe(t){return Object.fromEntries(Object.entries(t).map(([e,o])=>[e,{description:o.description,inputSchema:w.asSchema(o.inputSchema).jsonSchema,outputSchema:w.asSchema(o.outputSchema).jsonSchema}]))}function me(t){return Object.fromEntries(Object.entries(t).map(([e,o])=>[e,w.tool({...o,inputSchema:w.jsonSchema(o.inputSchema),outputSchema:w.jsonSchema(o.outputSchema)})]))}const he={"mistral.chat":{mode:"auto"},"google.generative-ai":{mode:"auto"},"groq.chat":{providerOptions:{groq:{structuredOutputs:!1}}}};function J(t){return he[t.provider]||{}}class je{constructor(e){this.opts=e}async generateObject(e,o){const{model:r,_additionalOptions:n}=this.opts;if(typeof r=="string")throw new Error("model must be a LanguageModelV2");const a=Object.keys(o)[0],i=o[a].inputSchema,s=await w.generateObject({output:"object",schema:i,model:r,mode:"tool",system:this.opts.systemPrompt,messages:w.convertToModelMessages(I(e)),...J(r),...n??{}});return pe(s.object,a)}async streamObject(e,o){const{model:r,_additionalOptions:n}=this.opts;if(typeof r=="string")throw new Error("model must be a LanguageModelV2");const a=Object.keys(o)[0],i=o[a].inputSchema,s=w.streamObject({output:"object",schema:i,model:r,mode:"tool",system:this.opts.systemPrompt,messages:w.convertToModelMessages(I(e)),...J(r),...n??{}});return de(s.fullStream,a)}async streamText(e,o){const{model:r,_additionalOptions:n}=this.opts;return w.streamText({model:r,system:this.opts.systemPrompt,messages:w.convertToModelMessages(I(e)),tools:o,toolChoice:"required",...n??{}}).toUIMessageStream()}async sendMessages({messages:e,body:o}){const r=this.opts.stream??!0,n=o.toolDefinitions,a=me(n);if(this.opts.objectGeneration)return r?this.streamObject(e,a):this.generateObject(e,a);if(r)return await this.streamText(e,a);throw new Error("Not implemented (generateText)")}reconnectToStream(){throw new Error("Not implemented")}}function De(){let t,e=Promise.resolve(),o=!1,r;const n=new Promise((c,d)=>{r=d});n.catch(()=>{});const a=new ReadableStream({start(c){t=c},cancel(c){o=!0,t.error(c),r==null||r(c)}});async function i(c){if(o)throw new Error("Appendable stream canceled, can't append");const d=c.getReader();return e=e.then(async()=>{for(;;)try{const{done:u,value:l}=await Promise.race([d.read(),n]);if(u||o)break;t.enqueue(l)}catch(u){o=!0,t.error(u);break}}),e}async function s(){await e,o||t.close()}return{output:a,append:i,finalize:s}}function $e(t){return new ReadableStream({async start(e){try{for await(const o of t)e.enqueue(o);e.close()}catch(o){e.error(o)}}})}function ye(t){if(t.locked)throw new Error("Stream (source) is already locked and cannot be iterated.");const e=t.pipeThrough(new TransformStream);return e[Symbol.asyncIterator]=()=>{if(e.locked)throw new Error("Stream is already locked and cannot be iterated again.");const o=e.getReader();return{async next(){const{done:r,value:n}=await o.read();return r?{done:!0,value:void 0}:{done:!1,value:n}}}},e}function qe(t){return ye($e(t))}async function*Le(t,e){var a;let o=0,r=!0,n;for await(const i of t)if((a=i.operations)!=null&&a.length){for(let s=o;s<i.operations.length;s++){const c=i.operations[s];n=c,yield{partialOperation:c,isUpdateToPreviousOperation:s===o&&!r,isPossiblyPartial:s===i.operations.length-1,metadata:e},r=!1}o=i.operations.length-1}if(!n)throw new Error("No operations seen");yield{partialOperation:n,isUpdateToPreviousOperation:!0,isPossiblyPartial:!1,metadata:e}}async function*Ue(t,e){let o=!1;for await(const r of t){const n=r.operation;n.ok?(yield{operation:n.value,isUpdateToPreviousOperation:o?!1:r.isUpdateToPreviousOperation,isPossiblyPartial:r.isPossiblyPartial,metadata:r.metadata},o=!1):(o=o||!r.isUpdateToPreviousOperation,e==null||e({...r,operation:n}))}}async function*Je(t,e){for await(const o of t){const r=e.find(a=>a.name===o.partialOperation.type);if(!r){yield{operation:{ok:!1,error:`No matching function for ${o.partialOperation.type}`},isUpdateToPreviousOperation:o.isUpdateToPreviousOperation,isPossiblyPartial:o.isPossiblyPartial,metadata:o.metadata};continue}yield{operation:r.validate(o.partialOperation),isUpdateToPreviousOperation:o.isUpdateToPreviousOperation,isPossiblyPartial:o.isPossiblyPartial,metadata:o.metadata}}}async function*Re(t,e){const o=Je(t,e);yield*Ue(o,n=>{if(!n.isPossiblyPartial)throw new F("invalid operation: "+n.operation.error,n)})}function be(t,e,o){return qe(Re(Le(ye(t),o),e))}async function Se(t,e,o,r){const n=new ue(t,r),a=De(),i=a.output.pipeTo(n.writable),s=new Map;let c=!0;const d=e["~registerMessagesCallback"](()=>{He(e,S=>{if(!s.has(S.toolCallId)){const y=ze(t,S.toolName,S.toolCallId);a.append(y.operationsStream),s.set(S.toolCallId,y),c&&(c=!1,o==null||o())}return s.get(S.toolCallId)})});await new Promise(S=>{const y=e["~registerStatusCallback"](()=>{(e.status==="ready"||e.status==="error")&&(d(),y(),e.status!=="error"&&h(),S())}),h=e["~registerErrorCallback"](()=>{if(e.error){h();for(const k of s.values())k.complete||k.writer.abort(e.error)}})}),await a.finalize();const l=await Promise.allSettled([n.finish(),i]),f=l[0];if(l[1].status==="rejected"&&(l[0].status!=="rejected"||l[0].reason!==l[1].reason))throw new Error("unexpected, pipeToPromise rejected but executor.finish() doesn't have same error!?");let p;if(f.status==="rejected"){if(f.reason instanceof F)p=f.reason;else if(!e.error)throw new Error("Unexpected: no ChunkExecutionError but also no chat.error (network error?)")}let b=!1;const m=Array.from(s.values().filter(S=>S.complete));return m.forEach((S,y)=>{const h=S.toolCallId===(p==null?void 0:p.chunk.metadata.toolCallId);h&&(b=!0),b?e.addToolOutput({tool:m[y].toolName,toolCallId:m[y].toolCallId,state:"output-error",errorText:JSON.stringify(h?{status:"error",error:H.getErrorMessage(p)}:{status:"not-executed-previous-tool-errored"})}):e.addToolOutput({state:"output-available",tool:m[y].toolName,toolCallId:m[y].toolCallId,output:{status:"ok"}})}),p?{ok:!1,error:p}:{ok:!0,value:void 0}}function He(t,e){var o;for(const r of((o=t.lastMessage)==null?void 0:o.parts)??[]){if(!w.isToolUIPart(r)||r.type.replace("tool-","")!=="applyDocumentOperations")continue;const a=r.toolCallId,i=e({toolName:r.type.replace("tool-",""),toolCallId:a});Fe(r,i)}}function ze(t,e,o){const r=new TransformStream,n=be(r.readable,t,{toolCallId:o});return{writer:r.writable.getWriter(),complete:!1,operationsStream:n,toolName:e,toolCallId:o}}function Fe(t,e){if(t.state==="input-streaming"){const o=t.input;o!==void 0&&e.writer.write(o)}else if(t.state==="input-available"){const o=t.input;if(o===void 0)throw new Error("input is undefined");e.complete||(e.complete=!0,e.writer.write(o),e.writer.close())}}async function We(t,e,o,r,n){const a=o??t.lastMessage;if(!a)throw new Error("No message to send");a.metadata=K.default(a.metadata,{documentState:e.documentState});const i=Se(e.streamTools,t,e.onStart,n);return r=K.default(r,{metadata:{source:"blocknote-ai"},body:{toolDefinitions:fe(le(e.streamTools))}}),await t.sendMessage(o,r),await i}function ke(t,e){const o=t.getTextCursorPosition(),r=[];for(const n of e){const a=n.id===o.block.id;r.push({id:n.id,block:n.block}),a&&r.push({cursor:!0})}return r}async function A(t,e){return await Promise.all(t.map(async o=>({id:o.id,block:await e(o)})))}function x(t){return t.flatMap(e=>[{...e,children:[]},...x(e.children)])}function W(t){return t.map(e=>typeof e=="object"&&e&&"id"in e?{...e,id:`${e.id}$`}:e)}function $(t){return async e=>e.selectedBlocks?await Ye(e.editor,t,{selectedBlocks:e.selectedBlocks}):await Ve(e.editor,t,{excludeBlockIds:e.emptyCursorBlockToDelete?[e.emptyCursorBlockToDelete]:void 0})}async function Ve(t,e,o){const r=E(t.document).length===0,n=t.getTextCursorPosition().block.id,a=E(t.document,{cursorBlockId:n}),i=await A(x(a),async u=>e(t,u)),c=ke(t,i).filter(u=>"cursor"in u||!(o.excludeBlockIds||[]).includes(u.id));return{selection:!1,blocks:W(c),isEmptyDocument:r}}async function Ye(t,e,o){const r=E(t.document).length===0,n=await A(x(o.selectedBlocks),async i=>e(t,i)),a=W(n);return{isEmptyDocument:r,selection:!0,selectedBlocks:a,blocks:(await A(x(t.document),async i=>e(t,i))).map(({block:i})=>({block:i}))}}function Xe(t){let e,o=!1;return t.descendants((r,n)=>o?!1:(r.isText&&(o=!0,e=n),!0)),e}function j(t){var a;const e=T.getPmSchema(t),{modification:o}=e.marks,r=[],n=new g.Transform(t.before);for(let i=0;i<t.steps.length;i++){const s=t.steps[i],c=new g.Mapping(t.mapping.maps.slice(0,i)).invert();if(s.structure){if(s instanceof g.ReplaceStep){if(s.to!==s.from+1||s.slice.openStart!==0||s.slice.openEnd!==1||s.slice.content.size!==2)throw new Error("Structure change is not in expected format (ReplaceStep)")}else if(s instanceof g.ReplaceAroundStep){if(s.insert!==1||s.slice.size!==2||s.gapTo!==s.to-1||s.gapFrom!==s.from+1)throw new Error("Structure change is not in expected format (ReplaceAroundStep)")}else throw new Error("Step is not a ReplaceStep or ReplaceAroundStep");const y=c.map(s.from),h=s.slice.content.firstChild,k=n.doc.resolve(n.mapping.map(y)).nodeAfter;let v=h.marks||[];h.type!==k.type&&(v=o.create({type:"nodeType",previousValue:k.type.name,newValue:h.type.name}).addToSet(v));const B=new Set([...Object.keys(h.attrs),...Object.keys(k.attrs)]);for(const P of B)h.attrs[P]!==k.attrs[P]&&(v=o.create({type:"attr",attrName:P,previousValue:k.attrs[P],newValue:h.attrs[P]}).addToSet(v));const O=n.steps.length;n.setNodeMarkup(n.mapping.map(y),h.type,h.attrs,v),r.push({prosemirrorSteps:n.steps.slice(O),selection:void 0,type:"replace"});continue}if(!(s instanceof g.ReplaceStep))throw new Error("Step is not a ReplaceStep");const d=c.map(s.from),u=c.map(s.to);if(s.slice.openStart>0||s.slice.openEnd>0)throw new Error("Slice has openStart or openEnd > 0, but structure=false");r.push({prosemirrorSteps:[],selection:{anchor:n.mapping.map(d),head:n.mapping.map(u)},type:"select"});const l=s.slice.content.textBetween(0,s.slice.size),f=l===n.doc.textBetween(n.mapping.map(d),n.mapping.map(u));let p;if(f)p=s.slice.content.size;else if(l.length===0)p=s.slice.content.size;else{const y=Xe(s.slice.content);if(y===void 0)throw new Error("unexpected: no first character found");p=y+1}let b=n.mapping.map(u);const m=n.mapping.map(u);let S=!0;for(let y=p;y<=s.slice.content.size;y++){const h=S&&d!==u,k=n.steps.length;if(h){const O=n.doc.resolve(n.mapping.map(d));(a=O.nodeAfter)!=null&&a.isBlock&&n.addNodeMark(O.pos,e.mark("deletion",{})),n.addMark(O.pos,b,e.mark("deletion",{})),b=n.mapping.map(u)}const v=new xe.Slice(s.slice.content.cut(0,y),0,0);n.replace(m,b,v).addMark(m,m+v.content.size,e.mark("insertion",{})),n.doc.nodesBetween(m,m+v.content.size,(O,P)=>P<m||P>m+v.content.size?!0:(O.isBlock&&n.addNodeMark(P,e.mark("insertion",{})),!1)),b=n.mapping.slice(k).map(b);const B=Ce.TextSelection.near(n.doc.resolve(m+v.content.size),-1);r.push({prosemirrorSteps:n.steps.slice(k),selection:{anchor:B.from,head:B.from},type:h?"replace":"insert"}),S=!1}}return r}async function V(t){const e=Math.random()*.3+.85;if(t.type==="select")await new Promise(o=>setTimeout(o,100*e));else if(t.type==="insert")await new Promise(o=>setTimeout(o,10*e));else if(t.type==="replace")await new Promise(o=>setTimeout(o,200*e));else throw new T.UnreachableCaseError(t.type)}function Y(t,e){t.setMeta("addToHistory",!1),e.selection&&t.setMeta("aiAgent",{selection:{anchor:e.selection.anchor,head:e.selection.head}});for(const o of e.prosemirrorSteps)if(t.maybeStep(o).failed)throw new Error("failed to apply step");return t}function Ze(t,e,o){const r=new g.Transform(e);for(const i of t){const s=new g.ReplaceStep(r.mapping.map(i.fromA),r.mapping.map(i.toA),o.slice(i.fromB,i.toB));r.step(s)}const n=r.mapping.invert();let a=r.doc.content.findDiffStart(o.content);for(;a!==null;){const i=o.resolve(a).nodeAfter,s=r.doc.resolve(a).nodeAfter;if(!i||!s)throw new Error("diffNode not found");const c=!i.isLeaf&&i.content.eq(s.content),d=c?1:Math.min(i.nodeSize,s.nodeSize),u=a+d,l=n.map(a),f=n.map(u);let p=t.length;for(let m=0;m<t.length;m++)if(t[m].fromA>=f){p=m;break}t.splice(p,0,{fromA:l,toA:f,fromB:a,toB:u,deleted:[],inserted:[],type:c?"node-type-or-attr-update":"mark-update"}),r.step(new g.ReplaceStep(a,u,o.slice(a,u),c));const b=r.doc.content.findDiffStart(o.content);if(b===a)throw new Error("diffStart not moving");a=b}return t}const Q=(t,e)=>{const o=new Set,r=new Set;t.descendants(i=>{i.type.name==="tableCell"&&o.add(JSON.stringify(i.toJSON()))}),e.descendants(i=>{i.type.name==="tableCell"&&r.add(JSON.stringify(i.toJSON()))});const n=new Set([...o].filter(i=>r.has(i)));return{encodeCharacter:i=>i,encodeNodeStart:i=>{if(i.type.name==="tableCell"){const s=JSON.stringify(i.toJSON());return n.has(s)?s:i.type.name}return i.type.name},encodeNodeEnd:i=>{if(i.type.name==="tableCell"){const s=JSON.stringify(i.toJSON());return n.has(s)?s:-1}return-1},compareTokens:(i,s)=>i===s}};function q(t,e,o=!1,r,n){const a=T.getNodeById(t.id,e),i=new g.Transform(e);T.updateBlockTr(i,a.posBeforeNode,t.block,r,n);let s=i.doc,c=U.ChangeSet.create(e,void 0,Q(e,s));if(c=c.addSteps(s,i.mapping.maps,0),o&&c.changes.length>0){const l=c.changes[c.changes.length-1],f=l.toA-l.fromA,p=l.toB-l.fromB;if(f>p){const b=e.slice(l.fromA+p,l.toA);i.step(new g.ReplaceStep(l.toB,l.toB,b)),s=i.doc,c=U.ChangeSet.create(c.startDoc,void 0,Q(c.startDoc,s)),c=c.addSteps(s,i.mapping.maps,0)}}const d=[],u=U.simplifyChanges(c.changes,s);for(let l=0;l<u.length;l++){const f=u[l],p=s.slice(f.fromB,f.toB);if(p.openEnd===1&&p.openStart===0&&(f.type="node-type-or-attr-update",p.size>2)){const b={fromA:f.fromA,toA:f.fromA+1,fromB:f.fromB,toB:f.fromB+1,deleted:[],inserted:[],type:"node-type-or-attr-update"},m={fromA:f.fromA+1,toA:f.toA,fromB:f.fromB+1,toB:f.toB,deleted:[],inserted:[]};u.splice(l,1,b,m),l++}}Ze(u,e,s);for(let l=0;l<u.length;l++){const f=u[l],p=s.slice(f.fromB,f.toB);if(p.openEnd>0&&p.size>1)throw new Error("unexpected, openEnd > 0 and size > 1, this should have been split into two steps");l===u.length-1&&o&&f.type==="mark-update"||d.push(new g.ReplaceStep(f.fromA,f.toA,p,f.type==="node-type-or-attr-update"))}return d}class we extends Error{constructor(e,o){super(e,o),this.name="AbortError"}}function Ge(t,e){if(!t||!Array.isArray(t)||t.length===0)return{ok:!1,error:"blocks is required"};const o=[];for(const r of t){const n=e(r);if(!n.ok)return{ok:!1,error:`Invalid block: ${n.error}`};o.push(n.value)}return{ok:!0,value:o}}function X(t){return(e,o)=>{const r=typeof t.schema=="function"?t.schema(e):t.schema;return{name:"add",description:t.description,inputSchema:{type:"object",properties:{referenceId:{type:"string",description:"MUST be an id of a block in the document"},position:{type:"string",enum:["before","after"],description:"`after` to add blocks AFTER (below) the block with `referenceId`, `before` to add the block BEFORE (above)"},blocks:{items:r.block,type:"array"}},required:["referenceId","position","blocks"],$defs:r.$defs},validate:n=>{if(n.type!=="add")return{ok:!1,error:"invalid operation type"};if(n.position!=="before"&&n.position!=="after")return{ok:!1,error:"invalid position"};if(!n.referenceId||!n.blocks)return{ok:!1,error:"referenceId and blocks are required"};let a=n.referenceId;if(o.idsSuffixed){if(!(a!=null&&a.endsWith("$")))return{ok:!1,error:"referenceId must end with $"};a=a.slice(0,-1)}if(!e.getBlock(a))return{ok:!1,error:"referenceId not found"};const s=Ge(n.blocks,c=>t.validateBlock(c,e));return s.ok?{ok:!0,value:{type:n.type,referenceId:a,position:n.position,blocks:s.value}}:s},executor:()=>{let n=[];const a={};return{execute:async(i,s)=>{var u;if(i.isUpdateToPreviousOperation||(n=[]),i.operation.type!=="add")return!1;const c=i.operation,d=await t.toJSONToolCall(e,{...i,operation:c});if(!d||i.isPossiblyPartial&&z(d.blocks[d.blocks.length-1]))return!0;for(let l=0;l<d.blocks.length;l++){const f=d.blocks[l],p=e.prosemirrorState.tr;let b=[];if(l<n.length){const m=await t.rebaseTool(n[l],e),y=q({id:n[l],block:f},m.doc,!1).map(h=>h.map(m.invertMap));for(const h of y)p.step(h.map(p.mapping));b=j(p),b=b.filter(h=>h.type!=="select")}else{const m=c.position==="after"?a[c.referenceId]:void 0,S=T.insertBlocks(p,[f],l>0?n[l-1]:m||c.referenceId,l>0?"after":c.position);n.push(...S.map(y=>y.id)),b=j(p)}for(const m of b){if(s!=null&&s.aborted)throw new we("Operation was aborted");o.withDelays&&await V(m),e.transact(S=>{Y(S,m)}),(u=o.onBlockUpdate)==null||u.call(o,n[l])}}return i.isPossiblyPartial||c.position==="after"&&(a[c.referenceId]=n[n.length-1]),!0}}}}}}function Z(t){return(e,o)=>{const r=typeof t.schema=="function"?t.schema(e):t.schema;return{name:"update",description:t.description,inputSchema:{type:"object",properties:{id:{type:"string",description:"id of block to update"},block:r.block},required:["id","block"],$defs:r.$defs},validate:n=>{if(n.type!=="update")return{ok:!1,error:"invalid operation type"};if(!n.id)return{ok:!1,error:"id is required"};let a=n.id;if(o.idsSuffixed){if(!(a!=null&&a.endsWith("$")))return{ok:!1,error:"id must end with $"};a=a.slice(0,-1)}if(!n.block)return{ok:!1,error:"block is required"};const i=e.getBlock(a);if(!i)return console.error("BLOCK NOT FOUND",a),{ok:!1,error:"block not found"};const s=t.validateBlock(n.block,e,i.type);return s.ok?{ok:!0,value:{type:n.type,id:a,block:s.value}}:s},executor:()=>{let a=50;const i=o.updateSelection?{from:T.trackPosition(e,o.updateSelection.from),to:T.trackPosition(e,o.updateSelection.to)}:void 0;return{execute:async(s,c)=>{var h;if(s.operation.type!=="update")return!1;const d=s.operation;if(s.isPossiblyPartial){const k=JSON.stringify(d.block).length;if(k<a)return!0;a=k+50}else a=50;const u=await t.rebaseTool(d.id,e),l=i?u.invertMap.invert().map(i.from()):void 0,f=i?u.invertMap.invert().map(i.to()):void 0,p=await t.toJSONToolCall(e,{...s,operation:d});if(!p)return!0;const b=q(p,u.doc,s.isPossiblyPartial,l,f);if(b.length===1&&s.isPossiblyPartial)return!0;const m=b.map(k=>k.map(u.invertMap)),S=new g.Transform(e.prosemirrorState.doc);for(const k of m)S.step(k.map(S.mapping));const y=j(S);for(const k of y){if(c!=null&&c.aborted)throw new we("Operation was aborted");o.withDelays&&await V(k),e.transact(v=>{Y(v,k)}),(h=o.onBlockUpdate)==null||h.call(o,d.id)}return!0}}}}}}const G=(t,e)=>({name:"delete",description:"Delete a block",inputSchema:{type:"object",properties:{id:{type:"string",description:"id of block to delete"}},required:["id"]},validate:o=>{if(o.type!=="delete")return{ok:!1,error:"invalid operation type"};if(!o.id)return{ok:!1,error:"id is required"};let r=o.id;if(e.idsSuffixed){if(!(r!=null&&r.endsWith("$")))return{ok:!1,error:"id must end with $"};r=r.slice(0,-1)}return t.getBlock(r)?{ok:!0,value:{type:"delete",id:r}}:{ok:!1,error:"block not found"}},executor:()=>({execute:async o=>{var i;if(o.operation.type!=="delete")return!1;const r=o.operation,n=t.prosemirrorState.tr;T.removeAndInsertBlocks(n,[r.id],[]);const a=j(n);for(const s of a)e.withDelays&&await V(s),t.transact(c=>{Y(c,s)}),(i=e.onBlockUpdate)==null||i.call(e,r.id);return!0}})});function ee(t){const e=t.lastIndexOf("<"),o=t.lastIndexOf(">");let r=t;if(e>o&&(r=t.substring(0,e),!r.trim()))return;const n=r.match(/&[a-zA-Z0-9]*$/);n&&(r=r.substring(0,r.length-n[0].length));const s=new DOMParser().parseFromString(`<div>${r}</div>`,"text/html").body.firstChild;return s?s.innerHTML:""}function C(t){let e;if(Be.applySuggestions(t.prosemirrorState,o=>{e=o}),!e)throw new Error("applySuggestionsTr is not set");return e}function D(t,e){const o=e.mapping.invert();return{doc:e.doc,tr:()=>new g.Transform(e.doc),invertMap:o,rebaseTr:r=>{if(r.steps.length===0)throw new Error("No steps to apply");let n=t.prosemirrorState.tr;for(const a of r.steps){const i=a.map(o);if(!i)throw new Error("Step is not mapped");n=n.step(i)}return n}}}async function te(t,e){var d;const o=C(e),r=T.getBlock(o.doc,t);if(!r)throw new Error("block not found");const n=await e.blocksToHTMLLossy([{...r,children:[]}]),a=(d=window.__TEST_OPTIONS)==null?void 0:d.mockID,i=await e.tryParseHTMLToBlocks(n);if(window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=a),i.length!==1)throw new Error("html diff invalid block count");const s=i[0];if(s.id=t,q({id:t,block:s},o.doc).length)throw new Error("html diff");return D(e,o)}function oe(t){return typeof t!="string"?{ok:!1,error:"block must be a string"}:{ok:!0,value:t}}const M={add:X({description:"Insert new blocks",schema:{block:{type:"string",description:"html of block (MUST be a single, VALID HTML element)"}},validateBlock:oe,rebaseTool:te,toJSONToolCall:async(t,e)=>{var n;const o=(n=window.__TEST_OPTIONS)==null?void 0:n.mockID,r=(await Promise.all(e.operation.blocks.map(async a=>{const i=e.isPossiblyPartial?ee(a):a;return i?(await t.tryParseHTMLToBlocks(i)).map(s=>(delete s.id,s)):[]}))).flat();if(window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=o),r.length!==0)return{...e.operation,blocks:r}}}),update:Z({description:"Update a block",schema:{block:{type:"string",description:"html of block (MUST be a single HTML element)"}},validateBlock:oe,rebaseTool:te,toJSONToolCall:async(t,e)=>{const o=e.isPossiblyPartial?ee(e.operation.block):e.operation.block;if(!o)return;const r=(await t.tryParseHTMLToBlocks(o))[0];return window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=void 0),delete r.id,{...e.operation,block:r}}}),delete:G};function Ke(t,e,o,r,n){if(typeof r=="boolean"){const s=r?t.getSelectionCutBlocks():void 0;r=s?{from:s._meta.startPos,to:s._meta.endPos}:void 0}const a=o??{add:!0,update:!0,delete:!0};return[...a.update?[M.update(t,{idsSuffixed:!0,withDelays:e,updateSelection:r,onBlockUpdate:n})]:[],...a.add?[M.add(t,{idsSuffixed:!0,withDelays:e,onBlockUpdate:n})]:[],...a.delete?[M.delete(t,{idsSuffixed:!0,withDelays:e,onBlockUpdate:n})]:[]]}const Qe=`You're manipulating a text document using HTML blocks.
|
|
5
|
-
Make sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $).
|
|
6
|
-
List 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.
|
|
7
|
-
For code blocks, you can use the \`data-language\` attribute on a <code> block (wrapped with <pre>) to specify the language.
|
|
8
|
-
|
|
9
|
-
If the user requests updates to the document, use the "applyDocumentOperations" tool to update the document.
|
|
10
|
-
---
|
|
11
|
-
IF 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.
|
|
12
|
-
EXAMPLE: if user says "below" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor.
|
|
13
|
-
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\`
|
|
14
|
-
---
|
|
15
|
-
`,et={getStreamToolsProvider:(t={})=>({getStreamTools:(e,o,r)=>Ke(e,t.withDelays??!0,t.defaultStreamTools,o,r)}),systemPrompt:Qe,tools:M,defaultDocumentStateBuilder:$(async(t,e)=>t.blocksToHTMLLossy([e]))};function tt(t){const e={},o={};return t.forEach(n=>{const{type:a,...i}=n.properties,s=JSON.stringify(i);e[s]?e[s].push(a.enum[0]):(e[s]=[a.enum[0]],o[s]=n)}),Object.keys(e).map(n=>{const a=o[n];return{...a,properties:{...a.properties,type:{type:"string",enum:e[n]}}}})}function ot(t){return{type:"object",properties:Object.fromEntries(Object.entries(t).map(([e,o])=>[e,{type:o.propSchema}])),additionalProperties:!1}}function rt(){return{type:"object",properties:{type:{type:"string",enum:["text"]},text:{type:"string"},styles:{$ref:"#/$defs/styles"}},additionalProperties:!1,required:["type","text"]}}function ge(t){return{type:"object",properties:Object.fromEntries(Object.entries(t).filter(([e,o])=>o.default!==void 0).map(([e,o])=>[e,{type:typeof o.default,enum:o.values}])),additionalProperties:!1}}function nt(t){return{type:"array",items:{anyOf:Object.entries(t).map(([e,o])=>o==="text"?{$ref:"#/$defs/styledtext"}:o==="link"?{type:"object",properties:{type:{type:"string",enum:["link"]},content:{type:"array",items:{$ref:"#/$defs/styledtext"}},href:{type:"string"}},additionalProperties:!1,required:["type","href","content"]}:{type:"object",properties:{type:{type:"string",enum:[o.type]},content:o.content==="styled"?{type:"array",items:{$ref:"#/$defs/styledtext"}}:void 0,props:ge(o.propSchema)},additionalProperties:!1,required:["type",...o.content==="styled"?["content"]:[]]})}}}function st(t){return{anyOf:tt(Object.entries(t).map(([e,o])=>({type:"object",properties:{type:{type:"string",enum:[o.type]},content:o.content==="inline"?{$ref:"#/$defs/inlinecontent"}:o.content==="table"?{type:"object",properties:{}}:void 0,props:ge(o.propSchema)},additionalProperties:!1,required:["type"]})))}}function at(t){const e=JSON.parse(JSON.stringify({blockSchema:t.blockSchema,inlineContentSchema:t.inlineContentSchema,styleSchema:t.styleSchema}));return{removeFileBlocks(){return e.blockSchema=Object.fromEntries(Object.entries(e.blockSchema).filter(([o,r])=>{var n;return!((n=t.blockSpecs[r.type].implementation.meta)!=null&&n.fileBlockAccept)})),this},removeDefaultProps(){return e.blockSchema=Object.fromEntries(Object.entries(e.blockSchema).map(([o,r])=>[o,{...r,propSchema:Object.fromEntries(Object.entries(r.propSchema).filter(n=>typeof T.defaultProps[n[0]]>"u"))}])),this},get(){return e}}}function re(t){return t=at(t).removeFileBlocks().removeDefaultProps().get(),{$defs:{styles:ot(t.styleSchema),styledtext:rt(),inlinecontent:nt(t.inlineContentSchema),block:st(t.blockSchema)}}}function Te(t,e){return!e.schema.inlineContentSchema[t.type]||T.isStyledTextInlineContent(t)&&!("text"in t)?!1:T.isLinkInlineContent(t)?!("content"in t)||!("href"in t)?!1:Te(t.content,e):!0}function ne(t,e,o){const r=t.type||o,n=e.schema.blockSchema[r];if(!n)return{ok:!1,error:"block type not found in editor"};if(t.children,n.content==="none"){if(t.content)return{ok:!1,error:"block content not expected for this block type"}}else{if(!t.content)return{ok:!0,value:t};if(!Array.isArray(t.content))return{ok:!1,error:"block content must be an array"};if(n.content==="table")return{ok:!0,value:t};if(!t.content.every(a=>Te(a,e)))return{ok:!1,error:"block content must be an array of inline content"}}return{ok:!0,value:t}}const N={add:X({description:"Insert new blocks",schema:t=>({block:{$ref:"#/$defs/block"},...re(t.schema)}),validateBlock:ne,rebaseTool:async(t,e)=>D(e,C(e)),toJSONToolCall:async(t,e)=>e.operation}),update:Z({description:"Update a block, the new block will replace the existing block.",schema:t=>({block:{$ref:"#/$defs/block"},...re(t.schema)}),validateBlock:ne,rebaseTool:async(t,e)=>D(e,C(e)),toJSONToolCall:async(t,e)=>{const o=Object.fromEntries(Object.entries(T.defaultProps).map(([r,n])=>[r,n.default]));return{...e.operation,block:{...e.operation.block,props:{...o,...e.operation.block.props}}}}}),delete:G};function it(t,e,o,r,n){if(typeof r=="boolean"){const s=r?t.getSelectionCutBlocks():void 0;r=s?{from:s._meta.startPos,to:s._meta.endPos}:void 0}const a=o??{add:!0,update:!0,delete:!0};return[...a.update?[N.update(t,{idsSuffixed:!0,withDelays:e,updateSelection:r,onBlockUpdate:n})]:[],...a.add?[N.add(t,{idsSuffixed:!0,withDelays:e,onBlockUpdate:n})]:[],...a.delete?[N.delete(t,{idsSuffixed:!0,withDelays:e,onBlockUpdate:n})]:[]]}const ct=`You're manipulating a text document using JSON blocks.
|
|
16
|
-
Make sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $).
|
|
17
|
-
|
|
18
|
-
If the user requests updates to the document, use the "applyDocumentOperations" tool to update the document.
|
|
19
|
-
---
|
|
20
|
-
IF 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.
|
|
21
|
-
EXAMPLE: if user says "below" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor.
|
|
22
|
-
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\`
|
|
23
|
-
---
|
|
24
|
-
`,lt={getStreamToolsProvider:(t={})=>({getStreamTools:(e,o,r)=>it(e,t.withDelays??!0,t.defaultStreamTools,o,r)}),tools:N,systemPrompt:ct,defaultDocumentStateBuilder:$(async(t,e)=>({...e,id:void 0,children:void 0}))};async function se(t,e){const o=C(e),r=await e.blocksToMarkdownLossy([T.getBlock(o.doc,t)]),n=await e.tryParseMarkdownToBlocks(r),a=q({id:t,block:n[0]},o.doc),i=new g.Mapping;for(const s of a){const c=s.map(i);if(!c)throw new Error("Failed to map step");o.step(c),i.appendMap(c.getMap())}return D(e,o)}function ae(t){return typeof t!="string"?{ok:!1,error:"block must be a string"}:{ok:!0,value:t}}const _={add:X({description:"Insert new blocks",schema:{block:{$ref:"#/$defs/block"},$defs:{block:{type:"string",description:"markdown of block"}}},validateBlock:ae,rebaseTool:se,toJSONToolCall:async(t,e)=>{const o=await Promise.all(e.operation.blocks.map(async r=>{const n=(await t.tryParseMarkdownToBlocks(r.trim()))[0];return delete n.id,n}));return window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=void 0),{...e.operation,blocks:o}}}),update:Z({description:"Update a block, the new block will replace the existing block.",schema:{block:{$ref:"#/$defs/block"},$defs:{block:{type:"string",description:"markdown of block"}}},validateBlock:ae,rebaseTool:se,toJSONToolCall:async(t,e)=>{const o=(await t.tryParseMarkdownToBlocks(e.operation.block.trim()))[0];return delete o.id,window.__TEST_OPTIONS&&(window.__TEST_OPTIONS.mockID=void 0),{...e.operation,block:o}}}),delete:G};function ut(t,e,o,r,n){if(typeof r=="boolean"){const s=r?t.getSelectionCutBlocks():void 0;r=s?{from:s._meta.startPos,to:s._meta.endPos}:void 0}const a=o??{add:!0,update:!0,delete:!0};return[...a.update?[_.update(t,{idsSuffixed:!0,withDelays:e,updateSelection:r,onBlockUpdate:n})]:[],...a.add?[_.add(t,{idsSuffixed:!0,withDelays:e,onBlockUpdate:n})]:[],...a.delete?[_.delete(t,{idsSuffixed:!0,withDelays:e,onBlockUpdate:n})]:[]]}const dt=`You're manipulating a text document using Markdown blocks.
|
|
25
|
-
Make sure to follow the json schema provided. When referencing ids they MUST be EXACTLY the same (including the trailing $).
|
|
26
|
-
List items are 1 block with 1 list item each, so block content \`- item1\` is valid, but \`- item1
|
|
27
|
-
- item2\` is invalid. We'll merge them automatically.
|
|
28
|
-
|
|
29
|
-
If the user requests updates to the document, use the "applyDocumentOperations" tool to update the document.
|
|
30
|
-
---
|
|
31
|
-
IF 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.
|
|
32
|
-
EXAMPLE: if user says "below" (without pointing to a specific part of the document) he / she probably indicates the block(s) after the cursor.
|
|
33
|
-
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\`
|
|
34
|
-
---
|
|
35
|
-
`,pt={getStreamToolsProvider:(t={})=>({getStreamTools:(e,o,r)=>ut(e,t.withDelays??!0,t.defaultStreamTools,o,r)}),systemPrompt:dt,tools:_,defaultDocumentStateBuilder:$(async(t,e)=>t.blocksToMarkdownLossy([e]))},R={_experimental_json:lt,_experimental_markdown:pt,html:et},ft={addCursorPosition:ke,flattenBlocks:x,suffixIDs:W,trimEmptyBlocks:E,convertBlocks:A};function mt(t){if(!t.dictionary.ai)throw new Error("AI dictionary not found");return t.dictionary.ai}const ht=t=>async(e,o)=>{const r=new Request(e,o),n=t(r.url),a=new Request(n,{headers:r.headers,body:(o==null?void 0:o.body)||r.body,method:r.method,duplex:"half"});return await fetch(a)};exports.ClientSideTransport=je;exports.PROVIDER_OVERRIDES=he;exports.StreamToolExecutor=ue;exports.aiDocumentFormats=R;exports.buildAIRequest=Ne;exports.createStreamToolsArraySchema=ce;exports.fetchViaProxy=ht;exports.getAIDictionary=mt;exports.getApplySuggestionsTr=C;exports.getProviderOverrides=J;exports.injectDocumentStateMessages=I;exports.makeDocumentStateBuilder=$;exports.objectAsToolCallInUIMessageStream=pe;exports.objectStreamToOperationsResult=be;exports.partialObjectStreamAsToolCallInUIMessageStream=de;exports.promptHelpers=ft;exports.sendMessageWithAIRequest=We;exports.setupToolCallStreaming=Se;exports.streamToolsToToolSet=le;exports.toolDefinitionsToToolSet=me;exports.toolSetToToolDefinitions=fe;
|
|
36
|
-
//# sourceMappingURL=client-DrruPiJu.cjs.map
|