@flowdrop/flowdrop 2.7.0 → 2.9.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/CHANGELOG.md +71 -1
- package/dist/api/enhanced-client.d.ts +29 -1
- package/dist/api/enhanced-client.js +83 -9
- package/dist/chat/index.d.ts +5 -1
- package/dist/chat/index.js +2 -0
- package/dist/chat/toolCatalogue.d.ts +27 -0
- package/dist/chat/toolCatalogue.js +35 -0
- package/dist/chat/turnDriver.d.ts +143 -0
- package/dist/chat/turnDriver.js +124 -0
- package/dist/components/App.svelte +47 -56
- package/dist/components/SettingsPanel.svelte +13 -0
- package/dist/components/WorkflowEditor.svelte +4 -2
- package/dist/components/WorkflowEditor.svelte.d.ts +2 -0
- package/dist/components/chat/AIChatPanel.svelte +410 -22
- package/dist/components/form/FieldFactory.svelte +478 -0
- package/dist/components/form/FieldFactory.svelte.d.ts +14 -0
- package/dist/components/form/FormField.svelte +19 -404
- package/dist/components/form/FormField.svelte.d.ts +2 -27
- package/dist/components/form/FormFieldLight.svelte +11 -424
- package/dist/components/form/FormFieldLight.svelte.d.ts +2 -28
- package/dist/components/form/FormMarkdownEditor.svelte +11 -4
- package/dist/components/form/FormTemplateEditor.svelte +12 -5
- package/dist/components/form/resolveFieldType.d.ts +18 -15
- package/dist/components/form/resolveFieldType.js +33 -12
- package/dist/components/form/types.d.ts +14 -2
- package/dist/components/toast/DismissibleToast.svelte +53 -0
- package/dist/components/toast/DismissibleToast.svelte.d.ts +24 -0
- package/dist/components/toast/WarningIcon.svelte +28 -0
- package/dist/components/toast/WarningIcon.svelte.d.ts +26 -0
- package/dist/config/constants.d.ts +7 -3
- package/dist/config/constants.js +7 -3
- package/dist/config/endpoints.d.ts +7 -0
- package/dist/config/endpoints.js +2 -1
- package/dist/editor/index.d.ts +1 -1
- package/dist/editor/index.js +1 -1
- package/dist/messages/defaults.d.ts +41 -0
- package/dist/messages/defaults.js +20 -0
- package/dist/services/chatService.d.ts +21 -3
- package/dist/services/chatService.js +33 -1
- package/dist/services/globalSave.js +3 -1
- package/dist/services/toastService.d.ts +23 -2
- package/dist/services/toastService.js +72 -28
- package/dist/stores/instanceContainer.svelte.d.ts +34 -0
- package/dist/stores/instanceContainer.svelte.js +30 -0
- package/dist/styles/toast.css +62 -0
- package/dist/svelte-app.d.ts +12 -2
- package/dist/svelte-app.js +29 -12
- package/dist/types/chat.d.ts +59 -0
- package/dist/types/events.d.ts +23 -0
- package/dist/types/events.js +3 -1
- package/dist/types/settings.d.ts +18 -1
- package/dist/types/settings.js +1 -0
- package/dist/webmcp/WebMCPConfirm.svelte +129 -68
- package/dist/webmcp/WebMCPConfirm.svelte.d.ts +2 -2
- package/dist/webmcp/descriptors.d.ts +7 -0
- package/dist/webmcp/descriptors.js +51 -0
- package/dist/webmcp/gate.d.ts +13 -7
- package/dist/webmcp/gate.js +8 -53
- package/dist/webmcp/index.d.ts +5 -2
- package/dist/webmcp/index.js +3 -1
- package/dist/webmcp/register.d.ts +11 -10
- package/dist/webmcp/register.js +59 -384
- package/dist/webmcp/runtime.d.ts +33 -0
- package/dist/webmcp/runtime.js +500 -0
- package/dist/webmcp/types.d.ts +92 -0
- package/package.json +1 -1
package/dist/webmcp/register.js
CHANGED
|
@@ -1,31 +1,23 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* WebMCP adapter — registration.
|
|
3
3
|
*
|
|
4
|
-
* The only file that touches the
|
|
5
|
-
* back to `navigator.modelContext`). Builds
|
|
6
|
-
*
|
|
7
|
-
* `
|
|
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 {
|
|
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
|
|
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
|
|
40
|
+
// Prefix registry (D2) — one registration per prefix per model context
|
|
49
41
|
// ============================================================================
|
|
50
42
|
const claimedPrefixes = new WeakMap();
|
|
51
|
-
function claimPrefix(
|
|
52
|
-
let set = claimedPrefixes.get(
|
|
43
|
+
function claimPrefix(modelContext, prefix) {
|
|
44
|
+
let set = claimedPrefixes.get(modelContext);
|
|
53
45
|
if (!set) {
|
|
54
46
|
set = new Set();
|
|
55
|
-
claimedPrefixes.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,73 +52,8 @@ function claimPrefix(runtime, prefix) {
|
|
|
60
52
|
}
|
|
61
53
|
set.add(prefix);
|
|
62
54
|
}
|
|
63
|
-
function releasePrefix(
|
|
64
|
-
claimedPrefixes.get(
|
|
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, extra = {}) {
|
|
76
|
-
return text({ ok: false, code, error: message, ...extra }, true);
|
|
77
|
-
}
|
|
78
|
-
/**
|
|
79
|
-
* A host envelope as a tool result. `ok: false` is an error result with the
|
|
80
|
-
* host's code; `ok: true` keeps `code` (e.g. `PENDING`) and passes `data` and
|
|
81
|
-
* `can` through untouched — the agent reads them, the adapter never does.
|
|
82
|
-
*/
|
|
83
|
-
function envelopeResult(envelope, fallbackMessage) {
|
|
84
|
-
const message = envelope.message ?? fallbackMessage;
|
|
85
|
-
if (!envelope.ok) {
|
|
86
|
-
return errorResult(envelope.code ?? 'FAILED', message, {
|
|
87
|
-
...(envelope.data !== undefined ? { data: envelope.data } : {}),
|
|
88
|
-
...(envelope.can ? { can: envelope.can } : {})
|
|
89
|
-
});
|
|
90
|
-
}
|
|
91
|
-
return text({
|
|
92
|
-
ok: true,
|
|
93
|
-
...(envelope.code ? { code: envelope.code } : {}),
|
|
94
|
-
message,
|
|
95
|
-
...(envelope.data !== undefined ? { data: envelope.data } : {}),
|
|
96
|
-
...(envelope.can ? { can: envelope.can } : {})
|
|
97
|
-
});
|
|
98
|
-
}
|
|
99
|
-
/**
|
|
100
|
-
* Whether a thrown save error is the server saying the copy moved on. The
|
|
101
|
-
* library's `ApiError` carries the parsed body as `errorData` (fddo publishes
|
|
102
|
-
* `error_code: 'CONFLICT'` with a 409); a bare 409 counts too.
|
|
103
|
-
*/
|
|
104
|
-
function isConflictError(err) {
|
|
105
|
-
if (!err || typeof err !== 'object')
|
|
106
|
-
return false;
|
|
107
|
-
const e = err;
|
|
108
|
-
return e.errorData?.error_code === 'CONFLICT' || e.status === 409;
|
|
109
|
-
}
|
|
110
|
-
function stripResult(result) {
|
|
111
|
-
if (result.ok) {
|
|
112
|
-
const out = { ok: true, message: result.message };
|
|
113
|
-
if (result.data !== undefined)
|
|
114
|
-
out.data = result.data;
|
|
115
|
-
if (result.uiActionPending)
|
|
116
|
-
out.uiActionPending = true;
|
|
117
|
-
return out;
|
|
118
|
-
}
|
|
119
|
-
return { ok: false, code: result.code, error: result.error };
|
|
120
|
-
}
|
|
121
|
-
/**
|
|
122
|
-
* The gate exists because any agent on the page can alter the user's
|
|
123
|
-
* document. A command that only moves the view — selection, a panel, the
|
|
124
|
-
* viewport — alters nothing the user would need to undo, so it runs unasked;
|
|
125
|
-
* `undo` and `redo` change the document and stay gated. A batch is gated as a
|
|
126
|
-
* whole when any of its items is.
|
|
127
|
-
*/
|
|
128
|
-
function needsApproval(commands) {
|
|
129
|
-
return commands.some((c) => isMutatingCommand(c.type) && !isViewCommand(c.type));
|
|
55
|
+
function releasePrefix(modelContext, prefix) {
|
|
56
|
+
claimedPrefixes.get(modelContext)?.delete(prefix);
|
|
130
57
|
}
|
|
131
58
|
// ============================================================================
|
|
132
59
|
// attach
|
|
@@ -135,12 +62,12 @@ function needsApproval(commands) {
|
|
|
135
62
|
* Register the editor's commands as WebMCP tools for `instance`.
|
|
136
63
|
*
|
|
137
64
|
* Returns `null` — with no console output — when the page has no WebMCP
|
|
138
|
-
*
|
|
139
|
-
* already registered on this
|
|
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
|
|
140
67
|
* prefixes).
|
|
141
68
|
*
|
|
142
69
|
* Registration settles asynchronously: `handle.tools` lists the tools the
|
|
143
|
-
*
|
|
70
|
+
* model context has accepted so far and `handle.ready` resolves when every
|
|
144
71
|
* registration has settled. The registration is torn down by
|
|
145
72
|
* `handle.detach()` or automatically when `instance.destroy()` runs.
|
|
146
73
|
*/
|
|
@@ -148,269 +75,43 @@ export function attachWebMCP(instance, options = {}) {
|
|
|
148
75
|
const detected = options.modelContext ?? detectModelContext();
|
|
149
76
|
if (!detected)
|
|
150
77
|
return null;
|
|
151
|
-
const
|
|
78
|
+
const modelContext = detected;
|
|
152
79
|
const prefix = options.prefix ?? DEFAULT_PREFIX;
|
|
153
80
|
if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(prefix)) {
|
|
154
81
|
throw new Error(`[flowdrop] Invalid WebMCP prefix "${prefix}"`);
|
|
155
82
|
}
|
|
156
|
-
claimPrefix(
|
|
157
|
-
const nodeTypes = () => {
|
|
158
|
-
const source = options.nodeTypes;
|
|
159
|
-
if (source === undefined)
|
|
160
|
-
return instance.nodeTypes.current;
|
|
161
|
-
return typeof source === 'function' ? source() : source;
|
|
162
|
-
};
|
|
83
|
+
claimPrefix(modelContext, prefix);
|
|
163
84
|
const editorName = () => instance.workflow.current?.name ?? instance.id;
|
|
164
|
-
|
|
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,
|
|
165
96
|
container: options.container,
|
|
166
|
-
editorName,
|
|
167
97
|
messages: options.messages,
|
|
168
98
|
rememberEdits: options.rememberEdits
|
|
169
99
|
});
|
|
100
|
+
if (!sharedGate)
|
|
101
|
+
instance.approvalGate = tools.gate;
|
|
170
102
|
const controller = new AbortController();
|
|
171
|
-
const descriptors = buildToolDescriptors({ view: Boolean(options.onUIAction) });
|
|
172
103
|
const names = [];
|
|
173
104
|
let attached = true;
|
|
174
|
-
// ---- execute ------------------------------------------------------------
|
|
175
|
-
async function run(descriptor, input) {
|
|
176
|
-
if (!attached)
|
|
177
|
-
return errorResult('DETACHED', 'This editor is no longer available');
|
|
178
|
-
let commands;
|
|
179
|
-
try {
|
|
180
|
-
commands = descriptor.toCommands(validateToolArgs(descriptor.inputSchema, input));
|
|
181
|
-
}
|
|
182
|
-
catch (err) {
|
|
183
|
-
if (err instanceof ToolArgumentError)
|
|
184
|
-
return errorResult('INVALID_ARGUMENTS', err.message);
|
|
185
|
-
throw err;
|
|
186
|
-
}
|
|
187
|
-
// D4: honour the layout opt-out with the chat panel's wording. A skip is
|
|
188
|
-
// not a failure; the rest of a batch still applies.
|
|
189
|
-
const skipped = [];
|
|
190
|
-
if (!getBehaviorSettings().chatAllowLayoutChanges) {
|
|
191
|
-
commands = commands.filter((c) => {
|
|
192
|
-
if (isLayoutCommand(c.type)) {
|
|
193
|
-
skipped.push(c);
|
|
194
|
-
return false;
|
|
195
|
-
}
|
|
196
|
-
return true;
|
|
197
|
-
});
|
|
198
|
-
}
|
|
199
|
-
if (commands.length === 0) {
|
|
200
|
-
return text({
|
|
201
|
-
ok: true,
|
|
202
|
-
results: [],
|
|
203
|
-
skipped: skipped.map((c) => ({ type: c.type, reason: LAYOUT_SKIPPED })),
|
|
204
|
-
completedCount: 0,
|
|
205
|
-
totalCount: 0
|
|
206
|
-
});
|
|
207
|
-
}
|
|
208
|
-
const context = createStoreCommandContext(nodeTypes(), options.onUIAction, instance);
|
|
209
|
-
if (!context)
|
|
210
|
-
return errorResult('NO_WORKFLOW', 'No workflow is loaded in this editor');
|
|
211
|
-
// D3: reads and view changes run; document changes wait for the gate.
|
|
212
|
-
if (needsApproval(commands)) {
|
|
213
|
-
let approved;
|
|
214
|
-
try {
|
|
215
|
-
approved = await gate.request(commands, { tool: descriptor.verb });
|
|
216
|
-
}
|
|
217
|
-
catch (err) {
|
|
218
|
-
if (err instanceof GateBusyError)
|
|
219
|
-
return errorResult('BUSY', err.message);
|
|
220
|
-
throw err;
|
|
221
|
-
}
|
|
222
|
-
if (!approved)
|
|
223
|
-
return errorResult('REJECTED', 'The user rejected the change');
|
|
224
|
-
if (!attached)
|
|
225
|
-
return errorResult('DETACHED', 'This editor is no longer available');
|
|
226
|
-
}
|
|
227
|
-
// Every call is one transaction and one undo step, like the chat panel.
|
|
228
|
-
const batch = executeBatch(commands, context);
|
|
229
|
-
if (commands.length === 1 && descriptor.verb !== 'batch' && skipped.length === 0) {
|
|
230
|
-
const only = batch.results[0];
|
|
231
|
-
return text(stripResult(only), !only.ok);
|
|
232
|
-
}
|
|
233
|
-
return text({
|
|
234
|
-
ok: batch.ok,
|
|
235
|
-
results: batch.results.map(stripResult),
|
|
236
|
-
...(skipped.length > 0
|
|
237
|
-
? { skipped: skipped.map((c) => ({ type: c.type, reason: LAYOUT_SKIPPED })) }
|
|
238
|
-
: {}),
|
|
239
|
-
completedCount: batch.completedCount,
|
|
240
|
-
totalCount: batch.totalCount,
|
|
241
|
-
...(batch.ok ? {} : { error: batch.error, rolledBack: true })
|
|
242
|
-
}, !batch.ok);
|
|
243
|
-
}
|
|
244
|
-
// ---- host tools: save, run, run_status --------------------------------
|
|
245
|
-
const EMPTY_SCHEMA = {
|
|
246
|
-
type: 'object',
|
|
247
|
-
properties: {},
|
|
248
|
-
additionalProperties: false
|
|
249
|
-
};
|
|
250
|
-
const RUN_SCHEMA = {
|
|
251
|
-
type: 'object',
|
|
252
|
-
properties: {
|
|
253
|
-
inputs: {
|
|
254
|
-
type: 'object',
|
|
255
|
-
description: "Values for the workflow's interface input ports, keyed by port name. Omit for a workflow with no inputs."
|
|
256
|
-
}
|
|
257
|
-
},
|
|
258
|
-
additionalProperties: false
|
|
259
|
-
};
|
|
260
|
-
const RUN_STATUS_SCHEMA = {
|
|
261
|
-
type: 'object',
|
|
262
|
-
properties: {
|
|
263
|
-
runId: { type: 'string', description: 'The `runId` returned by run.' }
|
|
264
|
-
},
|
|
265
|
-
required: ['runId'],
|
|
266
|
-
additionalProperties: false
|
|
267
|
-
};
|
|
268
|
-
/**
|
|
269
|
-
* The host's word on what the user may do with the workflow, when the
|
|
270
|
-
* payload it loaded carried one. `undefined` means the host said nothing —
|
|
271
|
-
* proceed and let the server decide (D3: the server is the authority; the
|
|
272
|
-
* client only pre-empts).
|
|
273
|
-
*/
|
|
274
|
-
function workflowCan(key) {
|
|
275
|
-
return instance.workflow.current?.can?.[key];
|
|
276
|
-
}
|
|
277
|
-
function validateOrError(schema, input) {
|
|
278
|
-
try {
|
|
279
|
-
return validateToolArgs(schema, input);
|
|
280
|
-
}
|
|
281
|
-
catch (err) {
|
|
282
|
-
if (err instanceof ToolArgumentError)
|
|
283
|
-
return errorResult('INVALID_ARGUMENTS', err.message);
|
|
284
|
-
throw err;
|
|
285
|
-
}
|
|
286
|
-
}
|
|
287
|
-
const isToolResult = (v) => typeof v === 'object' && v !== null && 'content' in v;
|
|
288
|
-
/** The gate, for a host tool with no commands of its own. */
|
|
289
|
-
async function askHostGate(tool) {
|
|
290
|
-
let approved;
|
|
291
|
-
try {
|
|
292
|
-
approved = await gate.request([], { tool });
|
|
293
|
-
}
|
|
294
|
-
catch (err) {
|
|
295
|
-
if (err instanceof GateBusyError)
|
|
296
|
-
return errorResult('BUSY', err.message);
|
|
297
|
-
throw err;
|
|
298
|
-
}
|
|
299
|
-
if (!approved)
|
|
300
|
-
return errorResult('REJECTED', 'The user rejected the change');
|
|
301
|
-
if (!attached)
|
|
302
|
-
return errorResult('DETACHED', 'This editor is no longer available');
|
|
303
|
-
return null;
|
|
304
|
-
}
|
|
305
|
-
/**
|
|
306
|
-
* `save` persists the workflow via the host's `onSave`. It has no commands
|
|
307
|
-
* of its own — nothing for `executeBatch` to run — so it is gated directly
|
|
308
|
-
* rather than going through `run()`'s command pipeline.
|
|
309
|
-
*/
|
|
310
|
-
async function runSave(onSave, input) {
|
|
311
|
-
if (!attached)
|
|
312
|
-
return errorResult('DETACHED', 'This editor is no longer available');
|
|
313
|
-
const args = validateOrError(EMPTY_SCHEMA, input);
|
|
314
|
-
if (isToolResult(args))
|
|
315
|
-
return args;
|
|
316
|
-
if (!instance.workflow.current) {
|
|
317
|
-
return errorResult('NO_WORKFLOW', 'No workflow is loaded in this editor');
|
|
318
|
-
}
|
|
319
|
-
if (workflowCan('save') === false) {
|
|
320
|
-
return errorResult('FORBIDDEN', 'Saving this workflow is not permitted');
|
|
321
|
-
}
|
|
322
|
-
const refused = await askHostGate('save');
|
|
323
|
-
if (refused)
|
|
324
|
-
return refused;
|
|
325
|
-
let envelope;
|
|
326
|
-
try {
|
|
327
|
-
envelope = await onSave();
|
|
328
|
-
}
|
|
329
|
-
catch (err) {
|
|
330
|
-
const message = err instanceof Error ? err.message : String(err);
|
|
331
|
-
if (!isConflictError(err))
|
|
332
|
-
return errorResult('SAVE_FAILED', message);
|
|
333
|
-
// The server's own wording usually already says to reload; add the hint
|
|
334
|
-
// only when it does not, so the agent is not told twice.
|
|
335
|
-
const hint = /reload/i.test(message)
|
|
336
|
-
? ''
|
|
337
|
-
: ' The workflow changed on the server since it was loaded; reload the page before saving.';
|
|
338
|
-
return errorResult('CONFLICT', `${message}${hint}`);
|
|
339
|
-
}
|
|
340
|
-
if (envelope)
|
|
341
|
-
return envelopeResult(envelope, 'Workflow saved');
|
|
342
|
-
return text({ ok: true, message: 'Workflow saved' });
|
|
343
|
-
}
|
|
344
|
-
/** `run` starts a run through the host's `onRun`; gated like `save`. */
|
|
345
|
-
async function runRun(onRun, input) {
|
|
346
|
-
if (!attached)
|
|
347
|
-
return errorResult('DETACHED', 'This editor is no longer available');
|
|
348
|
-
const args = validateOrError(RUN_SCHEMA, input);
|
|
349
|
-
if (isToolResult(args))
|
|
350
|
-
return args;
|
|
351
|
-
if (!instance.workflow.current) {
|
|
352
|
-
return errorResult('NO_WORKFLOW', 'No workflow is loaded in this editor');
|
|
353
|
-
}
|
|
354
|
-
if (workflowCan('run') === false) {
|
|
355
|
-
return errorResult('FORBIDDEN', 'Running this workflow is not permitted');
|
|
356
|
-
}
|
|
357
|
-
const refused = await askHostGate('run');
|
|
358
|
-
if (refused)
|
|
359
|
-
return refused;
|
|
360
|
-
let envelope;
|
|
361
|
-
try {
|
|
362
|
-
envelope = await onRun(args.inputs ?? {});
|
|
363
|
-
}
|
|
364
|
-
catch (err) {
|
|
365
|
-
return errorResult('RUN_FAILED', err instanceof Error ? err.message : String(err));
|
|
366
|
-
}
|
|
367
|
-
return envelopeResult(envelope, 'Run started');
|
|
368
|
-
}
|
|
369
|
-
/**
|
|
370
|
-
* `run_status` is a read: never gated. A paused run comes back `ok` with
|
|
371
|
-
* `code: 'PENDING'` and the pause's node and message — a person must act in
|
|
372
|
-
* the UI; no tool answers an interrupt (D8).
|
|
373
|
-
*/
|
|
374
|
-
async function runRunStatus(onRunStatus, input) {
|
|
375
|
-
if (!attached)
|
|
376
|
-
return errorResult('DETACHED', 'This editor is no longer available');
|
|
377
|
-
const args = validateOrError(RUN_STATUS_SCHEMA, input);
|
|
378
|
-
if (isToolResult(args))
|
|
379
|
-
return args;
|
|
380
|
-
let envelope;
|
|
381
|
-
try {
|
|
382
|
-
envelope = await onRunStatus(args.runId);
|
|
383
|
-
}
|
|
384
|
-
catch (err) {
|
|
385
|
-
return errorResult('STATUS_FAILED', err instanceof Error ? err.message : String(err));
|
|
386
|
-
}
|
|
387
|
-
if (envelope.ok && envelope.data?.status === 'paused' && !envelope.code) {
|
|
388
|
-
const p = envelope.data.pending;
|
|
389
|
-
const where = p?.nodeId ? ` at node ${p.nodeId}` : '';
|
|
390
|
-
const why = p?.message
|
|
391
|
-
? `: ${p.message}`
|
|
392
|
-
: envelope.data.pausedReason
|
|
393
|
-
? ` (${envelope.data.pausedReason})`
|
|
394
|
-
: '';
|
|
395
|
-
return envelopeResult({
|
|
396
|
-
...envelope,
|
|
397
|
-
code: 'PENDING',
|
|
398
|
-
message: envelope.message ??
|
|
399
|
-
`Run ${envelope.data.runId} is paused${where}${why}. A person must act in the editor; tell the user and poll run_status again.`
|
|
400
|
-
}, 'Run paused');
|
|
401
|
-
}
|
|
402
|
-
return envelopeResult(envelope, envelope.data ? `Run ${envelope.data.runId}: ${envelope.data.status}` : 'Run status');
|
|
403
|
-
}
|
|
404
105
|
// ---- register -----------------------------------------------------------
|
|
405
106
|
const nameSuffix = ` Editor: "${editorName()}".`;
|
|
406
107
|
async function registerRaw(tool) {
|
|
407
108
|
try {
|
|
408
|
-
// The spec returns a promise that rejects when the
|
|
409
|
-
// tool; pre-spec
|
|
410
|
-
await
|
|
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 });
|
|
411
112
|
}
|
|
412
113
|
catch (err) {
|
|
413
|
-
logger.warn(`WebMCP: the
|
|
114
|
+
logger.warn(`WebMCP: the model context refused tool "${tool.name}":`, err instanceof Error ? err.message : err);
|
|
414
115
|
return;
|
|
415
116
|
}
|
|
416
117
|
if (attached)
|
|
@@ -422,72 +123,46 @@ export function attachWebMCP(instance, options = {}) {
|
|
|
422
123
|
description: descriptor.description + nameSuffix,
|
|
423
124
|
inputSchema: descriptor.inputSchema,
|
|
424
125
|
annotations: { readOnlyHint: descriptor.readOnly },
|
|
425
|
-
execute: (input) =>
|
|
126
|
+
execute: (input) => tools.runTool(descriptor.verb, input)
|
|
426
127
|
});
|
|
427
128
|
}
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
inputSchema: EMPTY_SCHEMA,
|
|
440
|
-
annotations: { readOnlyHint: false, consequentialHint: true },
|
|
441
|
-
execute: (input) => runSave(onSave, input)
|
|
442
|
-
}));
|
|
443
|
-
}
|
|
444
|
-
if (onRun) {
|
|
445
|
-
toolRegistrations.push(registerRaw({
|
|
446
|
-
name: `${prefix}_run`,
|
|
447
|
-
description: 'Run the saved workflow on the server with optional inputs for its interface ports. ' +
|
|
448
|
-
'Save first: unsaved changes are not part of the run. Asks for approval. Returns a ' +
|
|
449
|
-
'`runId`' +
|
|
450
|
-
(onRunStatus ? ' to poll with run_status.' : '.') +
|
|
451
|
-
' Fails with FORBIDDEN when the user may not run, UNAVAILABLE when the workflow is not saved yet, ' +
|
|
452
|
-
'INVALID when the server rejected the workflow.' +
|
|
453
|
-
nameSuffix,
|
|
454
|
-
inputSchema: RUN_SCHEMA,
|
|
455
|
-
annotations: { readOnlyHint: false, consequentialHint: true },
|
|
456
|
-
execute: (input) => runRun(onRun, input)
|
|
457
|
-
}));
|
|
458
|
-
if (onRunStatus) {
|
|
459
|
-
toolRegistrations.push(registerRaw({
|
|
460
|
-
name: `${prefix}_run_status`,
|
|
461
|
-
description: 'Report the status of a run started with run: pending, running, paused, completed, failed or cancelled, ' +
|
|
462
|
-
'with outputs once it completed. A paused run answers code PENDING with the node and message it waits on — ' +
|
|
463
|
-
'a person must act in the editor; tell the user, then poll again. Read-only.' +
|
|
464
|
-
nameSuffix,
|
|
465
|
-
inputSchema: RUN_STATUS_SCHEMA,
|
|
466
|
-
annotations: { readOnlyHint: true },
|
|
467
|
-
execute: (input) => runRunStatus(onRunStatus, input)
|
|
468
|
-
}));
|
|
469
|
-
}
|
|
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
|
+
});
|
|
470
140
|
}
|
|
471
|
-
const ready = Promise.all(
|
|
141
|
+
const ready = Promise.all([
|
|
142
|
+
...tools.descriptors.map(register),
|
|
143
|
+
...tools.hostTools.map(registerHost)
|
|
144
|
+
]).then(() => undefined);
|
|
472
145
|
// ---- detach -------------------------------------------------------------
|
|
473
146
|
function detach() {
|
|
474
147
|
if (!attached)
|
|
475
148
|
return;
|
|
476
149
|
attached = false;
|
|
477
150
|
unsubscribeDestroy();
|
|
478
|
-
gate
|
|
151
|
+
if (instance.approvalGate === tools.gate && !sharedGate)
|
|
152
|
+
instance.approvalGate = null;
|
|
153
|
+
tools.dispose();
|
|
479
154
|
controller.abort();
|
|
480
|
-
if (typeof
|
|
155
|
+
if (typeof modelContext.unregisterTool === 'function') {
|
|
481
156
|
for (const name of names) {
|
|
482
157
|
try {
|
|
483
|
-
|
|
158
|
+
modelContext.unregisterTool(name);
|
|
484
159
|
}
|
|
485
160
|
catch {
|
|
486
|
-
// Pre-spec
|
|
161
|
+
// Pre-spec model-context quirks are not ours to surface.
|
|
487
162
|
}
|
|
488
163
|
}
|
|
489
164
|
}
|
|
490
|
-
releasePrefix(
|
|
165
|
+
releasePrefix(modelContext, prefix);
|
|
491
166
|
}
|
|
492
167
|
// Detach when the instance goes away.
|
|
493
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;
|