@flowdrop/flowdrop 2.6.0 → 2.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (72) hide show
  1. package/CHANGELOG.md +56 -0
  2. package/dist/api/enhanced-client.d.ts +29 -1
  3. package/dist/api/enhanced-client.js +83 -9
  4. package/dist/chat/commandClassifier.d.ts +2 -1
  5. package/dist/chat/commandClassifier.js +4 -1
  6. package/dist/chat/index.d.ts +5 -1
  7. package/dist/chat/index.js +2 -0
  8. package/dist/chat/toolCatalogue.d.ts +27 -0
  9. package/dist/chat/toolCatalogue.js +35 -0
  10. package/dist/chat/turnDriver.d.ts +143 -0
  11. package/dist/chat/turnDriver.js +124 -0
  12. package/dist/commands/executor.js +270 -37
  13. package/dist/commands/index.d.ts +1 -1
  14. package/dist/commands/parser.js +20 -0
  15. package/dist/commands/types.d.ts +77 -12
  16. package/dist/components/App.svelte +47 -56
  17. package/dist/components/SettingsPanel.svelte +13 -0
  18. package/dist/components/WorkflowEditor.svelte +4 -2
  19. package/dist/components/WorkflowEditor.svelte.d.ts +2 -0
  20. package/dist/components/chat/AIChatPanel.svelte +410 -22
  21. package/dist/components/console/CommandConsole.svelte +8 -0
  22. package/dist/components/console/formatters.d.ts +9 -1
  23. package/dist/components/console/formatters.js +54 -0
  24. package/dist/components/toast/DismissibleToast.svelte +53 -0
  25. package/dist/components/toast/DismissibleToast.svelte.d.ts +24 -0
  26. package/dist/components/toast/WarningIcon.svelte +28 -0
  27. package/dist/components/toast/WarningIcon.svelte.d.ts +26 -0
  28. package/dist/config/constants.d.ts +7 -3
  29. package/dist/config/constants.js +7 -3
  30. package/dist/config/endpoints.d.ts +7 -0
  31. package/dist/config/endpoints.js +2 -1
  32. package/dist/core/index.d.ts +1 -1
  33. package/dist/editor/index.d.ts +1 -1
  34. package/dist/editor/index.js +1 -1
  35. package/dist/messages/defaults.d.ts +74 -0
  36. package/dist/messages/defaults.js +35 -1
  37. package/dist/services/chatService.d.ts +21 -3
  38. package/dist/services/chatService.js +33 -1
  39. package/dist/services/globalSave.d.ts +7 -1
  40. package/dist/services/globalSave.js +20 -4
  41. package/dist/services/toastService.d.ts +23 -2
  42. package/dist/services/toastService.js +72 -28
  43. package/dist/stores/instanceContainer.svelte.d.ts +34 -0
  44. package/dist/stores/instanceContainer.svelte.js +30 -0
  45. package/dist/stores/workflowStore.svelte.d.ts +10 -0
  46. package/dist/stores/workflowStore.svelte.js +15 -0
  47. package/dist/styles/toast.css +62 -0
  48. package/dist/styles/tokens.css +6 -0
  49. package/dist/svelte-app.d.ts +16 -4
  50. package/dist/svelte-app.js +45 -14
  51. package/dist/types/chat.d.ts +59 -0
  52. package/dist/types/events.d.ts +23 -0
  53. package/dist/types/events.js +3 -1
  54. package/dist/types/index.d.ts +49 -0
  55. package/dist/types/settings.d.ts +18 -1
  56. package/dist/types/settings.js +1 -0
  57. package/dist/webmcp/WebMCPConfirm.svelte +168 -61
  58. package/dist/webmcp/WebMCPConfirm.svelte.d.ts +14 -4
  59. package/dist/webmcp/bridge.d.ts +63 -0
  60. package/dist/webmcp/bridge.js +106 -0
  61. package/dist/webmcp/descriptors.d.ts +8 -1
  62. package/dist/webmcp/descriptors.js +108 -17
  63. package/dist/webmcp/gate.d.ts +44 -2
  64. package/dist/webmcp/gate.js +61 -10
  65. package/dist/webmcp/index.d.ts +7 -2
  66. package/dist/webmcp/index.js +4 -1
  67. package/dist/webmcp/register.d.ts +11 -10
  68. package/dist/webmcp/register.js +72 -160
  69. package/dist/webmcp/runtime.d.ts +33 -0
  70. package/dist/webmcp/runtime.js +500 -0
  71. package/dist/webmcp/types.d.ts +196 -2
  72. package/package.json +1 -1
