@flowdrop/flowdrop 2.5.0 → 2.6.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 (52) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/dist/chat/commandClassifier.d.ts +17 -0
  3. package/dist/chat/commandClassifier.js +29 -0
  4. package/dist/chat/index.d.ts +1 -1
  5. package/dist/chat/index.js +1 -1
  6. package/dist/components/App.svelte +8 -0
  7. package/dist/components/BindablePortListbox.svelte +426 -0
  8. package/dist/components/BindablePortListbox.svelte.d.ts +23 -0
  9. package/dist/components/WorkflowInterfaceEditor.svelte +142 -36
  10. package/dist/components/WorkflowInterfaceEditor.svelte.d.ts +8 -0
  11. package/dist/components/WorkflowInterfaceEntryCard.svelte +537 -294
  12. package/dist/components/WorkflowInterfaceEntryCard.svelte.d.ts +6 -3
  13. package/dist/components/WorkflowInterfaceEntryComposer.svelte +331 -0
  14. package/dist/components/WorkflowInterfaceEntryComposer.svelte.d.ts +19 -0
  15. package/dist/messages/context.d.ts +6 -0
  16. package/dist/messages/context.js +8 -0
  17. package/dist/messages/defaults.d.ts +45 -2
  18. package/dist/messages/defaults.js +36 -3
  19. package/dist/messages/index.d.ts +1 -1
  20. package/dist/messages/index.js +1 -1
  21. package/dist/stores/instanceContainer.svelte.d.ts +26 -0
  22. package/dist/stores/instanceContainer.svelte.js +24 -0
  23. package/dist/stories/WebMCPFakeAgent.svelte +229 -0
  24. package/dist/stories/WebMCPFakeAgent.svelte.d.ts +10 -0
  25. package/dist/styles/base.css +4 -2
  26. package/dist/svelte-app.d.ts +20 -0
  27. package/dist/svelte-app.js +49 -1
  28. package/dist/utils/focus.d.ts +18 -0
  29. package/dist/utils/focus.js +24 -0
  30. package/dist/utils/whenWorkflowLoaded.svelte.d.ts +17 -0
  31. package/dist/utils/whenWorkflowLoaded.svelte.js +42 -0
  32. package/dist/utils/workflowInterface.d.ts +47 -3
  33. package/dist/utils/workflowInterface.js +84 -9
  34. package/dist/webmcp/WebMCP.stories.svelte +101 -0
  35. package/dist/webmcp/WebMCP.stories.svelte.d.ts +18 -0
  36. package/dist/webmcp/WebMCPConfirm.svelte +170 -0
  37. package/dist/webmcp/WebMCPConfirm.svelte.d.ts +11 -0
  38. package/dist/webmcp/descriptors.d.ts +59 -0
  39. package/dist/webmcp/descriptors.js +464 -0
  40. package/dist/webmcp/fake.d.ts +23 -0
  41. package/dist/webmcp/fake.js +42 -0
  42. package/dist/webmcp/gate.d.ts +40 -0
  43. package/dist/webmcp/gate.js +92 -0
  44. package/dist/webmcp/index.d.ts +34 -0
  45. package/dist/webmcp/index.js +31 -0
  46. package/dist/webmcp/register.d.ts +33 -0
  47. package/dist/webmcp/register.js +267 -0
  48. package/dist/webmcp/types.d.ts +166 -0
  49. package/dist/webmcp/types.js +23 -0
  50. package/dist/webmcp/validate.d.ts +32 -0
  51. package/dist/webmcp/validate.js +118 -0
  52. package/package.json +6 -1
