File size: 6,944 Bytes
8fc8501
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
import type { Editor } from "@tiptap/core";

/**
 * Frontend executor for Tiptap commands issued by the AI agent.
 *
 * The backend exposes a catalog of commands (see `backend/src/agent/tiptap-catalog.ts`).
 * When the LLM calls one, `useAgentChat` receives the tool call and
 * dispatches it here. Most commands map directly to
 * `editor.chain().focus()[commandName](args).run()`; a few need
 * specific handling (selectText, setLink).
 *
 * Returns a short human-readable status string that is sent back to the
 * LLM as the tool result so it can plan its next step.
 *
 * Inspired by `tiptap-apcore`'s TiptapExecutor but intentionally tiny -
 * we only cover the commands declared in the catalog.
 */

const SAFE_URL_PROTOCOLS = /^(https?|mailto|tel):/i;
const SAFE_URL_RELATIVE = /^[/#?]/;

function isSafeUrl(url: string): boolean {
  const trimmed = url.trim();
  return SAFE_URL_PROTOCOLS.test(trimmed) || SAFE_URL_RELATIVE.test(trimmed);
}

// ---------------------------------------------------------------------------
// selectText: semantic selection by text content
// ---------------------------------------------------------------------------

/**
 * Extract all text from the ProseMirror document as a flat string,
 * keeping a mapping from string offsets to document positions.
 *
 * Duplicated from the logic inside `useAgentChat.findTextPosition` so
 * this module has no React dependency.
 */
function getDocTextWithPositions(editor: Editor): { text: string; map: number[] } {
  const chunks: string[] = [];
  const map: number[] = [];

  editor.state.doc.descendants((node, pos) => {
    if (node.isText && node.text) {
      for (let i = 0; i < node.text.length; i++) {
        map.push(pos + i);
        chunks.push(node.text[i]);
      }
    } else if (node.isBlock && chunks.length > 0) {
      map.push(pos);
      chunks.push("\n");
    }
  });

  return { text: chunks.join(""), map };
}

interface SelectTextResult {
  found: boolean;
  from?: number;
  to?: number;
}

function handleSelectText(
  editor: Editor,
  args: {
    text: string;
    occurrence?: number;
    contextBefore?: string;
    contextAfter?: string;
  },
): SelectTextResult {
  const { text, occurrence = 1, contextBefore, contextAfter } = args;
  if (!text) return { found: false };

  const { text: docText, map } = getDocTextWithPositions(editor);

  // Collect all candidate indices
  const candidates: number[] = [];
  let startIdx = 0;
  while (true) {
    const idx = docText.indexOf(text, startIdx);
    if (idx === -1) break;
    candidates.push(idx);
    startIdx = idx + 1;
  }
  if (candidates.length === 0) return { found: false };

  let chosenIdx: number;
  if (contextBefore || contextAfter) {
    let bestIdx = candidates[0];
    let bestScore = -1;
    for (const idx of candidates) {
      let score = 0;
      if (contextBefore) {
        const before = docText.slice(Math.max(0, idx - contextBefore.length - 10), idx);
        if (before.includes(contextBefore)) score += 2;
        else if (before.toLowerCase().includes(contextBefore.toLowerCase())) score += 1;
      }
      if (contextAfter) {
        const after = docText.slice(idx + text.length, idx + text.length + contextAfter.length + 10);
        if (after.includes(contextAfter)) score += 2;
        else if (after.toLowerCase().includes(contextAfter.toLowerCase())) score += 1;
      }
      if (score > bestScore) {
        bestScore = score;
        bestIdx = idx;
      }
    }
    chosenIdx = bestIdx;
  } else {
    const occIdx = Math.max(0, Math.min(occurrence - 1, candidates.length - 1));
    chosenIdx = candidates[occIdx];
  }

  const from = map[chosenIdx];
  const to = map[chosenIdx + text.length - 1] + 1;
  editor.chain().focus().setTextSelection({ from, to }).run();
  return { found: true, from, to };
}

// ---------------------------------------------------------------------------
// Catalog command dispatch
// ---------------------------------------------------------------------------

/**
 * Tiptap commands that take no arguments. Called as
 * `editor.chain().focus()[name]().run()`.
 */
const EMPTY_ARG_COMMANDS = new Set([
  "toggleBold",
  "toggleItalic",
  "toggleStrike",
  "toggleCode",
  "unsetLink",
  "setParagraph",
  "toggleBulletList",
  "toggleOrderedList",
  "toggleBlockquote",
]);

/**
 * Map a tool call to an `editor.chain()` invocation.
 *
 * Returns null when the tool name is not in the Tiptap catalog (so the
 * caller can fall back to its own handling for applyDiff, frontmatter, etc.).
 */
export function executeTiptapCommand(
  editor: Editor,
  toolName: string,
  args: Record<string, unknown>,
): string | null {
  // selectText is not a native Tiptap command.
  if (toolName === "selectText") {
    const result = handleSelectText(editor, args as Parameters<typeof handleSelectText>[1]);
    if (!result.found) {
      return `selectText: text not found in the document`;
    }
    return `selectText: selected range ${result.from}-${result.to}`;
  }

  // Empty-arg commands - just call them directly.
  if (EMPTY_ARG_COMMANDS.has(toolName)) {
    const chain = editor.chain().focus();
    const fn = (chain as unknown as Record<string, () => typeof chain>)[toolName];
    if (typeof fn !== "function") {
      return `Unknown editor command: ${toolName}`;
    }
    const success = fn.call(chain).run();
    return success ? `${toolName} applied` : `${toolName} failed (selection state?)`;
  }

  // Commands with specific argument shapes.
  switch (toolName) {
    case "toggleHeading": {
      const level = (args as { level?: number }).level;
      if (!level || level < 1 || level > 3) return "toggleHeading: invalid level";
      const ok = editor
        .chain()
        .focus()
        .toggleHeading({ level: level as 1 | 2 | 3 })
        .run();
      return ok ? `toggleHeading (level ${level}) applied` : "toggleHeading failed";
    }
    case "toggleCodeBlock": {
      const language = (args as { language?: string }).language;
      const chain = editor.chain().focus();
      const ok = language
        ? chain.toggleCodeBlock({ language }).run()
        : chain.toggleCodeBlock().run();
      return ok ? "toggleCodeBlock applied" : "toggleCodeBlock failed";
    }
    case "setLink": {
      const href = (args as { href?: string }).href;
      if (!href || !isSafeUrl(href)) return `setLink: unsafe or missing URL`;
      const ok = editor.chain().focus().setLink({ href }).run();
      return ok ? `setLink applied (${href})` : "setLink failed (is text selected?)";
    }
    default:
      return null;
  }
}

/** Tool names handled by `executeTiptapCommand`, useful for dispatch. */
export const TIPTAP_TOOL_NAMES = new Set<string>([
  "selectText",
  "toggleBold",
  "toggleItalic",
  "toggleStrike",
  "toggleCode",
  "setLink",
  "unsetLink",
  "toggleHeading",
  "setParagraph",
  "toggleBulletList",
  "toggleOrderedList",
  "toggleBlockquote",
  "toggleCodeBlock",
]);