@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
@@ -0,0 +1,53 @@
1
+ <script lang="ts">
2
+ /**
3
+ * Toast body with a close button.
4
+ *
5
+ * svelte-5-french-toast renders a component message as
6
+ * `<toast.message {toast} {...toast.props} />`, so this receives the live
7
+ * toast (for its id) plus the props the service passes. Used for errors and
8
+ * warnings, which stay on screen until the user dismisses them: a refusal
9
+ * the user has to act on must not vanish mid-read.
10
+ *
11
+ * `details` are the server's reasons behind the headline (ApiError.details);
12
+ * they render as a list rather than being joined into the headline.
13
+ * The list is keyed by index on purpose: two reasons may share their
14
+ * wording, and keying on the text throws `each_key_duplicate` — in
15
+ * production too. The list never changes for the life of a toast.
16
+ */
17
+ import { toast as toastApi, type Toast } from 'svelte-5-french-toast';
18
+
19
+ interface Props {
20
+ toast: Toast;
21
+ text: string;
22
+ details?: readonly string[];
23
+ }
24
+
25
+ let { toast, text, details = [] }: Props = $props();
26
+ </script>
27
+
28
+ <div class="flowdrop-toast-text">
29
+ <p class="flowdrop-toast-headline">{text}</p>
30
+ {#if details.length}
31
+ <ul class="flowdrop-toast-details">
32
+ {#each details as detail, i (i)}
33
+ <li>{detail}</li>
34
+ {/each}
35
+ </ul>
36
+ {/if}
37
+ </div>
38
+ <button
39
+ type="button"
40
+ class="flowdrop-toast-close"
41
+ aria-label="Dismiss"
42
+ onclick={() => toastApi.dismiss(toast.id)}
43
+ >
44
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true" focusable="false">
45
+ <path
46
+ d="M4 4l8 8M12 4l-8 8"
47
+ stroke="currentColor"
48
+ stroke-width="1.75"
49
+ stroke-linecap="round"
50
+ fill="none"
51
+ />
52
+ </svg>
53
+ </button>
@@ -0,0 +1,24 @@
1
+ /**
2
+ * Toast body with a close button.
3
+ *
4
+ * svelte-5-french-toast renders a component message as
5
+ * `<toast.message {toast} {...toast.props} />`, so this receives the live
6
+ * toast (for its id) plus the props the service passes. Used for errors and
7
+ * warnings, which stay on screen until the user dismisses them: a refusal
8
+ * the user has to act on must not vanish mid-read.
9
+ *
10
+ * `details` are the server's reasons behind the headline (ApiError.details);
11
+ * they render as a list rather than being joined into the headline.
12
+ * The list is keyed by index on purpose: two reasons may share their
13
+ * wording, and keying on the text throws `each_key_duplicate` — in
14
+ * production too. The list never changes for the life of a toast.
15
+ */
16
+ import { type Toast } from 'svelte-5-french-toast';
17
+ interface Props {
18
+ toast: Toast;
19
+ text: string;
20
+ details?: readonly string[];
21
+ }
22
+ declare const DismissibleToast: import("svelte").Component<Props, {}, "">;
23
+ type DismissibleToast = ReturnType<typeof DismissibleToast>;
24
+ export default DismissibleToast;
@@ -0,0 +1,28 @@
1
+ <!--
2
+ Warning glyph for toasts. The library only ships success/error/loading
3
+ icons, so a warning would otherwise wear the error icon and be
4
+ indistinguishable from one.
5
+ -->
6
+ <svg
7
+ class="flowdrop-toast-warning-icon"
8
+ viewBox="0 0 20 20"
9
+ width="20"
10
+ height="20"
11
+ aria-hidden="true"
12
+ focusable="false"
13
+ >
14
+ <path
15
+ d="M10 2.5 18.5 17H1.5L10 2.5Z"
16
+ fill="var(--fd-warning, #f59e0b)"
17
+ stroke="var(--fd-warning, #f59e0b)"
18
+ stroke-width="1.5"
19
+ stroke-linejoin="round"
20
+ />
21
+ <path
22
+ d="M10 8v4.5"
23
+ stroke="var(--fd-warning-foreground, #fff)"
24
+ stroke-width="1.75"
25
+ stroke-linecap="round"
26
+ />
27
+ <circle cx="10" cy="14.75" r="1" fill="var(--fd-warning-foreground, #fff)" />
28
+ </svg>
@@ -0,0 +1,26 @@
1
+ export default WarningIcon;
2
+ type WarningIcon = SvelteComponent<{
3
+ [x: string]: never;
4
+ }, {
5
+ [evt: string]: CustomEvent<any>;
6
+ }, {}> & {
7
+ $$bindings?: string | undefined;
8
+ };
9
+ declare const WarningIcon: $$__sveltets_2_IsomorphicComponent<{
10
+ [x: string]: never;
11
+ }, {
12
+ [evt: string]: CustomEvent<any>;
13
+ }, {}, {}, string>;
14
+ interface $$__sveltets_2_IsomorphicComponent<Props extends Record<string, any> = any, Events extends Record<string, any> = any, Slots extends Record<string, any> = any, Exports = {}, Bindings = string> {
15
+ new (options: import("svelte").ComponentConstructorOptions<Props>): import("svelte").SvelteComponent<Props, Events, Slots> & {
16
+ $$bindings?: Bindings;
17
+ } & Exports;
18
+ (internal: unknown, props: {
19
+ $$events?: Events;
20
+ $$slots?: Slots;
21
+ }): Exports & {
22
+ $set?: any;
23
+ $on?: any;
24
+ };
25
+ z_$$bindings?: Bindings;
26
+ }
@@ -41,11 +41,15 @@ export declare const EDGE_MARKER_SIZES: {
41
41
  readonly height: 16;
42
42
  };
43
43
  };
44
- /** Toast notification durations in milliseconds */
44
+ /**
45
+ * How long each kind of toast stays, in milliseconds. `Infinity` means it
46
+ * stays until the user closes it: errors and warnings name something to act
47
+ * on, and a message that vanishes mid-read was never delivered.
48
+ */
45
49
  export declare const TOAST_DURATION: {
46
50
  readonly SUCCESS: 4000;
47
- readonly ERROR: 6000;
48
- readonly WARNING: 5000;
51
+ readonly ERROR: number;
52
+ readonly WARNING: number;
49
53
  readonly INFO: 4000;
50
54
  readonly CONFIRMATION: 5000;
51
55
  };
@@ -29,11 +29,15 @@ export const EDGE_MARKER_SIZES = {
29
29
  tool: { width: 16, height: 16 },
30
30
  data: { width: 16, height: 16 }
31
31
  };
32
- /** Toast notification durations in milliseconds */
32
+ /**
33
+ * How long each kind of toast stays, in milliseconds. `Infinity` means it
34
+ * stays until the user closes it: errors and warnings name something to act
35
+ * on, and a message that vanishes mid-read was never delivered.
36
+ */
33
37
  export const TOAST_DURATION = {
34
38
  SUCCESS: 4_000,
35
- ERROR: 6_000,
36
- WARNING: 5_000,
39
+ ERROR: Infinity,
40
+ WARNING: Infinity,
37
41
  INFO: 4_000,
38
42
  CONFIRMATION: 5_000
39
43
  };
@@ -127,6 +127,13 @@ export interface EndpointConfig {
127
127
  getHistory: string;
128
128
  /** Clear conversation history */
129
129
  clearHistory: string;
130
+ /**
131
+ * Continue a tool-calling turn with the results of the tool calls the
132
+ * assistant made (`POST`, `{turnId}` in the path). Optional: a backend
133
+ * without it gets the legacy text mode — the panel sends one message,
134
+ * parses the ```flowdrop block in the reply, and asks before applying.
135
+ */
136
+ toolResults?: string;
130
137
  };
131
138
  templates: {
132
139
  list: string;
@@ -73,7 +73,8 @@ export const defaultEndpointConfig = {
73
73
  chat: {
74
74
  sendMessage: '/workflows/{id}/chat/messages',
75
75
  getHistory: '/workflows/{id}/chat/messages',
76
- clearHistory: '/workflows/{id}/chat/messages'
76
+ clearHistory: '/workflows/{id}/chat/messages',
77
+ toolResults: '/workflows/{id}/chat/turns/{turnId}/tool-results'
77
78
  },
78
79
  templates: {
79
80
  list: '/templates',
@@ -50,7 +50,7 @@ export { resolveScopeToKey, keyToScope, generateDefaultUISchema, collectReferenc
50
50
  export { DEFAULT_PORT_CONFIG } from '../config/defaultPortConfig.js';
51
51
  export { defaultEndpointConfig, createEndpointConfig } from '../config/endpoints.js';
52
52
  export { generateNodeId, extractConfigDefaults } from '../utils/nodeIds.js';
53
- export type { AddNodeCommand, DeleteNodeCommand, RenameNodeCommand, SetConfigCommand, GetConfigCommand, ConnectCommand, DisconnectPortsCommand, DisconnectNodeCommand, ListNodesCommand, ListEdgesCommand, ListTypesCommand, InfoCommand, UndoCommand, RedoCommand, ConfigOpenCommand, SelectNodeCommand, HelpCommand, ClearCommand, SwapNodeCommand, MoveNodeCommand, AutoLayoutCommand, Command, ParseResult, CommandErrorCode, AddNodeResultData, ListNodesResultData, ListEdgesResultData, ListTypesResultData, InfoResultData, GetConfigResultData, SetConfigResultData, HelpResultData, CommandResultData, CommandResultOk, CommandResultError, CommandResult, BatchResult, UIAction, CommandDispatch, CommandContext } from '../commands/index.js';
53
+ export type { AddNodeCommand, DeleteNodeCommand, RenameNodeCommand, SetConfigCommand, GetConfigCommand, ConnectCommand, DisconnectPortsCommand, DisconnectNodeCommand, ListNodesCommand, ListEdgesCommand, ListTypesCommand, DescribeTypeCommand, SearchTypesCommand, InfoCommand, UndoCommand, RedoCommand, ConfigOpenCommand, SelectNodeCommand, HelpCommand, ClearCommand, SwapNodeCommand, MoveNodeCommand, AutoLayoutCommand, Command, ParseResult, CommandErrorCode, AddNodeResultData, ListNodesResultData, ListEdgesResultData, ListTypesResultData, SearchTypesResultData, DescribeTypeResultData, TypeSummary, ConfigKeyDescription, PortDescription, InfoResultData, GetConfigResultData, GetConfigKeyResultData, GetConfigAllResultData, SetConfigResultData, HelpResultData, CommandResultData, CommandResultOk, CommandResultError, CommandResult, BatchResult, UIAction, CommandDispatch, CommandContext } from '../commands/index.js';
54
54
  export { buildTypeMap, parseCommand, executeCommand, toShortId, toShortTypeId, resolveNode, executeBatch, computeAutoPosition } from '../commands/index.js';
55
55
  export { WorkflowAdapter } from '../adapters/WorkflowAdapter.js';
56
56
  export type { StandardNode, StandardEdge, StandardWorkflow, WorkflowExecutionResult, WorkflowValidationResult } from '../adapters/WorkflowAdapter.js';
@@ -82,7 +82,7 @@ export { fetchCategories, validateCategories } from '../services/categoriesApi.j
82
82
  export { fetchDynamicSchema, resolveExternalEditUrl, getEffectiveConfigEditOptions, clearSchemaCache, invalidateSchemaCache, hasConfigEditOptions, shouldShowExternalEdit, shouldUseDynamicSchema } from '../services/dynamicSchemaService.js';
83
83
  export { getDraftStorageKey, saveDraft, loadDraft, deleteDraft, hasDraft, getDraftMetadata, clearAllDrafts, setDraftStorage, getDraftStorage, resolveDraftStorage, DraftAutoSaveManager } from '../services/draftStorage.js';
84
84
  export type { DraftStorageAdapter, DraftStorageType, DraftStorageOption } from '../services/draftStorage.js';
85
- export { EnhancedFlowDropApiClient, ApiError } from '../api/enhanced-client.js';
85
+ export { EnhancedFlowDropApiClient, ApiError, parseApiErrorBody, errorDetails } from '../api/enhanced-client.js';
86
86
  export { isLoopbackEdge, isValidLoopbackCycle, PortCompatibilityChecker, getPossibleConnections, validateConnection, getConnectionSuggestions, hasCycles, hasInvalidCycles, getExecutionOrder } from '../utils/connections.js';
87
87
  export { SHAPE_GLYPH, portShape, portGlyph } from '../utils/portShape.js';
88
88
  export type { PortShape } from '../utils/portShape.js';
@@ -119,7 +119,7 @@ export { getDraftStorageKey, saveDraft, loadDraft, deleteDraft, hasDraft, getDra
119
119
  // ============================================================================
120
120
  // API Clients
121
121
  // ============================================================================
122
- export { EnhancedFlowDropApiClient, ApiError } from '../api/enhanced-client.js';
122
+ export { EnhancedFlowDropApiClient, ApiError, parseApiErrorBody, errorDetails } from '../api/enhanced-client.js';
123
123
  // ============================================================================
124
124
  // Connection Utilities
125
125
  // ============================================================================
@@ -265,6 +265,47 @@ export declare const defaultMessages: {
265
265
  attempt: number;
266
266
  max: number;
267
267
  }) => string;
268
+ readonly tools: {
269
+ /** Status line while a read tool runs: `Reading: describe_type http_request`. */
270
+ readonly reading: ({ tool, detail }: {
271
+ tool: string;
272
+ detail: string;
273
+ }) => string;
274
+ readonly awaitingApproval: ({ tool }: {
275
+ tool: string;
276
+ }) => string;
277
+ /** Title of the approval dialog when the assistant, not a browser agent, asks. */
278
+ readonly confirmTitle: ({ name }: {
279
+ name: string;
280
+ }) => string;
281
+ /** A read that completed: `Read: describe_type http_request`. */
282
+ readonly read: ({ tool, detail }: {
283
+ tool: string;
284
+ detail: string;
285
+ }) => string;
286
+ readonly applied: ({ tool, detail }: {
287
+ tool: string;
288
+ detail: string;
289
+ }) => string;
290
+ readonly rejected: ({ tool }: {
291
+ tool: string;
292
+ }) => string;
293
+ readonly failed: ({ tool, error }: {
294
+ tool: string;
295
+ error: string;
296
+ }) => string;
297
+ readonly rounds: ({ count }: {
298
+ count: number;
299
+ }) => string;
300
+ readonly legacyFallback: "This backend does not support tool-calling turns; using the text mode for this session.";
301
+ readonly aborted: ({ reason }: {
302
+ reason: string;
303
+ }) => string;
304
+ /** Deterministic warning under the reply when one or more tool calls failed this turn. */
305
+ readonly failedSummary: ({ count }: {
306
+ count: number;
307
+ }) => string;
308
+ };
268
309
  readonly commandPreview: {
269
310
  readonly ariaLabel: "Command preview";
270
311
  readonly applying: "Applying…";
@@ -601,5 +642,38 @@ export declare const defaultMessages: {
601
642
  }) => string;
602
643
  readonly reject: "Reject";
603
644
  readonly apply: "Apply";
645
+ readonly saveLine: ({ name }: {
646
+ name: string;
647
+ }) => string;
648
+ readonly saveHint: "Writes the workflow to the server. This cannot be undone from the editor.";
649
+ readonly runLine: ({ name }: {
650
+ name: string;
651
+ }) => string;
652
+ readonly runHint: "Starts a run of the saved workflow. Unsaved changes are not part of it.";
653
+ /** One clause per kind of change; joined into the batch summary. */
654
+ readonly summaryAdds: ({ count }: {
655
+ count: number;
656
+ }) => string;
657
+ readonly summaryDeletes: ({ count }: {
658
+ count: number;
659
+ }) => string;
660
+ readonly summaryConnects: ({ count }: {
661
+ count: number;
662
+ }) => string;
663
+ readonly summaryDisconnects: ({ count }: {
664
+ count: number;
665
+ }) => string;
666
+ readonly summaryConfigs: ({ count }: {
667
+ count: number;
668
+ }) => string;
669
+ readonly summaryOther: ({ count }: {
670
+ count: number;
671
+ }) => string;
672
+ /** `{count} changes — adds 2 nodes, connects 1 edge. Applied together, undone together.` */
673
+ readonly batchSummary: ({ count, parts }: {
674
+ count: number;
675
+ parts: string;
676
+ }) => string;
677
+ readonly rememberEdits: "Apply further edits from any agent on this page without asking, until this page is closed";
604
678
  };
605
679
  };
@@ -243,6 +243,26 @@ export const defaultMessages = {
243
243
  placeholder: 'Describe what you want to build...',
244
244
  send: 'Send message',
245
245
  autoRetry: ({ attempt, max }) => `Auto-retrying (attempt ${attempt}/${max})…`,
246
+ // Tool-calling turns (tools mode).
247
+ tools: {
248
+ /** Status line while a read tool runs: `Reading: describe_type http_request`. */
249
+ reading: ({ tool, detail }) => detail ? `Reading: ${tool} ${detail}` : `Reading: ${tool}`,
250
+ awaitingApproval: ({ tool }) => `Waiting for your approval: ${tool}`,
251
+ /** Title of the approval dialog when the assistant, not a browser agent, asks. */
252
+ confirmTitle: ({ name }) => `The assistant wants to change “${name}”`,
253
+ /** A read that completed: `Read: describe_type http_request`. */
254
+ read: ({ tool, detail }) => detail ? `Read: ${tool} ${detail}` : `Read: ${tool}`,
255
+ applied: ({ tool, detail }) => detail ? `Applied: ${detail}` : `Done: ${tool}`,
256
+ rejected: ({ tool }) => `You rejected: ${tool}`,
257
+ failed: ({ tool, error }) => `${tool} failed: ${error}`,
258
+ rounds: ({ count }) => `${count} ${count === 1 ? 'tool round' : 'tool rounds'}`,
259
+ legacyFallback: 'This backend does not support tool-calling turns; using the text mode for this session.',
260
+ aborted: ({ reason }) => `Stopped: ${reason}`,
261
+ /** Deterministic warning under the reply when one or more tool calls failed this turn. */
262
+ failedSummary: ({ count }) => count === 1
263
+ ? 'One tool call failed during this turn. Check the steps above before relying on the reply.'
264
+ : `${count} tool calls failed during this turn. Check the steps above before relying on the reply.`
265
+ },
246
266
  // CommandPreview labels.
247
267
  commandPreview: {
248
268
  ariaLabel: 'Command preview',
@@ -502,6 +522,20 @@ export const defaultMessages = {
502
522
  confirmTitle: ({ name }) => `A browser agent wants to change “${name}”`,
503
523
  confirmCount: ({ count }) => `${count === 1 ? '1 change' : `${count} changes`} — applied together, undone together.`,
504
524
  reject: 'Reject',
505
- apply: 'Apply'
525
+ apply: 'Apply',
526
+ saveLine: ({ name }) => `Save “${name}” to the server`,
527
+ saveHint: 'Writes the workflow to the server. This cannot be undone from the editor.',
528
+ runLine: ({ name }) => `Run “${name}” on the server`,
529
+ runHint: 'Starts a run of the saved workflow. Unsaved changes are not part of it.',
530
+ /** One clause per kind of change; joined into the batch summary. */
531
+ summaryAdds: ({ count }) => `adds ${count} ${count === 1 ? 'node' : 'nodes'}`,
532
+ summaryDeletes: ({ count }) => `deletes ${count} ${count === 1 ? 'node' : 'nodes'}`,
533
+ summaryConnects: ({ count }) => `connects ${count} ${count === 1 ? 'edge' : 'edges'}`,
534
+ summaryDisconnects: ({ count }) => `removes ${count} ${count === 1 ? 'edge' : 'edges'}`,
535
+ summaryConfigs: ({ count }) => `sets ${count} config ${count === 1 ? 'key' : 'keys'}`,
536
+ summaryOther: ({ count }) => `${count} other ${count === 1 ? 'change' : 'changes'}`,
537
+ /** `{count} changes — adds 2 nodes, connects 1 edge. Applied together, undone together.` */
538
+ batchSummary: ({ count, parts }) => `${count} changes — ${parts}. Applied together, undone together.`,
539
+ rememberEdits: 'Apply further edits from any agent on this page without asking, until this page is closed'
506
540
  }
507
541
  };
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * @module services/chatService
8
8
  */
9
- import type { ChatRequest, ChatResponse, ChatHistoryMessage } from '../types/chat.js';
9
+ import type { ChatRequest, ChatHistoryMessage, ChatToolResultsRequest, ChatTurnResponse } from '../types/chat.js';
10
10
  import type { EndpointConfig } from '../config/endpoints.js';
11
11
  import type { AuthProvider } from '../types/auth.js';
12
12
  /**
@@ -43,13 +43,31 @@ export declare class ChatService {
43
43
  */
44
44
  private request;
45
45
  /**
46
- * Send a message to the chat endpoint
46
+ * Send a message to the chat endpoint.
47
+ *
48
+ * With a {@link ChatTurnRequest} (a `tools` list) a tool-calling server
49
+ * answers a {@link ChatTurnResponse}; a legacy server ignores the list and
50
+ * answers a plain {@link ChatResponse} (no `turnId`). The return type is
51
+ * the union of the two so callers branch on `turnId`.
47
52
  *
48
53
  * @param workflowId - The workflow ID
49
54
  * @param request - The chat request payload
50
55
  * @returns The chat response from the LLM
51
56
  */
52
- sendMessage(endpointConfig: EndpointConfig | null, workflowId: string, request: ChatRequest, authProvider?: AuthProvider): Promise<ChatResponse>;
57
+ sendMessage(endpointConfig: EndpointConfig | null, workflowId: string, request: ChatRequest, authProvider?: AuthProvider): Promise<ChatTurnResponse>;
58
+ /**
59
+ * Whether the configured backend has the tool-results door — the
60
+ * precondition for the panel's tools mode.
61
+ */
62
+ supportsToolTurns(endpointConfig: EndpointConfig | null): boolean;
63
+ /**
64
+ * Continue a tool-calling turn with the results of the calls the assistant
65
+ * made. The server runs the reasoner again and answers either more calls
66
+ * (`done: false`) or the final text (`done: true`).
67
+ *
68
+ * @throws Error when the backend has no `chat.toolResults` endpoint
69
+ */
70
+ sendToolResults(endpointConfig: EndpointConfig | null, workflowId: string, turnId: string, request: ChatToolResultsRequest, authProvider?: AuthProvider): Promise<ChatTurnResponse>;
53
71
  /**
54
72
  * Get conversation history for a workflow
55
73
  *
@@ -75,7 +75,12 @@ export class ChatService {
75
75
  // Chat Operations
76
76
  // =========================================================================
77
77
  /**
78
- * Send a message to the chat endpoint
78
+ * Send a message to the chat endpoint.
79
+ *
80
+ * With a {@link ChatTurnRequest} (a `tools` list) a tool-calling server
81
+ * answers a {@link ChatTurnResponse}; a legacy server ignores the list and
82
+ * answers a plain {@link ChatResponse} (no `turnId`). The return type is
83
+ * the union of the two so callers branch on `turnId`.
79
84
  *
80
85
  * @param workflowId - The workflow ID
81
86
  * @param request - The chat request payload
@@ -92,6 +97,33 @@ export class ChatService {
92
97
  body: JSON.stringify(request)
93
98
  }, authProvider);
94
99
  }
100
+ /**
101
+ * Whether the configured backend has the tool-results door — the
102
+ * precondition for the panel's tools mode.
103
+ */
104
+ supportsToolTurns(endpointConfig) {
105
+ return typeof endpointConfig?.endpoints?.chat?.toolResults === 'string';
106
+ }
107
+ /**
108
+ * Continue a tool-calling turn with the results of the calls the assistant
109
+ * made. The server runs the reasoner again and answers either more calls
110
+ * (`done: false`) or the final text (`done: true`).
111
+ *
112
+ * @throws Error when the backend has no `chat.toolResults` endpoint
113
+ */
114
+ async sendToolResults(endpointConfig, workflowId, turnId, request, authProvider) {
115
+ const config = this.getConfig(endpointConfig);
116
+ const template = config.endpoints.chat.toolResults;
117
+ if (!template) {
118
+ throw new Error('This backend has no chat tool-results endpoint.');
119
+ }
120
+ const url = buildEndpointUrl(config, template, { id: workflowId, turnId });
121
+ logger.debug('[ChatService] Posting tool results to', url);
122
+ return this.request(config, url, {
123
+ method: 'POST',
124
+ body: JSON.stringify(request)
125
+ }, authProvider);
126
+ }
95
127
  /**
96
128
  * Get conversation history for a workflow
97
129
  *
@@ -65,7 +65,13 @@ export interface GlobalExportOptions {
65
65
  * 6. Call onMarkAsSaved / onAfterSave hooks
66
66
  * 7. Show toast notifications (respecting features.showToasts)
67
67
  */
68
- export declare function globalSaveWorkflow(options?: GlobalSaveOptions): Promise<void>;
68
+ /**
69
+ * Resolves `true` when the workflow was written, `false` when nothing was
70
+ * saved because there was no workflow or `onBeforeSave` cancelled. A failed
71
+ * request throws. Callers that relay the outcome (the WebMCP `save` tool)
72
+ * must not read a quiet return as a save.
73
+ */
74
+ export declare function globalSaveWorkflow(options?: GlobalSaveOptions): Promise<boolean>;
69
75
  /**
70
76
  * Export the current workflow as a downloadable JSON file.
71
77
  *
@@ -73,6 +73,12 @@ async function flushPendingFormChanges() {
73
73
  * 6. Call onMarkAsSaved / onAfterSave hooks
74
74
  * 7. Show toast notifications (respecting features.showToasts)
75
75
  */
76
+ /**
77
+ * Resolves `true` when the workflow was written, `false` when nothing was
78
+ * saved because there was no workflow or `onBeforeSave` cancelled. A failed
79
+ * request throws. Callers that relay the outcome (the WebMCP `save` tool)
80
+ * must not read a quiet return as a save.
81
+ */
76
82
  export async function globalSaveWorkflow(options = {}) {
77
83
  const { eventHandlers, onMarkAsSaved, onSaved } = options;
78
84
  const features = { ...DEFAULT_FEATURES, ...options.features };
@@ -87,13 +93,13 @@ export async function globalSaveWorkflow(options = {}) {
87
93
  if (features.showToasts) {
88
94
  apiToasts.error('Save workflow', 'No workflow to save');
89
95
  }
90
- return;
96
+ return false;
91
97
  }
92
98
  // Step 2 — Allow the parent to cancel the save
93
99
  if (eventHandlers?.onBeforeSave) {
94
100
  const shouldContinue = await eventHandlers.onBeforeSave(currentWorkflow);
95
101
  if (shouldContinue === false) {
96
- return;
102
+ return false;
97
103
  }
98
104
  }
99
105
  const loadingToast = features.showToasts ? apiToasts.loading('Saving workflow') : null;
@@ -124,7 +130,10 @@ export async function globalSaveWorkflow(options = {}) {
124
130
  // Explicit key list, so every contract field must be named here:
125
131
  // omitting `interface` silently strips the declared contract on save
126
132
  // (absent means "declares no interface" to the server).
127
- ...(currentWorkflow.interface !== undefined && { interface: currentWorkflow.interface })
133
+ ...(currentWorkflow.interface !== undefined && { interface: currentWorkflow.interface }),
134
+ // The revision the editor loaded, so a server that checks it can refuse
135
+ // a stale write (409 CONFLICT) instead of letting the last write win.
136
+ ...(currentWorkflow.revision !== undefined && { revision: currentWorkflow.revision })
128
137
  };
129
138
  // Step 4 — Persist via this instance's API client.
130
139
  // id-presence (computed above) decides update vs create — never UUID-regex.
@@ -144,6 +153,10 @@ export async function globalSaveWorkflow(options = {}) {
144
153
  }
145
154
  });
146
155
  }
156
+ // Step 5b — The save minted a new revision (and may have refreshed what the
157
+ // user may do); take the server's word so the next save sends the current
158
+ // stamp rather than the one this save just superseded.
159
+ fd.workflow.acknowledgeServer({ revision: savedWorkflow.revision, can: savedWorkflow.can });
147
160
  // Step 6a — Mark dirty state as clean
148
161
  if (onMarkAsSaved) {
149
162
  onMarkAsSaved();
@@ -165,6 +178,7 @@ export async function globalSaveWorkflow(options = {}) {
165
178
  if (eventHandlers?.onAfterSave) {
166
179
  await eventHandlers.onAfterSave(savedWorkflow);
167
180
  }
181
+ return true;
168
182
  }
169
183
  catch (error) {
170
184
  if (loadingToast)
@@ -181,7 +195,9 @@ export async function globalSaveWorkflow(options = {}) {
181
195
  suppressToast = eventHandlers.onApiError(errorObj, 'save') === true;
182
196
  }
183
197
  if (features.showToasts && !suppressToast) {
184
- apiToasts.error('Save workflow', errorObj.message);
198
+ // The error object, not its message: an ApiError carries the server's
199
+ // reasons as `details`, and the toast renders them as a list.
200
+ apiToasts.error('Save workflow', errorObj);
185
201
  }
186
202
  throw error;
187
203
  }
@@ -21,6 +21,17 @@ export type ToastType = 'success' | 'error' | 'warning' | 'info' | 'loading';
21
21
  */
22
22
  export interface ToastOptions {
23
23
  duration?: number;
24
+ /**
25
+ * Reasons behind the message, rendered as a list under it (errors and
26
+ * warnings only). Pass `ApiError.details` here.
27
+ */
28
+ details?: readonly string[];
29
+ /**
30
+ * Stable id: a toast with the same id replaces the one already showing
31
+ * instead of stacking. Errors and warnings default to an id derived from
32
+ * their text, so repeating a failing action does not wallpaper the screen.
33
+ */
34
+ id?: string;
24
35
  position?: 'top-left' | 'top-center' | 'top-right' | 'bottom-left' | 'bottom-center' | 'bottom-right';
25
36
  }
26
37
  /**
@@ -28,11 +39,21 @@ export interface ToastOptions {
28
39
  */
29
40
  export declare function showSuccess(message: string, options?: ToastOptions): string;
30
41
  /**
31
- * Show an error toast notification
42
+ * Show an error toast notification.
43
+ *
44
+ * Stays until the user closes it (TOAST_DURATION.ERROR is Infinity). Pass a
45
+ * finite `duration` to opt back into auto-dismiss.
32
46
  */
33
47
  export declare function showError(message: string, options?: ToastOptions): string;
34
48
  /**
35
- * Show a warning toast notification
49
+ * Show a warning toast notification.
50
+ *
51
+ * Persists until dismissed, like an error. The stance behind that: a warning
52
+ * here is not "done, by the way" — the editor reserves it for something the
53
+ * user should act on (an agent's config key that was ignored, an import that
54
+ * dropped nodes), and a message like that must not vanish mid-read. Pass a
55
+ * finite `duration` for a warning that is only informational. Wears its own
56
+ * icon and colour so it is not mistaken for an error.
36
57
  */
37
58
  export declare function showWarning(message: string, options?: ToastOptions): string;
38
59
  /**