@@ -0,0 +1,229 @@
1
+ <!--
2
+ WebMCPFakeAgent
3
+
4
+ Storybook harness for the WebMCP adapter. Mounts a full editor, attaches the
5
+ editor tools to a fake `modelContext`, and shows a side panel that plays the
6
+ browser agent: pick a tool, type its JSON arguments, invoke it, read the
7
+ result. The approval dialog appears exactly as it would for a real agent, so
8
+ the gate and the results are visible to a human without Chrome's origin trial.
9
+ -->
10
+
11
+ <script lang="ts">
12
+ import { onMount, untrack } from 'svelte';
13
+ import App from '../components/App.svelte';
14
+ import { createFlowDropInstance } from '../stores/instanceContainer.svelte.js';
15
+ import { attachWebMCP } from '../webmcp/register.js';
16
+ import { createFakeModelContext } from '../webmcp/fake.js';
17
+ import type { WebMCPApproval, WebMCPHandle } from '../webmcp/types.js';
18
+ import type { NodeMetadata, Workflow } from '../types/index.js';
19
+
20
+ interface Props {
21
+ nodes: NodeMetadata[];
22
+ workflow: Workflow;
23
+ approval?: WebMCPApproval;
24
+ }
25
+
26
+ let { nodes, workflow, approval = 'confirm' }: Props = $props();
27
+
28
+ const fd = createFlowDropInstance({ id: 'webmcp-story' });
29
+ // Seed once; later prop changes are the story's business, not the editor's.
30
+ fd.workflow.initialize(untrack(() => workflow));
31
+
32
+ const runtime = createFakeModelContext();
33
+ let handle = $state<WebMCPHandle | null>(null);
34
+ let toolNames = $state<string[]>([]);
35
+ let selected = $state('flowdrop_list_types');
36
+ let argsText = $state('{}');
37
+ let log = $state<Array<{ tool: string; args: string; result: string; error: boolean }>>([]);
38
+ let running = $state(false);
39
+
40
+ const SAMPLES: Record<string, string> = {
41
+ flowdrop_list_types: '{}',
42
+ flowdrop_list_nodes: '{}',
43
+ flowdrop_info: '{ "nodeId": "chat_model.1" }',
44
+ flowdrop_add_node: '{ "nodeTypeId": "chat_model" }',
45
+ flowdrop_set_config: '{ "nodeId": "chat_model.1", "key": "model", "value": "gpt-4o-mini" }',
46
+ flowdrop_connect:
47
+ '{ "sourceNodeId": "text_input.1", "sourcePort": "value", "targetNodeId": "chat_model.1", "targetPort": "message" }',
48
+ flowdrop_batch:
49
+ '{ "commands": [\n { "type": "add_node", "nodeTypeId": "chat_model" },\n { "type": "add_node", "nodeTypeId": "chat_output" }\n] }',
50
+ flowdrop_undo: '{}'
51
+ };
52
+
53
+ onMount(() => {
54
+ handle = attachWebMCP(fd, { nodeTypes: () => nodes, approval, modelContext: runtime });
55
+ const sync = () => (toolNames = [...runtime.tools.keys()]);
56
+ sync();
57
+ const off = runtime.onToolChange(sync);
58
+ return () => {
59
+ off();
60
+ handle?.detach();
61
+ };
62
+ });
63
+
64
+ function pick(name: string): void {
65
+ selected = name;
66
+ argsText = SAMPLES[name] ?? '{}';
67
+ }
68
+
69
+ async function invoke(): Promise<void> {
70
+ let input: unknown;
71
+ try {
72
+ input = JSON.parse(argsText || '{}');
73
+ } catch (err) {
74
+ log = [{ tool: selected, args: argsText, result: String(err), error: true }, ...log];
75
+ return;
76
+ }
77
+ running = true;
78
+ try {
79
+ const result = await runtime.executeTool(selected, input);
80
+ const pretty = JSON.stringify(JSON.parse(result.content[0].text), null, 2);
81
+ log = [{ tool: selected, args: argsText, result: pretty, error: !!result.isError }, ...log];
82
+ } finally {
83
+ running = false;
84
+ }
85
+ }
86
+ </script>
87
+
88
+ <div class="webmcp-story">
89
+ <div class="webmcp-story__editor">
90
+ <App instance={fd} {nodes} {workflow} height="100%" />
91
+ </div>
92
+
93
+ <aside class="webmcp-story__agent">
94
+ <h3 class="webmcp-story__title">Fake browser agent</h3>
95
+ <p class="webmcp-story__hint">
96
+ {toolNames.length} tools registered on <code>document.modelContext</code> (fake). Reads run at
97
+ once; changes ask first{approval === 'auto' ? ' — except here: approval is auto' : ''}.
98
+ </p>
99
+
100
+ <label class="webmcp-story__label">
101
+ Tool
102
+ <select
103
+ class="webmcp-story__select"
104
+ data-testid="webmcp-tool"
105
+ value={selected}
106
+ onchange={(e) => pick((e.currentTarget as HTMLSelectElement).value)}
107
+ >
108
+ {#each toolNames as name (name)}
109
+ <option value={name}>{name}</option>
110
+ {/each}
111
+ </select>
112
+ </label>
113
+
114
+ <label class="webmcp-story__label">
115
+ Arguments (JSON)
116
+ <textarea class="webmcp-story__args" data-testid="webmcp-args" rows="5" bind:value={argsText}
117
+ ></textarea>
118
+ </label>
119
+
120
+ <button
121
+ type="button"
122
+ class="webmcp-story__invoke"
123
+ data-testid="webmcp-invoke"
124
+ disabled={running || !handle}
125
+ onclick={invoke}
126
+ >
127
+ {running ? 'Waiting…' : 'Invoke'}
128
+ </button>
129
+
130
+ <ol class="webmcp-story__log" data-testid="webmcp-log">
131
+ {#each log as entry, i (log.length - i)}
132
+ <li class="webmcp-story__entry" class:webmcp-story__entry--error={entry.error}>
133
+ <div class="webmcp-story__call">{entry.tool} {entry.args}</div>
134
+ <pre class="webmcp-story__result">{entry.result}</pre>
135
+ </li>
136
+ {/each}
137
+ </ol>
138
+ </aside>
139
+ </div>
140
+
141
+ <style>
142
+ .webmcp-story {
143
+ display: grid;
144
+ grid-template-columns: minmax(0, 1fr) 22rem;
145
+ height: 100vh;
146
+ font-family: system-ui, sans-serif;
147
+ }
148
+ .webmcp-story__editor {
149
+ min-width: 0;
150
+ height: 100%;
151
+ }
152
+ .webmcp-story__agent {
153
+ display: flex;
154
+ flex-direction: column;
155
+ gap: 0.5rem;
156
+ padding: 0.75rem;
157
+ border-left: 1px solid #e4e4e7;
158
+ background: #fafafa;
159
+ overflow: auto;
160
+ font-size: 0.8125rem;
161
+ }
162
+ .webmcp-story__title {
163
+ margin: 0;
164
+ font-size: 0.9375rem;
165
+ }
166
+ .webmcp-story__hint {
167
+ margin: 0;
168
+ color: #71717a;
169
+ }
170
+ .webmcp-story__label {
171
+ display: flex;
172
+ flex-direction: column;
173
+ gap: 0.25rem;
174
+ font-weight: 600;
175
+ }
176
+ .webmcp-story__select,
177
+ .webmcp-story__args {
178
+ font: inherit;
179
+ font-family: ui-monospace, monospace;
180
+ font-weight: 400;
181
+ padding: 0.375rem;
182
+ border: 1px solid #d4d4d8;
183
+ border-radius: 0.375rem;
184
+ background: #fff;
185
+ }
186
+ .webmcp-story__invoke {
187
+ align-self: flex-start;
188
+ padding: 0.375rem 0.75rem;
189
+ border: 1px solid #2563eb;
190
+ border-radius: 0.375rem;
191
+ background: #2563eb;
192
+ color: #fff;
193
+ font: inherit;
194
+ cursor: pointer;
195
+ }
196
+ .webmcp-story__invoke:disabled {
197
+ opacity: 0.6;
198
+ cursor: default;
199
+ }
200
+ .webmcp-story__log {
201
+ margin: 0;
202
+ padding: 0;
203
+ list-style: none;
204
+ display: flex;
205
+ flex-direction: column;
206
+ gap: 0.5rem;
207
+ }
208
+ .webmcp-story__entry {
209
+ padding: 0.5rem;
210
+ border: 1px solid #e4e4e7;
211
+ border-radius: 0.375rem;
212
+ background: #fff;
213
+ }
214
+ .webmcp-story__entry--error {
215
+ border-color: #fca5a5;
216
+ }
217
+ .webmcp-story__call {
218
+ font-family: ui-monospace, monospace;
219
+ font-weight: 600;
220
+ margin-bottom: 0.25rem;
221
+ overflow-wrap: anywhere;
222
+ }
223
+ .webmcp-story__result {
224
+ margin: 0;
225
+ font-size: 0.75rem;
226
+ white-space: pre-wrap;
227
+ overflow-wrap: anywhere;
228
+ }
229
+ </style>
@@ -0,0 +1,10 @@
1
+ import type { WebMCPApproval } from '../webmcp/types.js';
2
+ import type { NodeMetadata, Workflow } from '../types/index.js';
3
+ interface Props {
4
+ nodes: NodeMetadata[];
5
+ workflow: Workflow;
6
+ approval?: WebMCPApproval;
7
+ }
8
+ declare const WebMCPFakeAgent: import("svelte").Component<Props, {}, "">;
9
+ type WebMCPFakeAgent = ReturnType<typeof WebMCPFakeAgent>;
10
+ export default WebMCPFakeAgent;
@@ -224,9 +224,11 @@ p {
224
224
  }
225
225
 
226
226
  .flowdrop-btn--sm {
227
- padding: var(--fd-space-2xs) var(--fd-space-md);
227
+ /* Same height as IconButton's sm (--fd-size-icon-btn), so the two sit on one
228
+ line without callers overriding either. */
229
+ padding: 0 var(--fd-space-md);
228
230
  font-size: var(--fd-text-xs);
229
- min-height: 2rem;
231
+ min-height: var(--fd-size-icon-btn);
230
232
  }
231
233
 
232
234
  .flowdrop-btn--lg {
@@ -16,7 +16,9 @@ import { type FlowDropInstance } from './stores/instanceContainer.svelte.js';
16
16
  import { type DraftStorageOption } from './services/draftStorage.js';
17
17
  import type { PartialSettings, SettingsCategory, SurfacePlacement } from './types/settings.js';
18
18
  import type { NavbarAction } from './types/navbar.js';
19
+ import type { WebMCPHandle, WebMCPMountOptions } from './webmcp/types.js';
19
20
  export type { NavbarAction };
21
+ export type { WebMCPHandle, WebMCPMountOptions };
20
22
  /**
21
23
  * Mount options for FlowDrop App
22
24
  */
@@ -129,6 +131,16 @@ export interface FlowDropMountOptions {
129
131
  * enabled, so keys stay stable across page loads.
130
132
  */
131
133
  instanceId?: string;
134
+ /**
135
+ * Expose the editor's commands as WebMCP **editor tools** for a
136
+ * browser-resident agent (Chrome 149+ / Edge 150+ origin trial, Brave Leo,
137
+ * ChatGPT Desktop). `true` uses the defaults — prefix `flowdrop`, mutations
138
+ * behind a confirm dialog; pass a {@link WebMCPMountOptions} to change them.
139
+ * The adapter is loaded on demand (`@flowdrop/flowdrop/webmcp`), so the
140
+ * core bundle is unchanged when this is off. No-op in browsers without the
141
+ * API. Default off.
142
+ */
143
+ webmcp?: boolean | WebMCPMountOptions;
132
144
  }
133
145
  /**
134
146
  * Return type for mounted FlowDrop app
@@ -178,6 +190,14 @@ export interface MountedFlowDropApp {
178
190
  * @returns The number of entries removed.
179
191
  */
180
192
  clearAllDrafts: () => number;
193
+ /**
194
+ * The WebMCP registration when the `webmcp` mount option was set and the
195
+ * browser has the API; `undefined` otherwise. The adapter attaches in the
196
+ * background once the workflow is loaded, so this is `undefined` for a
197
+ * moment after mount even when the API exists. Detached automatically on
198
+ * `destroy()`.
199
+ */
200
+ readonly webmcp?: WebMCPHandle;
181
201
  }
182
202
  /**
183
203
  * Mount the full FlowDrop App with navbar, sidebars, and workflow editor
@@ -18,6 +18,7 @@ import { mergeFeatures } from './types/events.js';
18
18
  import { initializeSettings, getBehaviorSettings, onSettingsChange } from './stores/settingsStore.svelte.js';
19
19
  import { logger } from './utils/logger.js';
20
20
  import { globalSaveWorkflow, globalExportWorkflow } from './services/globalSave.js';
21
+ import { whenWorkflowLoaded } from './utils/whenWorkflowLoaded.svelte.js';
21
22
  // ---------------------------------------------------------------------------
22
23
  // Instance acquisition
23
24
  // ---------------------------------------------------------------------------
@@ -107,6 +108,30 @@ async function configureInstance(fd, options) {
107
108
  }
108
109
  return config;
109
110
  }
111
+ /**
112
+ * Attach the WebMCP adapter for a `mountFlowDropApp` mount.
113
+ *
114
+ * Adds no request and no mount latency: node types are read lazily from the
115
+ * instance, which `App` fills from the same fetch it already makes (or from
116
+ * the mount's `nodes` option, seeded below), and attachment waits for the
117
+ * workflow to be known so every tool description names it. Resolves
118
+ * `undefined` when the browser has no WebMCP runtime or the mount was
119
+ * destroyed first.
120
+ */
121
+ function attachWebMCPToMount(fd, options, isDestroyed) {
122
+ return new Promise((resolve) => {
123
+ // Dynamic imports keep the adapter and the rune helper out of the core
124
+ // entry's static graph (see scripts/check-bundle.mjs).
125
+ whenWorkflowLoaded(fd, async () => {
126
+ if (isDestroyed())
127
+ return resolve(undefined);
128
+ const { attachWebMCP } = await import('./webmcp/index.js');
129
+ if (isDestroyed())
130
+ return resolve(undefined);
131
+ resolve(attachWebMCP(fd, options) ?? undefined);
132
+ });
133
+ });
134
+ }
110
135
  /**
111
136
  * Mount the full FlowDrop App with navbar, sidebars, and workflow editor
112
137
  *
@@ -132,7 +157,7 @@ async function configureInstance(fd, options) {
132
157
  * ```
133
158
  */
134
159
  export async function mountFlowDropApp(container, options = {}) {
135
- const { workflow, nodes, endpointConfig, portConfig, categories, height = '100vh', width = '100%', showNavbar = false, disableSidebar, configPlacement, consolePlacement, mode, pipelineId, navbarTitle, navbarActions, showSettings, showStatus, authProvider, eventHandlers, features: userFeatures, settings: initialSettings, draftStorageKey: customDraftKey, draftStorage, formatAdapters, workflowFormats, theme, settingsCategories, showSettingsSyncButton, showSettingsResetButton, instanceId } = options;
160
+ const { workflow, nodes, endpointConfig, portConfig, categories, height = '100vh', width = '100%', showNavbar = false, disableSidebar, configPlacement, consolePlacement, mode, pipelineId, navbarTitle, navbarActions, showSettings, showStatus, authProvider, eventHandlers, features: userFeatures, settings: initialSettings, draftStorageKey: customDraftKey, draftStorage, formatAdapters, workflowFormats, theme, settingsCategories, showSettingsSyncButton, showSettingsResetButton, instanceId, webmcp } = options;
136
161
  // Per-instance state container — this is what allows multiple FlowDrop
137
162
  // editors to coexist on one page without sharing workflow/history state.
138
163
  const { fd, isDefault } = acquireInstance(instanceId);
@@ -170,6 +195,11 @@ export async function mountFlowDropApp(container, options = {}) {
170
195
  if (eventHandlers?.onWorkflowChange) {
171
196
  fd.workflow.setOnWorkflowChange(eventHandlers.onWorkflowChange);
172
197
  }
198
+ // The mount's `nodes` seed the instance's node-type list; App replaces it
199
+ // with the merged (props + format nodes) list as soon as it has one.
200
+ if (nodes && nodes.length > 0) {
201
+ fd.nodeTypes.set(nodes);
202
+ }
173
203
  // Create the Svelte App component with configuration
174
204
  const svelteApp = mount(App, {
175
205
  target: container,
@@ -251,10 +281,28 @@ export async function mountFlowDropApp(container, options = {}) {
251
281
  eventHandlers: eventHandlers ?? null,
252
282
  unsubscribeDraftSettings
253
283
  };
284
+ // WebMCP editor tools, opt-in. Attaches in the background — mounting does
285
+ // not wait for it — and detaches with the mount.
286
+ let webmcpHandle;
287
+ let destroyed = false;
288
+ if (webmcp) {
289
+ void attachWebMCPToMount(fd, webmcp === true ? {} : webmcp, () => destroyed).then((handle) => {
290
+ if (destroyed)
291
+ handle?.detach();
292
+ else
293
+ webmcpHandle = handle;
294
+ });
295
+ }
254
296
  // Create the mounted app interface
255
297
  const mountedApp = {
256
298
  instance: fd,
299
+ get webmcp() {
300
+ return webmcpHandle;
301
+ },
257
302
  destroy: () => {
303
+ // Remove the agent-facing tools before anything else goes away.
304
+ destroyed = true;
305
+ webmcpHandle?.detach();
258
306
  // Call onBeforeUnmount if provided
259
307
  if (state.eventHandlers?.onBeforeUnmount) {
260
308
  const currentWorkflow = fd.workflow.current;
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Focus attachments.
3
+ *
4
+ * `{@attach focusOnMount()}` moves keyboard focus to an element as it enters
5
+ * the DOM — a dialog's primary button, the first choice of a form that just
6
+ * opened, a listbox the author stepped into. An attachment rather than an
7
+ * `$effect` over a `bind:this` because focusing is a fact about the element's
8
+ * arrival, not about state: it runs once when the node mounts and never again.
9
+ *
10
+ * @module utils/focus
11
+ */
12
+ import type { Attachment } from 'svelte/attachments';
13
+ /**
14
+ * Focus the element when it mounts. Pass `false` to switch it off at a call
15
+ * site that only sometimes wants focus (a listbox that is autofocused in one
16
+ * host and not in another).
17
+ */
18
+ export declare function focusOnMount(enabled?: boolean): Attachment<HTMLElement>;
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Focus attachments.
3
+ *
4
+ * `{@attach focusOnMount()}` moves keyboard focus to an element as it enters
5
+ * the DOM — a dialog's primary button, the first choice of a form that just
6
+ * opened, a listbox the author stepped into. An attachment rather than an
7
+ * `$effect` over a `bind:this` because focusing is a fact about the element's
8
+ * arrival, not about state: it runs once when the node mounts and never again.
9
+ *
10
+ * @module utils/focus
11
+ */
12
+ const noop = () => { };
13
+ /**
14
+ * Focus the element when it mounts. Pass `false` to switch it off at a call
15
+ * site that only sometimes wants focus (a listbox that is autofocused in one
16
+ * host and not in another).
17
+ */
18
+ export function focusOnMount(enabled = true) {
19
+ if (!enabled)
20
+ return noop;
21
+ return (element) => {
22
+ element.focus();
23
+ };
24
+ }
@@ -0,0 +1,17 @@
1
+ /**
2
+ * Run a callback once an instance has a workflow.
3
+ *
4
+ * `fd.workflow.current` is `null` between `createFlowDropInstance()` and the
5
+ * editor's `initialize()`, which the `App` component runs on mount. Anything
6
+ * that wants the workflow's identity at set-up time — the WebMCP adapter puts
7
+ * the workflow's name in every tool description — waits here for it.
8
+ *
9
+ * Fires at once when the workflow is already known. Returns a cancel function
10
+ * for the case where the caller goes away first; after the callback has run
11
+ * the watcher has already disposed itself and cancel is a no-op.
12
+ *
13
+ * @module utils/whenWorkflowLoaded
14
+ */
15
+ import type { FlowDropInstance } from '../stores/instanceContainer.svelte.js';
16
+ import type { Workflow } from '../types/index.js';
17
+ export declare function whenWorkflowLoaded(instance: FlowDropInstance, callback: (workflow: Workflow) => void): () => void;
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Run a callback once an instance has a workflow.
3
+ *
4
+ * `fd.workflow.current` is `null` between `createFlowDropInstance()` and the
5
+ * editor's `initialize()`, which the `App` component runs on mount. Anything
6
+ * that wants the workflow's identity at set-up time — the WebMCP adapter puts
7
+ * the workflow's name in every tool description — waits here for it.
8
+ *
9
+ * Fires at once when the workflow is already known. Returns a cancel function
10
+ * for the case where the caller goes away first; after the callback has run
11
+ * the watcher has already disposed itself and cancel is a no-op.
12
+ *
13
+ * @module utils/whenWorkflowLoaded
14
+ */
15
+ export function whenWorkflowLoaded(instance, callback) {
16
+ const now = instance.workflow.current;
17
+ if (now) {
18
+ callback(now);
19
+ return () => { };
20
+ }
21
+ let done = false;
22
+ const dispose = $effect.root(() => {
23
+ $effect(() => {
24
+ const workflow = instance.workflow.current;
25
+ if (!workflow || done)
26
+ return;
27
+ done = true;
28
+ // Leave the effect before running user code, and dispose the root after
29
+ // it — disposing from inside the effect that is running is undefined.
30
+ queueMicrotask(() => {
31
+ dispose();
32
+ callback(workflow);
33
+ });
34
+ });
35
+ });
36
+ return () => {
37
+ if (done)
38
+ return;
39
+ done = true;
40
+ dispose();
41
+ };
42
+ }
@@ -200,9 +200,53 @@ export interface BindablePort {
200
200
  * Mirrors `FormPorts.svelte`'s port list: a node's static metadata ports plus
201
201
  * its user-defined dynamic ports, filtered by `isPortExposed`.
202
202
  *
203
- * Control-flow ports are excluded: the reserved `trigger`/`tool` dataTypes and
204
- * the `loop_back` port are intra-graph control flow, not an external surface
205
- * (DN1's grounded fact). The model and validation stay permissive — this only
203
+ * Control-flow ports are excluded: the reserved `trigger` dataType, the
204
+ * `loop_back` port and `tool` outputs are intra-graph control flow, not an
205
+ * external surface (DN1's grounded fact). `tool` inputs are offered — see
206
+ * `isControlFlowPort`. The model and validation stay permissive — this only
206
207
  * constrains what the authoring picker offers.
207
208
  */
208
209
  export declare function listBindablePorts(workflow: Workflow, direction: 'input' | 'output'): BindablePort[];
210
+ /** A bindable port plus what the canvas already does with it. */
211
+ export interface RankedBindablePort extends BindablePort {
212
+ /** An edge already feeds this input, or already drains this output. */
213
+ connected: boolean;
214
+ /** The id of the same-direction interface entry that already binds this port, if any. */
215
+ publishedAs?: string;
216
+ }
217
+ /**
218
+ * A stable key for a bindable port — `nodeId::portId` — the value a picker
219
+ * highlights by and an entry's single binding is compared against.
220
+ */
221
+ export declare function bindablePortKey(candidate: BindablePort | {
222
+ nodeId: string;
223
+ portId: string;
224
+ }): string;
225
+ /** A port nothing is using yet — the natural first pick for a new entry. */
226
+ export declare function isFreeBindablePort(candidate: RankedBindablePort): boolean;
227
+ /**
228
+ * `listBindablePorts`, annotated and ordered for a "pick a port to publish"
229
+ * picker: every port nothing is using yet comes first, then the ports that
230
+ * already have an edge or are already published by another entry. Within
231
+ * each group the canvas order is kept, so the list stays stable as the
232
+ * author edits.
233
+ *
234
+ * "Connected" mirrors `validateWorkflowInterface`'s already-connected rule
235
+ * for inputs (an incoming edge on the bound handle) and its natural inverse
236
+ * for outputs (an outgoing edge). Neither is forbidden — an output can be
237
+ * both wired and published — the ranking only says which ports need no
238
+ * second thought.
239
+ */
240
+ export declare function rankBindablePorts(workflow: Workflow, direction: 'input' | 'output'): RankedBindablePort[];
241
+ /**
242
+ * A complete new entry for a port the author just picked: bound to it, with
243
+ * every field `pullEntryFieldsFromPort` can derive, and an `id` seeded from
244
+ * the port's own id — made unique against `existingIds` with a numeric
245
+ * suffix (`text`, `text_2`, `text_3`, …).
246
+ *
247
+ * Seeding the id from the port is a convenience at creation time only: the
248
+ * author edits it like any other field afterwards, and nothing later
249
+ * re-derives it. DN1's concern — a contract silently keyed on internal port
250
+ * names — is about that ongoing coupling, which this does not introduce.
251
+ */
252
+ export declare function entryFromBindablePort(candidate: BindablePort, existingIds: Iterable<string>): WorkflowInterfaceEntry;
@@ -347,12 +347,22 @@ export function pullEntryFieldsFromPort(port) {
347
347
  return patch;
348
348
  }
349
349
  /**
350
- * Whether a port is intra-graph control flow — the reserved `trigger`/`tool`
351
- * dataTypes or the loopback input — and therefore never publishable in a
352
- * workflow's interface.
350
+ * Whether a port is intra-graph control flow — the reserved `trigger`
351
+ * dataType, the loopback input, or a `tool` *output* — and therefore never
352
+ * publishable in a workflow's interface.
353
+ *
354
+ * A `tool` **input** is deliberately not control flow here. Tools are a typed
355
+ * argument of a workflow's execution (fddo DF9): exposing a consumer's `tool`
356
+ * input (a ToolBox's `tools`, an LLM node's `tools`) in the interface is how a
357
+ * parent hands its tools to a sub-workflow, so the picker must offer it. A
358
+ * `tool` output is the inverse — a workflow *producing* a tool — which is not
359
+ * a composition the runtime supports through the interface (a workflow is
360
+ * made a tool by a different mechanism), so it stays excluded.
353
361
  */
354
- function isControlFlowPort(port) {
355
- return port.dataType === 'trigger' || port.dataType === 'tool' || port.id === LOOPBACK_PORT_NAME;
362
+ function isControlFlowPort(port, direction) {
363
+ if (port.dataType === 'trigger' || port.id === LOOPBACK_PORT_NAME)
364
+ return true;
365
+ return port.dataType === 'tool' && direction === 'output';
356
366
  }
357
367
  /**
358
368
  * Every canvas-exposed port of a workflow, for one direction — the candidate
@@ -362,9 +372,10 @@ function isControlFlowPort(port) {
362
372
  * Mirrors `FormPorts.svelte`'s port list: a node's static metadata ports plus
363
373
  * its user-defined dynamic ports, filtered by `isPortExposed`.
364
374
  *
365
- * Control-flow ports are excluded: the reserved `trigger`/`tool` dataTypes and
366
- * the `loop_back` port are intra-graph control flow, not an external surface
367
- * (DN1's grounded fact). The model and validation stay permissive — this only
375
+ * Control-flow ports are excluded: the reserved `trigger` dataType, the
376
+ * `loop_back` port and `tool` outputs are intra-graph control flow, not an
377
+ * external surface (DN1's grounded fact). `tool` inputs are offered — see
378
+ * `isControlFlowPort`. The model and validation stay permissive — this only
368
379
  * constrains what the authoring picker offers.
369
380
  */
370
381
  export function listBindablePorts(workflow, direction) {
@@ -380,7 +391,7 @@ export function listBindablePorts(workflow, direction) {
380
391
  const portsConfig = node.data?.config?.[PORTS_CONFIG_KEY];
381
392
  const entries = portsConfig?.[portsConfigDirection];
382
393
  for (const port of [...staticPorts, ...dynamicPorts]) {
383
- if (isControlFlowPort(port))
394
+ if (isControlFlowPort(port, direction))
384
395
  continue;
385
396
  if (isPortExposed(port, entries)) {
386
397
  result.push({ nodeId: node.id, nodeLabel: node.data?.label ?? node.id, port });
@@ -389,3 +400,67 @@ export function listBindablePorts(workflow, direction) {
389
400
  }
390
401
  return result;
391
402
  }
403
+ /**
404
+ * A stable key for a bindable port — `nodeId::portId` — the value a picker
405
+ * highlights by and an entry's single binding is compared against.
406
+ */
407
+ export function bindablePortKey(candidate) {
408
+ const portId = 'port' in candidate ? candidate.port.id : candidate.portId;
409
+ return `${candidate.nodeId}::${portId}`;
410
+ }
411
+ /** A port nothing is using yet — the natural first pick for a new entry. */
412
+ export function isFreeBindablePort(candidate) {
413
+ return !candidate.connected && candidate.publishedAs === undefined;
414
+ }
415
+ /**
416
+ * `listBindablePorts`, annotated and ordered for a "pick a port to publish"
417
+ * picker: every port nothing is using yet comes first, then the ports that
418
+ * already have an edge or are already published by another entry. Within
419
+ * each group the canvas order is kept, so the list stays stable as the
420
+ * author edits.
421
+ *
422
+ * "Connected" mirrors `validateWorkflowInterface`'s already-connected rule
423
+ * for inputs (an incoming edge on the bound handle) and its natural inverse
424
+ * for outputs (an outgoing edge). Neither is forbidden — an output can be
425
+ * both wired and published — the ranking only says which ports need no
426
+ * second thought.
427
+ */
428
+ export function rankBindablePorts(workflow, direction) {
429
+ const entries = (direction === 'input' ? workflow.interface?.inputs : workflow.interface?.outputs) ?? [];
430
+ const ranked = listBindablePorts(workflow, direction).map((candidate) => {
431
+ const handleId = buildHandleId(candidate.nodeId, direction, candidate.port.id);
432
+ const connected = workflow.edges.some((edge) => direction === 'input' ? edge.targetHandle === handleId : edge.sourceHandle === handleId);
433
+ const publishedAs = entries.find((entry) => entry.bindings.some((binding) => binding.nodeId === candidate.nodeId && binding.portId === candidate.port.id))?.id;
434
+ return publishedAs === undefined
435
+ ? { ...candidate, connected }
436
+ : { ...candidate, connected, publishedAs };
437
+ });
438
+ return [
439
+ ...ranked.filter(isFreeBindablePort),
440
+ ...ranked.filter((candidate) => !isFreeBindablePort(candidate))
441
+ ];
442
+ }
443
+ /**
444
+ * A complete new entry for a port the author just picked: bound to it, with
445
+ * every field `pullEntryFieldsFromPort` can derive, and an `id` seeded from
446
+ * the port's own id — made unique against `existingIds` with a numeric
447
+ * suffix (`text`, `text_2`, `text_3`, …).
448
+ *
449
+ * Seeding the id from the port is a convenience at creation time only: the
450
+ * author edits it like any other field afterwards, and nothing later
451
+ * re-derives it. DN1's concern — a contract silently keyed on internal port
452
+ * names — is about that ongoing coupling, which this does not introduce.
453
+ */
454
+ export function entryFromBindablePort(candidate, existingIds) {
455
+ const taken = new Set(existingIds);
456
+ let id = candidate.port.id;
457
+ for (let n = 2; taken.has(id); n += 1) {
458
+ id = `${candidate.port.id}_${n}`;
459
+ }
460
+ return {
461
+ id,
462
+ dataType: candidate.port.dataType,
463
+ bindings: [{ nodeId: candidate.nodeId, portId: candidate.port.id }],
464
+ ...pullEntryFieldsFromPort(candidate.port)
465
+ };
466
+ }