@flowdrop/flowdrop 2.5.0 → 2.7.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 +59 -0
- package/dist/chat/commandClassifier.d.ts +19 -1
- package/dist/chat/commandClassifier.js +33 -1
- package/dist/chat/index.d.ts +1 -1
- package/dist/chat/index.js +1 -1
- package/dist/commands/executor.js +270 -37
- package/dist/commands/index.d.ts +1 -1
- package/dist/commands/parser.js +20 -0
- package/dist/commands/types.d.ts +77 -12
- package/dist/components/App.svelte +8 -0
- package/dist/components/BindablePortListbox.svelte +426 -0
- package/dist/components/BindablePortListbox.svelte.d.ts +23 -0
- package/dist/components/WorkflowInterfaceEditor.svelte +142 -36
- package/dist/components/WorkflowInterfaceEditor.svelte.d.ts +8 -0
- package/dist/components/WorkflowInterfaceEntryCard.svelte +537 -294
- package/dist/components/WorkflowInterfaceEntryCard.svelte.d.ts +6 -3
- package/dist/components/WorkflowInterfaceEntryComposer.svelte +331 -0
- package/dist/components/WorkflowInterfaceEntryComposer.svelte.d.ts +19 -0
- package/dist/components/console/CommandConsole.svelte +8 -0
- package/dist/components/console/formatters.d.ts +9 -1
- package/dist/components/console/formatters.js +54 -0
- package/dist/core/index.d.ts +1 -1
- package/dist/messages/context.d.ts +6 -0
- package/dist/messages/context.js +8 -0
- package/dist/messages/defaults.d.ts +78 -2
- package/dist/messages/defaults.js +50 -3
- package/dist/messages/index.d.ts +1 -1
- package/dist/messages/index.js +1 -1
- package/dist/services/globalSave.d.ts +7 -1
- package/dist/services/globalSave.js +17 -3
- package/dist/stores/instanceContainer.svelte.d.ts +26 -0
- package/dist/stores/instanceContainer.svelte.js +24 -0
- package/dist/stores/workflowStore.svelte.d.ts +10 -0
- package/dist/stores/workflowStore.svelte.js +15 -0
- package/dist/stories/WebMCPFakeAgent.svelte +229 -0
- package/dist/stories/WebMCPFakeAgent.svelte.d.ts +10 -0
- package/dist/styles/base.css +4 -2
- package/dist/styles/tokens.css +6 -0
- package/dist/svelte-app.d.ts +24 -2
- package/dist/svelte-app.js +65 -3
- package/dist/types/index.d.ts +49 -0
- package/dist/utils/focus.d.ts +18 -0
- package/dist/utils/focus.js +24 -0
- package/dist/utils/whenWorkflowLoaded.svelte.d.ts +17 -0
- package/dist/utils/whenWorkflowLoaded.svelte.js +42 -0
- package/dist/utils/workflowInterface.d.ts +47 -3
- package/dist/utils/workflowInterface.js +84 -9
- package/dist/webmcp/WebMCP.stories.svelte +101 -0
- package/dist/webmcp/WebMCP.stories.svelte.d.ts +18 -0
- package/dist/webmcp/WebMCPConfirm.svelte +216 -0
- package/dist/webmcp/WebMCPConfirm.svelte.d.ts +21 -0
- package/dist/webmcp/bridge.d.ts +63 -0
- package/dist/webmcp/bridge.js +106 -0
- package/dist/webmcp/descriptors.d.ts +59 -0
- package/dist/webmcp/descriptors.js +504 -0
- package/dist/webmcp/fake.d.ts +23 -0
- package/dist/webmcp/fake.js +42 -0
- package/dist/webmcp/gate.d.ts +76 -0
- package/dist/webmcp/gate.js +188 -0
- package/dist/webmcp/index.d.ts +36 -0
- package/dist/webmcp/index.js +32 -0
- package/dist/webmcp/register.d.ts +33 -0
- package/dist/webmcp/register.js +504 -0
- package/dist/webmcp/types.d.ts +268 -0
- package/dist/webmcp/types.js +23 -0
- package/dist/webmcp/validate.d.ts +32 -0
- package/dist/webmcp/validate.js +118 -0
- package/package.json +6 -1
|
@@ -0,0 +1,504 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* WebMCP adapter — registration.
|
|
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()`.
|
|
9
|
+
*
|
|
10
|
+
* @module webmcp/register
|
|
11
|
+
*/
|
|
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
|
+
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';
|
|
21
|
+
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
|
+
// ============================================================================
|
|
25
|
+
// Runtime detection
|
|
26
|
+
// ============================================================================
|
|
27
|
+
/**
|
|
28
|
+
* Find the WebMCP runtime on this page, or `null` when the browser has none.
|
|
29
|
+
* Structural: anything with a callable `registerTool` counts.
|
|
30
|
+
*/
|
|
31
|
+
export function detectModelContext() {
|
|
32
|
+
if (typeof document === 'undefined')
|
|
33
|
+
return null;
|
|
34
|
+
const candidates = [
|
|
35
|
+
document.modelContext,
|
|
36
|
+
typeof navigator !== 'undefined'
|
|
37
|
+
? navigator.modelContext
|
|
38
|
+
: undefined
|
|
39
|
+
];
|
|
40
|
+
for (const c of candidates) {
|
|
41
|
+
if (c && typeof c.registerTool === 'function') {
|
|
42
|
+
return c;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return null;
|
|
46
|
+
}
|
|
47
|
+
// ============================================================================
|
|
48
|
+
// Prefix registry (D2) — one registration per prefix per runtime
|
|
49
|
+
// ============================================================================
|
|
50
|
+
const claimedPrefixes = new WeakMap();
|
|
51
|
+
function claimPrefix(runtime, prefix) {
|
|
52
|
+
let set = claimedPrefixes.get(runtime);
|
|
53
|
+
if (!set) {
|
|
54
|
+
set = new Set();
|
|
55
|
+
claimedPrefixes.set(runtime, set);
|
|
56
|
+
}
|
|
57
|
+
if (set.has(prefix)) {
|
|
58
|
+
throw new Error(`[flowdrop] WebMCP tools with prefix "${prefix}" are already registered on this page. ` +
|
|
59
|
+
`Pass a distinct \`prefix\` for each editor instance.`);
|
|
60
|
+
}
|
|
61
|
+
set.add(prefix);
|
|
62
|
+
}
|
|
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, 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));
|
|
130
|
+
}
|
|
131
|
+
// ============================================================================
|
|
132
|
+
// attach
|
|
133
|
+
// ============================================================================
|
|
134
|
+
/**
|
|
135
|
+
* Register the editor's commands as WebMCP tools for `instance`.
|
|
136
|
+
*
|
|
137
|
+
* Returns `null` — with no console output — when the page has no WebMCP
|
|
138
|
+
* runtime, so hosts can call it unconditionally. Throws when the prefix is
|
|
139
|
+
* already registered on this runtime (two editors on one page need distinct
|
|
140
|
+
* prefixes).
|
|
141
|
+
*
|
|
142
|
+
* Registration settles asynchronously: `handle.tools` lists the tools the
|
|
143
|
+
* runtime has accepted so far and `handle.ready` resolves when every
|
|
144
|
+
* registration has settled. The registration is torn down by
|
|
145
|
+
* `handle.detach()` or automatically when `instance.destroy()` runs.
|
|
146
|
+
*/
|
|
147
|
+
export function attachWebMCP(instance, options = {}) {
|
|
148
|
+
const detected = options.modelContext ?? detectModelContext();
|
|
149
|
+
if (!detected)
|
|
150
|
+
return null;
|
|
151
|
+
const runtime = detected;
|
|
152
|
+
const prefix = options.prefix ?? DEFAULT_PREFIX;
|
|
153
|
+
if (!/^[A-Za-z][A-Za-z0-9_-]*$/.test(prefix)) {
|
|
154
|
+
throw new Error(`[flowdrop] Invalid WebMCP prefix "${prefix}"`);
|
|
155
|
+
}
|
|
156
|
+
claimPrefix(runtime, prefix);
|
|
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
|
+
};
|
|
163
|
+
const editorName = () => instance.workflow.current?.name ?? instance.id;
|
|
164
|
+
const gate = createApprovalGate(options.approval ?? 'confirm', {
|
|
165
|
+
container: options.container,
|
|
166
|
+
editorName,
|
|
167
|
+
messages: options.messages,
|
|
168
|
+
rememberEdits: options.rememberEdits
|
|
169
|
+
});
|
|
170
|
+
const controller = new AbortController();
|
|
171
|
+
const descriptors = buildToolDescriptors({ view: Boolean(options.onUIAction) });
|
|
172
|
+
const names = [];
|
|
173
|
+
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
|
+
// ---- register -----------------------------------------------------------
|
|
405
|
+
const nameSuffix = ` Editor: "${editorName()}".`;
|
|
406
|
+
async function registerRaw(tool) {
|
|
407
|
+
try {
|
|
408
|
+
// The spec returns a promise that rejects when the runtime refuses the
|
|
409
|
+
// tool; pre-spec runtimes return nothing, which `await` takes as accepted.
|
|
410
|
+
await runtime.registerTool(tool, { signal: controller.signal });
|
|
411
|
+
}
|
|
412
|
+
catch (err) {
|
|
413
|
+
logger.warn(`WebMCP: the runtime refused tool "${tool.name}":`, err instanceof Error ? err.message : err);
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (attached)
|
|
417
|
+
names.push(tool.name);
|
|
418
|
+
}
|
|
419
|
+
function register(descriptor) {
|
|
420
|
+
return registerRaw({
|
|
421
|
+
name: `${prefix}_${descriptor.verb}`,
|
|
422
|
+
description: descriptor.description + nameSuffix,
|
|
423
|
+
inputSchema: descriptor.inputSchema,
|
|
424
|
+
annotations: { readOnlyHint: descriptor.readOnly },
|
|
425
|
+
execute: (input) => run(descriptor, input)
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
const toolRegistrations = descriptors.map(register);
|
|
429
|
+
const { onSave, onRun, onRunStatus } = options;
|
|
430
|
+
if (onSave) {
|
|
431
|
+
toolRegistrations.push(registerRaw({
|
|
432
|
+
name: `${prefix}_save`,
|
|
433
|
+
description: 'Save the workflow to the server. Nothing an agent changes is persisted until ' +
|
|
434
|
+
'this runs or the person clicks Save. Asks for approval; cannot be undone from ' +
|
|
435
|
+
'the editor. Fails with FORBIDDEN when the user may not save, CONFLICT when the ' +
|
|
436
|
+
'server copy changed since it was loaded (reload the page), INVALID when the ' +
|
|
437
|
+
'server rejected the workflow — the message says which node or port.' +
|
|
438
|
+
nameSuffix,
|
|
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
|
+
}
|
|
470
|
+
}
|
|
471
|
+
const ready = Promise.all(toolRegistrations).then(() => undefined);
|
|
472
|
+
// ---- detach -------------------------------------------------------------
|
|
473
|
+
function detach() {
|
|
474
|
+
if (!attached)
|
|
475
|
+
return;
|
|
476
|
+
attached = false;
|
|
477
|
+
unsubscribeDestroy();
|
|
478
|
+
gate.dispose();
|
|
479
|
+
controller.abort();
|
|
480
|
+
if (typeof runtime.unregisterTool === 'function') {
|
|
481
|
+
for (const name of names) {
|
|
482
|
+
try {
|
|
483
|
+
runtime.unregisterTool(name);
|
|
484
|
+
}
|
|
485
|
+
catch {
|
|
486
|
+
// Pre-spec runtime quirks are not ours to surface.
|
|
487
|
+
}
|
|
488
|
+
}
|
|
489
|
+
}
|
|
490
|
+
releasePrefix(runtime, prefix);
|
|
491
|
+
}
|
|
492
|
+
// Detach when the instance goes away.
|
|
493
|
+
const unsubscribeDestroy = instance.onDestroy(detach);
|
|
494
|
+
return {
|
|
495
|
+
get tools() {
|
|
496
|
+
return names;
|
|
497
|
+
},
|
|
498
|
+
ready,
|
|
499
|
+
get attached() {
|
|
500
|
+
return attached;
|
|
501
|
+
},
|
|
502
|
+
detach
|
|
503
|
+
};
|
|
504
|
+
}
|