@@ -1,31 +1,23 @@
1
1
  /**
2
2
  * WebMCP adapter — registration.
3
3
  *
4
- * The only file that touches the runtime (`document.modelContext`, falling
5
- * back to `navigator.modelContext`). Builds the descriptors, wraps each in an
6
- * `execute` that validates → maps to commands → gates → runs one
7
- * `executeBatch` transaction, and registers the lot under one AbortSignal so
8
- * detaching is a single `abort()`.
4
+ * The only file that touches the browser's model context
5
+ * (`document.modelContext`, falling back to `navigator.modelContext`). Builds
6
+ * a tool runtime for the instance, registers each of its tools with an
7
+ * `execute` that delegates to `runTool()`, and registers the lot under one
8
+ * AbortSignal so detaching is a single `abort()`. What a call *does* — validation, the gate, the batch —
9
+ * lives in `runtime.ts`, which the chat panel shares.
9
10
  *
10
11
  * @module webmcp/register
11
12
  */
12
- import { executeBatch } from '../commands/batch.js';
13
- import { createStoreCommandContext } from '../commands/storeIntegration.svelte.js';
14
- import { isLayoutCommand, isMutatingCommand, isViewCommand } from '../chat/commandClassifier.js';
15
- import { getBehaviorSettings } from '../stores/settingsStore.svelte.js';
16
13
  import { logger } from '../utils/logger.js';
17
- import { buildToolDescriptors } from './descriptors.js';
18
- import { validateToolArgs } from './validate.js';
19
- import { createApprovalGate, GateBusyError } from './gate.js';
20
- import { ToolArgumentError } from './types.js';
14
+ import { createToolRuntime } from './runtime.js';
21
15
  export const DEFAULT_PREFIX = 'flowdrop';
22
- /** Wording shared with the chat panel's CommandPreview (issue #36). */
23
- const LAYOUT_SKIPPED = 'Skipped — AI layout changes are disabled in Settings';
24
16
  // ============================================================================
25
17
  // Runtime detection
26
18
  // ============================================================================
27
19
  /**
28
- * Find the WebMCP runtime on this page, or `null` when the browser has none.
20
+ * Find the WebMCP model context on this page, or `null` when the browser has none.
29
21
  * Structural: anything with a callable `registerTool` counts.
30
22
  */
31
23
  export function detectModelContext() {
@@ -45,14 +37,14 @@ export function detectModelContext() {
45
37
  return null;
46
38
  }
47
39
  // ============================================================================
48
- // Prefix registry (D2) — one registration per prefix per runtime
40
+ // Prefix registry (D2) — one registration per prefix per model context
49
41
  // ============================================================================
50
42
  const claimedPrefixes = new WeakMap();
51
- function claimPrefix(runtime, prefix) {
52
- let set = claimedPrefixes.get(runtime);
43
+ function claimPrefix(modelContext, prefix) {
44
+ let set = claimedPrefixes.get(modelContext);
53
45
  if (!set) {
54
46
  set = new Set();
55
- claimedPrefixes.set(runtime, set);
47
+ claimedPrefixes.set(modelContext, set);
56
48
  }
57
49
  if (set.has(prefix)) {
58
50
  throw new Error(`[flowdrop] WebMCP tools with prefix "${prefix}" are already registered on this page. ` +
@@ -60,41 +52,8 @@ function claimPrefix(runtime, prefix) {
60
52
  }
61
53
  set.add(prefix);
62
54
  }
63
- function releasePrefix(runtime, prefix) {
64
- claimedPrefixes.get(runtime)?.delete(prefix);
65
- }
66
- // ============================================================================
67
- // Result formatting
68
- // ============================================================================
69
- function text(payload, isError = false) {
70
- return {
71
- content: [{ type: 'text', text: JSON.stringify(payload) }],
72
- ...(isError ? { isError: true } : {})
73
- };
74
- }
75
- function errorResult(code, message) {
76
- return text({ ok: false, code, error: message }, true);
77
- }
78
- function stripResult(result) {
79
- if (result.ok) {
80
- const out = { ok: true, message: result.message };
81
- if (result.data !== undefined)
82
- out.data = result.data;
83
- if (result.uiActionPending)
84
- out.uiActionPending = true;
85
- return out;
86
- }
87
- return { ok: false, code: result.code, error: result.error };
88
- }
89
- /**
90
- * The gate exists because any agent on the page can alter the user's
91
- * document. A command that only moves the view — selection, a panel, the
92
- * viewport — alters nothing the user would need to undo, so it runs unasked;
93
- * `undo` and `redo` change the document and stay gated. A batch is gated as a
94
- * whole when any of its items is.
95
- */
96
- function needsApproval(commands) {
97
- return commands.some((c) => isMutatingCommand(c.type) && !isViewCommand(c.type));
55
+ function releasePrefix(modelContext, prefix) {
56
+ claimedPrefixes.get(modelContext)?.delete(prefix);
98
57
  }
99
58
  // ============================================================================
100
59
  // attach
@@ -103,12 +62,12 @@ function needsApproval(commands) {
103
62
  * Register the editor's commands as WebMCP tools for `instance`.
104
63
  *
105
64
  * Returns `null` — with no console output — when the page has no WebMCP
106
- * runtime, so hosts can call it unconditionally. Throws when the prefix is
107
- * already registered on this runtime (two editors on one page need distinct
65
+ * model context, so hosts can call it unconditionally. Throws when the prefix is
66
+ * already registered on this model context (two editors on one page need distinct
108
67
  * prefixes).
109
68
  *
110
69
  * Registration settles asynchronously: `handle.tools` lists the tools the
111
- * runtime has accepted so far and `handle.ready` resolves when every
70
+ * model context has accepted so far and `handle.ready` resolves when every
112
71
  * registration has settled. The registration is torn down by
113
72
  * `handle.detach()` or automatically when `instance.destroy()` runs.
114
73
  */
@@ -116,141 +75,94 @@ export function attachWebMCP(instance, options = {}) {
116
75
  const detected = options.modelContext ?? detectModelContext();
117
76
  if (!detected)
118
77
  return null;
119
- const runtime = detected;
78
+ const modelContext = detected;
120
79
  const prefix = options.prefix ?? DEFAULT_PREFIX;
121
80
  if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(prefix)) {
122
81
  throw new Error(`[flowdrop] Invalid WebMCP prefix "${prefix}"`);
123
82
  }
124
- claimPrefix(runtime, prefix);
125
- const nodeTypes = () => {
126
- const source = options.nodeTypes;
127
- if (source === undefined)
128
- return instance.nodeTypes.current;
129
- return typeof source === 'function' ? source() : source;
130
- };
83
+ claimPrefix(modelContext, prefix);
131
84
  const editorName = () => instance.workflow.current?.name ?? instance.id;
132
- const gate = createApprovalGate(options.approval ?? 'confirm', {
85
+ // One gate per editor (see `FlowDropInstance.approvalGate`): reuse the one
86
+ // another surface published, or publish ours.
87
+ const { onSave, onRun, onRunStatus } = options;
88
+ const sharedGate = instance.approvalGate;
89
+ const tools = createToolRuntime({
90
+ instance,
91
+ nodeTypes: options.nodeTypes,
92
+ onUIAction: options.onUIAction,
93
+ hooks: { onSave, onRun, onRunStatus },
94
+ gate: sharedGate ?? undefined,
95
+ approval: options.approval,
133
96
  container: options.container,
134
- editorName,
135
- messages: options.messages
97
+ messages: options.messages,
98
+ rememberEdits: options.rememberEdits
136
99
  });
100
+ if (!sharedGate)
101
+ instance.approvalGate = tools.gate;
137
102
  const controller = new AbortController();
138
- const descriptors = buildToolDescriptors({ view: Boolean(options.onUIAction) });
139
103
  const names = [];
140
104
  let attached = true;
141
- // ---- execute ------------------------------------------------------------
142
- async function run(descriptor, input) {
143
- if (!attached)
144
- return errorResult('DETACHED', 'This editor is no longer available');
145
- let commands;
146
- try {
147
- commands = descriptor.toCommands(validateToolArgs(descriptor.inputSchema, input));
148
- }
149
- catch (err) {
150
- if (err instanceof ToolArgumentError)
151
- return errorResult('INVALID_ARGUMENTS', err.message);
152
- throw err;
153
- }
154
- // D4: honour the layout opt-out with the chat panel's wording. A skip is
155
- // not a failure; the rest of a batch still applies.
156
- const skipped = [];
157
- if (!getBehaviorSettings().chatAllowLayoutChanges) {
158
- commands = commands.filter((c) => {
159
- if (isLayoutCommand(c.type)) {
160
- skipped.push(c);
161
- return false;
162
- }
163
- return true;
164
- });
165
- }
166
- if (commands.length === 0) {
167
- return text({
168
- ok: true,
169
- results: [],
170
- skipped: skipped.map((c) => ({ type: c.type, reason: LAYOUT_SKIPPED })),
171
- completedCount: 0,
172
- totalCount: 0
173
- });
174
- }
175
- const context = createStoreCommandContext(nodeTypes(), options.onUIAction, instance);
176
- if (!context)
177
- return errorResult('NO_WORKFLOW', 'No workflow is loaded in this editor');
178
- // D3: reads and view changes run; document changes wait for the gate.
179
- if (needsApproval(commands)) {
180
- let approved;
181
- try {
182
- approved = await gate.request(commands);
183
- }
184
- catch (err) {
185
- if (err instanceof GateBusyError)
186
- return errorResult('BUSY', err.message);
187
- throw err;
188
- }
189
- if (!approved)
190
- return errorResult('REJECTED', 'The user rejected the change');
191
- if (!attached)
192
- return errorResult('DETACHED', 'This editor is no longer available');
193
- }
194
- // Every call is one transaction and one undo step, like the chat panel.
195
- const batch = executeBatch(commands, context);
196
- if (commands.length === 1 && descriptor.verb !== 'batch' && skipped.length === 0) {
197
- const only = batch.results[0];
198
- return text(stripResult(only), !only.ok);
199
- }
200
- return text({
201
- ok: batch.ok,
202
- results: batch.results.map(stripResult),
203
- ...(skipped.length > 0
204
- ? { skipped: skipped.map((c) => ({ type: c.type, reason: LAYOUT_SKIPPED })) }
205
- : {}),
206
- completedCount: batch.completedCount,
207
- totalCount: batch.totalCount,
208
- ...(batch.ok ? {} : { error: batch.error, rolledBack: true })
209
- }, !batch.ok);
210
- }
211
105
  // ---- register -----------------------------------------------------------
212
106
  const nameSuffix = ` Editor: "${editorName()}".`;
213
- async function register(descriptor) {
214
- const name = `${prefix}_${descriptor.verb}`;
215
- const tool = {
216
- name,
217
- description: descriptor.description + nameSuffix,
218
- inputSchema: descriptor.inputSchema,
219
- annotations: { readOnlyHint: descriptor.readOnly },
220
- execute: (input) => run(descriptor, input)
221
- };
107
+ async function registerRaw(tool) {
222
108
  try {
223
- // The spec returns a promise that rejects when the runtime refuses the
224
- // tool; pre-spec runtimes return nothing, which `await` takes as accepted.
225
- await runtime.registerTool(tool, { signal: controller.signal });
109
+ // The spec returns a promise that rejects when the model context refuses
110
+ // the tool; pre-spec ones return nothing, which `await` takes as accepted.
111
+ await modelContext.registerTool(tool, { signal: controller.signal });
226
112
  }
227
113
  catch (err) {
228
- logger.warn(`WebMCP: the runtime refused tool "${name}":`, err instanceof Error ? err.message : err);
114
+ logger.warn(`WebMCP: the model context refused tool "${tool.name}":`, err instanceof Error ? err.message : err);
229
115
  return;
230
116
  }
231
117
  if (attached)
232
- names.push(name);
118
+ names.push(tool.name);
119
+ }
120
+ function register(descriptor) {
121
+ return registerRaw({
122
+ name: `${prefix}_${descriptor.verb}`,
123
+ description: descriptor.description + nameSuffix,
124
+ inputSchema: descriptor.inputSchema,
125
+ annotations: { readOnlyHint: descriptor.readOnly },
126
+ execute: (input) => tools.runTool(descriptor.verb, input)
127
+ });
128
+ }
129
+ function registerHost(descriptor) {
130
+ return registerRaw({
131
+ name: `${prefix}_${descriptor.verb}`,
132
+ description: descriptor.description + nameSuffix,
133
+ inputSchema: descriptor.inputSchema,
134
+ annotations: {
135
+ readOnlyHint: descriptor.readOnly,
136
+ ...(descriptor.consequential ? { consequentialHint: true } : {})
137
+ },
138
+ execute: (input) => tools.runTool(descriptor.verb, input)
139
+ });
233
140
  }
234
- const ready = Promise.all(descriptors.map(register)).then(() => undefined);
141
+ const ready = Promise.all([
142
+ ...tools.descriptors.map(register),
143
+ ...tools.hostTools.map(registerHost)
144
+ ]).then(() => undefined);
235
145
  // ---- detach -------------------------------------------------------------
236
146
  function detach() {
237
147
  if (!attached)
238
148
  return;
239
149
  attached = false;
240
150
  unsubscribeDestroy();
241
- gate.dispose();
151
+ if (instance.approvalGate === tools.gate && !sharedGate)
152
+ instance.approvalGate = null;
153
+ tools.dispose();
242
154
  controller.abort();
243
- if (typeof runtime.unregisterTool === 'function') {
155
+ if (typeof modelContext.unregisterTool === 'function') {
244
156
  for (const name of names) {
245
157
  try {
246
- runtime.unregisterTool(name);
158
+ modelContext.unregisterTool(name);
247
159
  }
248
160
  catch {
249
- // Pre-spec runtime quirks are not ours to surface.
161
+ // Pre-spec model-context quirks are not ours to surface.
250
162
  }
251
163
  }
252
164
  }
253
- releasePrefix(runtime, prefix);
165
+ releasePrefix(modelContext, prefix);
254
166
  }
255
167
  // Detach when the instance goes away.
256
168
  const unsubscribeDestroy = instance.onDestroy(detach);
@@ -0,0 +1,33 @@
1
+ /**
2
+ * WebMCP adapter — the tool runtime.
3
+ *
4
+ * One place that turns a tool name and its arguments into an effect on the
5
+ * editor: validate → map to commands → honour the layout opt-out → ask the
6
+ * gate → run one `executeBatch` transaction → strip the result. The three
7
+ * host tools (`save`, `run`, `run_status`) live here too, behind the hooks
8
+ * the host supplied.
9
+ *
10
+ * Two callers share it. The WebMCP registration (`register.ts`) wraps
11
+ * `runTool` in each tool's `execute`; the chat panel's turn driver calls it
12
+ * for the tool calls the assistant makes. Both therefore go through the same
13
+ * validation, the same consent dialog, the same teaching errors and the same
14
+ * undo step — the point of the shared runtime is that there is no second,
15
+ * weaker path to the user's document.
16
+ *
17
+ * @module webmcp/runtime
18
+ */
19
+ import { type HostHooks, type HostToolDescriptor, type ToolRuntime, type ToolRuntimeOptions } from './types.js';
20
+ /**
21
+ * The host tools a set of hooks makes available, in registration order.
22
+ * `save` needs `onSave`; `run` needs `onRun`; `run_status` needs both `onRun`
23
+ * and `onRunStatus` (a status tool without a way to start a run has nothing
24
+ * to report on).
25
+ */
26
+ export declare function buildHostToolDescriptors(hooks: HostHooks): HostToolDescriptor[];
27
+ /**
28
+ * Build the runtime for one editor instance. Pure of the WebMCP API: it
29
+ * touches no `document.modelContext`, so it serves the chat panel as well as
30
+ * the registration. Dispose it when the caller goes away; a disposed runtime
31
+ * answers every call with `DETACHED`.
32
+ */
33
+ export declare function createToolRuntime(options: ToolRuntimeOptions): ToolRuntime;