@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
package/CHANGELOG.md CHANGED
@@ -5,6 +5,62 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [2.8.0] - 2026-09-10
9
+
10
+ ### Added
11
+
12
+ - **The AI Assistant panel is now a tool-calling agent, and it shares one execution path with browser agents.** Until now the panel was a single-shot text generator: one reply holding a ```flowdrop block, then a click to apply, with the whole node-type catalogue re-sent on every message and no way to ask before acting, save, run, or watch a run. In the new **tools mode** (behaviour setting **`chatMode: 'tools'`**, the default) a user message is one _turn_: the panel sends its tool catalogue with the message, the server answers with tool calls, the panel runs them and posts the results, and the loop continues until the assistant answers in text. The tools are the editor's WebMCP editor tools — `describe_type`, `search_types`, `batch`, `save`, `run`, `run_status`and the rest — run through the **same runtime the WebMCP registration uses**: same argument validation, same layout opt-out, same approval dialog (reads run unasked; document changes ask once per round with the batch summary;`save`and`run` always ask), same one-transaction-one-undo-step, same teaching errors. The transcript shows each call as a compact status line — reading, waiting for approval, applied with the dialog's own summary, rejected, failed — and a rejection is a result the model reads, not the end of the turn.
13
+ - **Protocol.** The first request of a turn is a `ChatTurnRequest` — the existing `ChatRequest` plus `tools: ChatToolDefinition[]` (`{name, description, input_schema, readOnly}`, bare verbs, no prefix). The server answers a `ChatTurnResponse` (`turnId`, `toolCalls?: [{id, name, args}]`, `content?`, `done`). Tool results go to a new endpoint, **`chat.toolResults`** (`POST /workflows/{id}/chat/turns/{turnId}/tool-results`, body `{results: [{toolCallId, content, isError?}]}`), via **`chatService.sendToolResults()`**. The endpoint is optional in `EndpointConfig`; the default preset carries it.
14
+ - **Graceful with an older backend.** A server that ignores `tools` and answers a plain `ChatResponse` (no `turnId`) puts the panel into the text mode for the rest of the session, with one notice in the transcript. **`chatMode: 'dsl'`** selects the text mode outright; it is deprecated and will be removed one minor after tools mode ships in fddo, together with `chatAutoRetry` and the panel's use of `CommandPreview`.
15
+ - **fdnpm owns the catalogue.** `toToolDefinitions(runtime)` (new, `@flowdrop/flowdrop/chat`) projects the runtime's descriptors; the server holds no copy of the schemas. Measured 2026-09-09: 13.3 kB with all 25 tools, 10.7 kB without `view` and the host tools; `catalogueBytes()` is exported for hosts that want to check.
16
+ - **One gate per editor.** Whichever agent surface comes first — the WebMCP registration or the panel — creates the approval gate and publishes it as **`instance.approvalGate`**; the other reuses it. One "don't ask again for edits" covers both surfaces, and two dialogs never stack. The dialog still says who is asking: `GateRequest` gained **`title`**, `ToolRuntimeOptions` gained **`dialogTitle(editorName)`**, and the panel passes its own wording through them. `ToolPreview` now reports what `runTool` will actually do — `commands` after the layout opt-out, the **`skipped`** layout commands, and **`asks`**, true only when the call will wait on the gate (not under `approval: 'auto'`, not once edits are pre-approved, always for `save` and `run`); the transcript's "waiting for your approval" line comes from `asks`. A server that continues a turn (`done: false`) with no tool calls is reported as an `aborted` outcome, not rendered as an empty reply. `summarizeCommands` moved to the descriptors module (still exported from `@flowdrop/flowdrop/webmcp`); `WebMCPConfirm` takes `title` instead of `editorName`.
17
+ - **Host hooks reach the panel.** `mountFlowDropApp` now publishes its `onSave` (its own Save) and the `onRun`/`onRunStatus` hooks on the instance as **`instance.host`** (`HostHooksStore`), whether or not WebMCP is on, so the assistant persists and runs exactly the way a browser agent does — and exactly the way clicking Save does. A new mount option **`host: { onSave?, onRun?, onRunStatus? }`** carries them; hooks given inside the `webmcp` option take precedence and, the other way round, `webmcp: true` now picks up the `host` hooks, so a Drupal host passes them once and both surfaces share them. Svelte hosts set `instance.host.set({...})` themselves.
18
+ - **`createToolRuntime()`** (new, `@flowdrop/flowdrop/webmcp`) — the execution body behind every WebMCP tool, extracted from the registration as one `runTool(name, input): Promise<ToolResult>` over editor tools and host tools alike, plus `preview(name, input)` (what a call would do), `descriptors`, `hostTools`, `gate`, `dispose()`. `attachWebMCP` is now registration only and behaves identically. Also exported: `buildHostToolDescriptors(hooks)`, `createApprovalGate`, `summarizeCommands`, `GateBusyError`, and the types `ToolRuntime`, `ToolRuntimeOptions`, `ToolPreview`, `HostHooks`, `HostToolDescriptor`, `ApprovalGate`, `GateRequest`, `CreateGateOptions`. An unknown tool name answers `UNKNOWN_TOOL` with the names it has.
19
+ - **`runTurn(request, deps)`** (new, `@flowdrop/flowdrop/chat`) — the turn driver, free of Svelte and the DOM: `send` → for each call `runTool` → `sendToolResults` → until `done`, emitting `TurnEvent`s (`reading`, `awaiting-approval`, `applied`, `rejected`, `failed`, `round-complete`, `final`) and returning a `TurnOutcome` (`final` | `legacy` | `aborted`). A client-side `maxRounds` (default 32) backstops the server's own bound. With `parseOutcome`, `toolResultText` and the types `TurnDriverDeps`, `TurnEvent`, `TurnOutcome`, `ToolOutcome`.
20
+ - **New chat types** in `@flowdrop/flowdrop/chat`: `ChatToolDefinition`, `ChatToolCall`, `ChatToolResult`, `ChatToolResultsRequest`, `ChatTurnRequest`, `ChatTurnResponse`. New strings under `defaultMessages.chat.tools` (`reading`, `read`, `awaitingApproval`, `applied`, `rejected`, `failed`, `rounds`, `legacyFallback`, `aborted`, and `confirmTitle` — the approval dialog says the assistant is asking, not a browser agent). The Settings panel gained "AI Assistant Mode". The MSW mock backend scripts one round of reads for a tool-calling turn so the dev pages exercise the mode.
21
+
22
+ - **API refusals arrive with their reasons.** `ApiError.details` holds the server's reasons behind `message` — for a fddo validation failure the `details[].message` strings, for a 403 the permission the user lacks. Error toasts render them as a list under the headline, the WebMCP `save` tool relays them to the agent, and the exported `ToastOptions.details` / `ToastOptions.id` let a host do the same. New exports: `parseApiErrorBody`, `errorDetails`.
23
+ - **Hosts can hide the Command Console and the AI Assistant.** Two new feature flags, **`features.console`** and **`features.assistant`** (both default `true`), drop the matching tab from the console / AI Assistant group wherever it is hosted (sidebar, bottom panel, modal). With one tab left the strip collapses to a plain panel; with both off the canvas toggle button and its backtick shortcut disappear too. Independent of the flag, the AI Assistant tab is now offered only when the endpoint configuration carries a `chat` group — before, a host without a chat backend still got the tab with a dead "requires backend configuration" notice. Browser agents (WebMCP) are unaffected either way; they drive the tool runtime, not the panel.
24
+ - **Tools mode reports a failed turn deterministically, instead of trusting the model's closing prose.** A `batch` call that fails and rolls back no longer lets the assistant's final text claim success unchallenged: `runTurn`'s final `TurnOutcome` and `'final'` `TurnEvent` now carry `failed`/`rejected` counts over the whole turn, and the panel shows a warning under the reply (`defaultMessages.chat.tools.failedSummary`) whenever `failed > 0`.
25
+ - **Interim model text now shows up in the trace.** A non-final `ChatTurnResponse` can carry `content` alongside `toolCalls` — text the model wrote next to its calls, e.g. "this node has no url input port". The driver emits it as a new `'note'` `TurnEvent`, and the panel renders it as an italic note line in the tool trace.
26
+ - New tool-line status `'note'` and `DisplayMessage.warning` in `AIChatPanel.svelte`.
27
+
28
+ - **`ApprovalGate.asks`** — whether the gate can ask at all (`false` under `approval: 'auto'`). `ToolPreview.asks` reads it, so the transcript's "waiting for your approval" line is honest for a shared gate too: before, a runtime given another surface's gate assumed it asked.
29
+
30
+ ### Fixed
31
+
32
+ - **The AI Assistant panel no longer clears an approval gate it did not publish.** Closing the console after a tools-mode message used to null `instance.approvalGate` even when the WebMCP registration had published it, so the next panel built a second gate — one "don't ask again" per surface, and two dialogs could stack. The panel now clears only the gate it created. A turn still in flight when the panel unmounts keeps its runtime until the turn ends instead of answering `DETACHED` to the model for the rest of the round, and the transcript scrolls as tool lines and the reply grow.
33
+
34
+ ### Changed
35
+
36
+ - **Error and warning toasts stay until dismissed.** `TOAST_DURATION.ERROR` and `TOAST_DURATION.WARNING` are now `Infinity`; both toasts carry a close button, and a toast with the same text replaces the one already showing instead of stacking. This is a policy change for the exported `showWarning`: the editor treats a warning as something the user should act on, not a "done, by the way". A caller that wants an informational warning passes a finite `duration`. Warnings also wear their own icon and colour instead of the error's.
37
+ - **The API client retries only what can change.** Network failures, 408, 429 and 5xx are retried; every other 4xx is a refusal and is thrown at once. A stale save used to send three PUTs and get three 409s.
38
+ - **The WebMCP approval dialog now looks like the rest of the editor.** `WebMCPConfirm` follows the Settings modal shell — blurred backdrop, header / body / footer on the `xl` spacing rhythm, an `lg` title, the command list as a bordered card, a 16px checkbox, an enter animation, a bottom-sheet layout under 640px — and its buttons compose on `.flowdrop-btn` (`--primary` / `--outline`) instead of one-off styles. Test ids are unchanged.
39
+
40
+ ## [2.7.0] - 2026-09-09
41
+
42
+ ### Added
43
+
44
+ - **A browser agent can now _finish_ a workflow, not just edit one.** Building a four-node fetch-and-convert flow through the 2.6.0 tools showed the gaps: an agent could not learn a node type's ports or config without adding a node first, could not tell whether the result was valid, and could not run it. The editor-tool set closes them, on one rule — **the tools read only what the editor has already fetched** (the node type catalog and the open workflow); no new endpoints, no per-tool round trips.
45
+ - **`describe_type`** (new command and tool, read-only) describes a node type before it is used: input and output ports with data type and required flag, every config key with type, enum, default and description, and — when the host publishes them — the **confirmation policy** (`ask` means a run pauses for a person at this node), what the user may do with it (`can`) and host-written guidance (`agent`). Three new optional fields on `NodeMetadata` carry those: `confirmation`, `can`, `agent`; the library passes them through verbatim.
46
+ - **`search_types { query }`** (new command and tool, read-only) finds node types by a case-insensitive substring of id, name, description or tags; a blank query is refused with `EMPTY_QUERY` (new `CommandErrorCode`) instead of returning the catalog. **`list_types` rows now carry `description` and `tags`.** The text DSL gained `describe <type>` and `search <text>` to match, and the command console formats both.
47
+ - **`get_config` returns the schema next to the value**, and its `key` is optional: without one it answers every current value under `values` and the whole config schema. `get <nodeId>` works in the DSL too. The result is one of two shapes — `GetConfigKeyResultData` (`key`, `value`, `schema?`) or `GetConfigAllResultData` (`values`, `schema[]`) — narrow on `'key' in data`.
48
+ - **Errors teach.** A failure names the valid alternatives instead of stopping at "not found": an unknown node lists the workflow's nodes (or says to `add_node` first on an empty canvas); an unknown type names near misses and points at `list_types`; an unknown port lists the node's ports on both sides; a missing edge lists the edges leaving that node; an unknown config key lists the keys. Lists are capped at 15. `set_config` on a key the schema does not declare is still stored (hosts keep config open) but now carries an **`unknown_key` warning** with the declared keys — fatal only under `strict`.
49
+ - **Tool descriptions carry the call order.** `add_node`, `set_config`, `swap_node` and `batch` — the tools that take a type or a config key — end with "call `describe_type` before adding or configuring a type you have not seen; group several changes in one `batch`; `save` when done", and examples use type ids that exist (`http_request`, not `llm_node`).
50
+ - **`run` and `run_status`** tools, behind two new host hooks on `attachWebMCP` and the `webmcp` mount option: **`onRun(inputs) → Promise<HostEnvelope<RunStarted>>`** and **`onRunStatus(runId) → Promise<HostEnvelope<RunStatus>>`**. `run` is gated like `save` and flagged consequential; `run_status` is a read. A paused run is relayed as **`code: 'PENDING'`** with the node id and message it waits on — a person must act in the editor; no tool answers an interrupt, on purpose. `run_status` is registered only when both hooks are given; neither tool exists without its hook.
51
+ - **One result envelope for host hooks.** `onSave`, `onRun` and `onRunStatus` may answer `{ ok, code?, message?, data?, can? }` (`HostEnvelope`), with the codes `FORBIDDEN`, `UNAVAILABLE`, `NEEDS_APPROVAL`, `INVALID`, `CONFLICT`, `PENDING`, `NOT_FOUND` — aligned with fddo's API-8 `error_code` vocabulary where the two meet. The tool relays `code`, `message`, `data` and `can` untouched. `onSave` may still resolve to nothing (saved) or throw (`SAVE_FAILED`); a thrown error that is a 409 or carries `errorData.error_code === 'CONFLICT'` is relayed as **`CONFLICT`** with a reload hint.
52
+ - **The server stays the authority; the client pre-empts.** A workflow payload may now carry **`can: { save, run, … }`** and a **`revision`** (two new optional fields on `Workflow`). `save` and `run` answer `FORBIDDEN` before opening a dialog when `can` says no; when the host says nothing, the server decides. The save path sends the loaded `revision` back so a server that checks it can refuse a stale write, and takes the new `revision`/`can` from the response (`instance.workflow.acknowledgeServer()` — bookkeeping only, no history entry, no dirty flag).
53
+ - **The confirm dialog summarises a batch** — "4 changes — adds 2 nodes, connects 1 edge, sets 1 config key." — above the line list, and offers **"Apply further edits from any agent on this page without asking, until this page is closed"** — worded as what it does: the gate cannot tell one agent from another, so once ticked every caller on the page is covered. Ticked (and approved), later _edits_ run without the dialog; `save` and `run` always ask and never offer the box. Off with **`rememberEdits: false`**. Nine new strings under `defaultMessages.webmcp` (`runLine`, `runHint`, `summary*`, `batchSummary`, `rememberEdits`); Tab now cycles Apply → Reject → checkbox.
54
+ - **A browser agent can now save.** Feedback from the first WebMCP release: the first batch of nodes an agent added vanished on reload because nothing had persisted them — `flowdrop_add_node` and friends change the in-memory workflow, but only the editor's own Save button wrote it to the server. There is now a **`flowdrop_save`** tool: registered whenever `attachWebMCP` is given an **`onSave: () => Promise<void>`**, and automatically on the `mountFlowDropApp` path, where it defaults to the mount's own Save unless the host supplies its own `onSave`. Like any change, it asks — a save cannot be undone from the editor — and its `annotations` carry the new **`consequentialHint: true`** (added to the WebMCP spec 2026-09-03: "executing the tool will result in consequential actions that are significant, real-world, or non-reversible"). Approval callbacks (`WebMCPApproval` functions) now receive a second argument, `(commands, { tool })` — additive, existing one-argument callbacks keep working; for `save` the `commands` array is empty and `request.tool === 'save'`.
55
+ - **A bridge to desktop MCP clients, for browsers without the origin trial** (`installBridgedModelContext`, `createBridgedModelContext` in `@flowdrop/flowdrop/webmcp`). Presents the same `modelContext` surface over a page-side relay widget of the [`@jason.today/webmcp`](https://github.com/jasonjmcghee/webmcp) shape (`registerTool(name, description, inputSchema, execute)`), so Claude Code, Claude Desktop or Cursor can call the editor tools through a localhost MCP server the user runs and authorises with a token. Install it before the editor mounts; it is a no-op when a real runtime exists. The widget cannot unregister a tool, so after the editor is destroyed its tools answer a structured `UNAVAILABLE` until the page unloads. The relay's server times a tool call out after 30 seconds — a confirm dialog left open longer returns a timeout to the agent while the dialog stays up. The gate, `can` and the server's permissions apply unchanged; hosts should make the bridge an explicit opt-in.
56
+ - **New exported types** from `@flowdrop/flowdrop/core` and `/commands`: `DescribeTypeCommand`, `SearchTypesCommand`, `TypeSummary`, `PortDescription`, `ConfigKeyDescription`, `DescribeTypeResultData`, `SearchTypesResultData`, `GetConfigKeyResultData`, `GetConfigAllResultData`; from `/webmcp`: `HostCode`, `HostEnvelope`, `RunStarted`, `RunPending`, `RunStatus`, `WebMCPApprovalRequest`, `WebMCPWidgetLike`, `BridgedModelContext`. `NodeMetadata` gained `confirmation`, `can`, `agent` (`NodeConfirmation`, `NodeAgentGuidance`); `Workflow` gained `can`, `revision`.
57
+
58
+ ### Fixed
59
+
60
+ - **`mountFlowDropApp(...).save()` and `globalSaveWorkflow()` resolve `true` when the workflow was written and `false` when nothing was saved** (no workflow, or `onBeforeSave` cancelled). Before, both resolved to nothing either way, and the mount path's default `save` tool reported "Workflow saved" on a cancelled save. It now answers `{ ok: false, code: 'UNAVAILABLE' }`. Widening `void` to `boolean` is additive for callers.
61
+ - **The WebMCP confirm dialog no longer renders in the browser's serif fallback on Drupal.** The dialog mounts on `document.body`, outside the editor, and used `font-family: inherit` — on admin themes that scope their font to a wrapper, that is Times. It now uses a new public token **`--fd-font-sans`** (a system-ui stack), with an explicit size and line-height, so it reads like the editor wherever it is mounted. Hosts can override the token at `:root`.
62
+ - **`set_config` no longer warns "Expected type 'string,boolean' but got 'string'"** when a node config property declares several JSON Schema types; the warning now reads `Expected type 'string' or 'boolean' but got 'number'` and fires only when the value matches none of them.
63
+
8
64
  ## [2.6.0] - 2026-09-03
9
65
 
10
66
  ### Added
@@ -18,8 +18,36 @@ export declare class ApiError extends Error {
18
18
  readonly errorData: Record<string, unknown>;
19
19
  /** Operation that was being performed */
20
20
  readonly operation: string;
21
- constructor(message: string, status: number, operation: string, errorData?: Record<string, unknown>);
21
+ /**
22
+ * The reasons behind `message`, one per line, already human-readable.
23
+ * For a fddo validation refusal these are the `details[].message` strings;
24
+ * empty when the server gave only a headline.
25
+ */
26
+ readonly details: readonly string[];
27
+ constructor(message: string, status: number, operation: string, errorData?: Record<string, unknown>, details?: readonly string[]);
22
28
  }
29
+ /**
30
+ * The reasons an error carries, or none. An `ApiError` contributes its
31
+ * `details`; a plain `Error` or a string has nothing to add. Duck-typed rather
32
+ * than `instanceof` because the error may come from a host page that bundled
33
+ * its own copy of this client.
34
+ */
35
+ export declare function errorDetails(error: unknown): readonly string[];
36
+ /**
37
+ * Splits a non-2xx API body into a headline and its reasons.
38
+ *
39
+ * fddo answers a refusal as `{ success: false, error, error_code?, details? }`.
40
+ * `error` is the headline ("Workflow validation failed"); what the user can
41
+ * act on lives in `details` — for a validation failure an array of
42
+ * `{ code, message, locator }`. The exception subscriber's envelope carries
43
+ * the headline in `error` and the reason in `message`. Both are kept as
44
+ * structure (headline + list) so the toast can render a list instead of a
45
+ * semicolon-joined paragraph; the raw body still travels on `errorData`.
46
+ */
47
+ export declare function parseApiErrorBody(errorData: unknown, status: number, statusText: string): {
48
+ message: string;
49
+ details: string[];
50
+ };
23
51
  /**
24
52
  * Enhanced HTTP API client for FlowDrop with configurable endpoints
25
53
  *
@@ -20,13 +20,81 @@ export class ApiError extends Error {
20
20
  errorData;
21
21
  /** Operation that was being performed */
22
22
  operation;
23
- constructor(message, status, operation, errorData = {}) {
23
+ /**
24
+ * The reasons behind `message`, one per line, already human-readable.
25
+ * For a fddo validation refusal these are the `details[].message` strings;
26
+ * empty when the server gave only a headline.
27
+ */
28
+ details;
29
+ constructor(message, status, operation, errorData = {}, details = []) {
24
30
  super(message);
25
31
  this.name = 'ApiError';
26
32
  this.status = status;
27
33
  this.operation = operation;
28
34
  this.errorData = errorData;
35
+ this.details = details;
36
+ }
37
+ }
38
+ /**
39
+ * The reasons an error carries, or none. An `ApiError` contributes its
40
+ * `details`; a plain `Error` or a string has nothing to add. Duck-typed rather
41
+ * than `instanceof` because the error may come from a host page that bundled
42
+ * its own copy of this client.
43
+ */
44
+ export function errorDetails(error) {
45
+ if (!error || typeof error !== 'object')
46
+ return [];
47
+ const details = error.details;
48
+ return Array.isArray(details) ? details.filter((d) => typeof d === 'string') : [];
49
+ }
50
+ /**
51
+ * Splits a non-2xx API body into a headline and its reasons.
52
+ *
53
+ * fddo answers a refusal as `{ success: false, error, error_code?, details? }`.
54
+ * `error` is the headline ("Workflow validation failed"); what the user can
55
+ * act on lives in `details` — for a validation failure an array of
56
+ * `{ code, message, locator }`. The exception subscriber's envelope carries
57
+ * the headline in `error` and the reason in `message`. Both are kept as
58
+ * structure (headline + list) so the toast can render a list instead of a
59
+ * semicolon-joined paragraph; the raw body still travels on `errorData`.
60
+ */
61
+ export function parseApiErrorBody(errorData, status, statusText) {
62
+ const fallback = `HTTP ${status}: ${statusText}`;
63
+ if (!errorData || typeof errorData !== 'object')
64
+ return { message: fallback, details: [] };
65
+ const body = errorData;
66
+ const str = (v) => (typeof v === 'string' && v ? v : null);
67
+ const message = str(body.error) ?? str(body.message) ?? fallback;
68
+ const details = [];
69
+ const reason = str(body.message);
70
+ if (reason && reason !== message)
71
+ details.push(reason);
72
+ if (Array.isArray(body.details)) {
73
+ for (const detail of body.details) {
74
+ const text = str(detail) ??
75
+ (detail && typeof detail === 'object'
76
+ ? str(detail.message)
77
+ : null);
78
+ if (text)
79
+ details.push(text);
80
+ }
29
81
  }
82
+ return { message, details };
83
+ }
84
+ /**
85
+ * Whether a failed attempt is worth repeating.
86
+ *
87
+ * Only failures the next attempt could plausibly not repeat: a network failure
88
+ * (`fetch` rejects with a `TypeError`), 408 Request Timeout, 429 Too Many
89
+ * Requests, and 5xx. Every other 4xx is a refusal — the server read the request
90
+ * and said no — and the same bytes will get the same answer. A 2xx whose body
91
+ * is not JSON (`SyntaxError` from `response.json()`) is not retried either:
92
+ * the same proxy will serve the same login page three times.
93
+ */
94
+ function isRetryable(error) {
95
+ if (!(error instanceof ApiError))
96
+ return error instanceof TypeError;
97
+ return error.status === 408 || error.status === 429 || error.status >= 500;
30
98
  }
31
99
  export class EnhancedFlowDropApiClient {
32
100
  config;
@@ -80,6 +148,16 @@ export class EnhancedFlowDropApiClient {
80
148
  const maxAttempts = retryEnabled
81
149
  ? (userApiSettings.retryAttempts ?? this.config.retry?.maxAttempts ?? 3)
82
150
  : 1;
151
+ /**
152
+ * The `ApiError` for a non-2xx response, body read and split into headline
153
+ * and reasons. `statusText` is only the last-resort headline: a fddo 403
154
+ * says which permission is missing, and that must reach the user.
155
+ */
156
+ const refusal = async (response, status, statusText) => {
157
+ const errorData = await response.json().catch(() => ({}));
158
+ const { message, details } = parseApiErrorBody(errorData, status, statusText);
159
+ return new ApiError(message, status, operation, errorData, details);
160
+ };
83
161
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
84
162
  try {
85
163
  const response = await fetch(url, fetchConfig);
@@ -98,19 +176,18 @@ export class EnhancedFlowDropApiClient {
98
176
  continue; // Retry with new headers
99
177
  }
100
178
  }
101
- throw new ApiError('Unauthorized', 401, operation, {});
179
+ throw await refusal(response, 401, 'Unauthorized');
102
180
  }
103
181
  // Handle 403 Forbidden
104
182
  if (response.status === 403) {
105
183
  if (this.authProvider.onForbidden) {
106
184
  await this.authProvider.onForbidden();
107
185
  }
108
- throw new ApiError('Forbidden', 403, operation, {});
186
+ throw await refusal(response, 403, 'Forbidden');
109
187
  }
110
188
  // Handle other errors
111
189
  if (!response.ok) {
112
- const errorData = await response.json().catch(() => ({}));
113
- throw new ApiError(errorData.error ?? `HTTP ${response.status}: ${response.statusText}`, response.status, operation, errorData);
190
+ throw await refusal(response, response.status, response.statusText);
114
191
  }
115
192
  const data = await response.json();
116
193
  return data;
@@ -134,10 +211,7 @@ export class EnhancedFlowDropApiClient {
134
211
  else {
135
212
  lastError = error instanceof Error ? error : new Error(String(error));
136
213
  }
137
- // Don't retry on auth errors (401, 403) or last attempt
138
- if ((lastError instanceof ApiError &&
139
- (lastError.status === 401 || lastError.status === 403)) ||
140
- attempt === maxAttempts) {
214
+ if (!isRetryable(lastError) || attempt === maxAttempts) {
141
215
  logger.error(`API request failed after ${attempt} attempts:`, lastError);
142
216
  throw lastError;
143
217
  }
@@ -10,7 +10,8 @@
10
10
  /**
11
11
  * Determine whether a DSL command type is mutating (modifies workflow state).
12
12
  *
13
- * Read-only commands (list_nodes, list_edges, list_types, info, get_config, help)
13
+ * Read-only commands (list_nodes, list_edges, list_types, describe_type,
14
+ * search_types, info, get_config, help)
14
15
  * return false. All other commands are considered mutating and return true.
15
16
  *
16
17
  * @param commandType - The command type string (e.g., "add", "list_nodes")
@@ -12,6 +12,8 @@ const READ_ONLY_COMMANDS = new Set([
12
12
  'list_nodes',
13
13
  'list_edges',
14
14
  'list_types',
15
+ 'describe_type',
16
+ 'search_types',
15
17
  'info',
16
18
  'get_config',
17
19
  'help'
@@ -19,7 +21,8 @@ const READ_ONLY_COMMANDS = new Set([
19
21
  /**
20
22
  * Determine whether a DSL command type is mutating (modifies workflow state).
21
23
  *
22
- * Read-only commands (list_nodes, list_edges, list_types, info, get_config, help)
24
+ * Read-only commands (list_nodes, list_edges, list_types, describe_type,
25
+ * search_types, info, get_config, help)
23
26
  * return false. All other commands are considered mutating and return true.
24
27
  *
25
28
  * @param commandType - The command type string (e.g., "add", "list_nodes")
@@ -25,4 +25,8 @@ export { default as CommandPreview } from '../components/chat/CommandPreview.sve
25
25
  export { extractCommands } from './responseParser.js';
26
26
  export { isMutatingCommand, isLayoutCommand, isViewCommand, VIEW_COMMAND_TYPES } from './commandClassifier.js';
27
27
  export { buildApiHistory, type ChatLogEntry } from './historyBuilder.js';
28
- export type { ChatMessageRole, ChatHistoryMessage, ChatRequest, ChatResponse, ExtractedCommands, CommandExecutionStatus, CommandPreviewItem } from '../types/chat.js';
28
+ export { toToolDefinitions, catalogueBytes } from './toolCatalogue.js';
29
+ export type { ToolCatalogueSource } from './toolCatalogue.js';
30
+ export { runTurn, parseOutcome, toolResultText } from './turnDriver.js';
31
+ export type { TurnDriverDeps, TurnEvent, TurnOutcome, ToolOutcome } from './turnDriver.js';
32
+ export type { ChatMessageRole, ChatHistoryMessage, ChatRequest, ChatResponse, ExtractedCommands, CommandExecutionStatus, CommandPreviewItem, ChatToolDefinition, ChatToolCall, ChatToolResult, ChatToolResultsRequest, ChatTurnRequest, ChatTurnResponse } from '../types/chat.js';
@@ -31,3 +31,5 @@ export { default as CommandPreview } from '../components/chat/CommandPreview.sve
31
31
  export { extractCommands } from './responseParser.js';
32
32
  export { isMutatingCommand, isLayoutCommand, isViewCommand, VIEW_COMMAND_TYPES } from './commandClassifier.js';
33
33
  export { buildApiHistory } from './historyBuilder.js';
34
+ export { toToolDefinitions, catalogueBytes } from './toolCatalogue.js';
35
+ export { runTurn, parseOutcome, toolResultText } from './turnDriver.js';
@@ -0,0 +1,27 @@
1
+ /**
2
+ * Chat — the tool catalogue the panel sends to the server.
3
+ *
4
+ * fdnpm owns the tool catalogue (D2 of the chat tool-loop plan): the editor's
5
+ * tool descriptors are the single source, and the server holds no copy of
6
+ * their schemas. This module projects a tool runtime's descriptors — editor
7
+ * tools and the host tools its hooks make available — into the shape a
8
+ * function-calling reasoner takes: `{name, description, input_schema}`, plus
9
+ * the read-only flag the server may use to order or summarise calls.
10
+ *
11
+ * Names are the bare verbs (`describe_type`, `batch`, `save`). The WebMCP
12
+ * prefix belongs to the page's tool namespace, not to a conversation.
13
+ *
14
+ * @module chat/toolCatalogue
15
+ */
16
+ import type { ToolRuntime } from '../webmcp/types.js';
17
+ import type { ChatToolDefinition } from '../types/chat.js';
18
+ /** What the projection needs from a runtime: its two descriptor lists. */
19
+ export type ToolCatalogueSource = Pick<ToolRuntime, 'descriptors' | 'hostTools'>;
20
+ /**
21
+ * Project a runtime's tools into chat tool definitions, editor tools first,
22
+ * then the host tools present for the runtime's hooks (the same set the
23
+ * WebMCP registration would register).
24
+ */
25
+ export declare function toToolDefinitions(source: ToolCatalogueSource): ChatToolDefinition[];
26
+ /** Serialized size of a catalogue in bytes, as it travels on the wire. */
27
+ export declare function catalogueBytes(tools: ChatToolDefinition[]): number;
@@ -0,0 +1,35 @@
1
+ /**
2
+ * Chat — the tool catalogue the panel sends to the server.
3
+ *
4
+ * fdnpm owns the tool catalogue (D2 of the chat tool-loop plan): the editor's
5
+ * tool descriptors are the single source, and the server holds no copy of
6
+ * their schemas. This module projects a tool runtime's descriptors — editor
7
+ * tools and the host tools its hooks make available — into the shape a
8
+ * function-calling reasoner takes: `{name, description, input_schema}`, plus
9
+ * the read-only flag the server may use to order or summarise calls.
10
+ *
11
+ * Names are the bare verbs (`describe_type`, `batch`, `save`). The WebMCP
12
+ * prefix belongs to the page's tool namespace, not to a conversation.
13
+ *
14
+ * @module chat/toolCatalogue
15
+ */
16
+ function project(d) {
17
+ return {
18
+ name: d.verb,
19
+ description: d.description,
20
+ input_schema: d.inputSchema,
21
+ readOnly: d.readOnly
22
+ };
23
+ }
24
+ /**
25
+ * Project a runtime's tools into chat tool definitions, editor tools first,
26
+ * then the host tools present for the runtime's hooks (the same set the
27
+ * WebMCP registration would register).
28
+ */
29
+ export function toToolDefinitions(source) {
30
+ return [...source.descriptors.map(project), ...source.hostTools.map(project)];
31
+ }
32
+ /** Serialized size of a catalogue in bytes, as it travels on the wire. */
33
+ export function catalogueBytes(tools) {
34
+ return new TextEncoder().encode(JSON.stringify(tools)).length;
35
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Chat — the turn driver.
3
+ *
4
+ * One user message is one *turn*. The driver sends it with the tool
5
+ * catalogue, and while the server answers with tool calls it runs each call
6
+ * through the tool runtime — the same validation, gate and batch a WebMCP
7
+ * browser agent goes through — posts the results back, and repeats until the
8
+ * server says the turn is done or something stops it.
9
+ *
10
+ * The driver knows nothing of Svelte or the DOM: it takes the three functions
11
+ * it needs (`send`, `sendToolResults`, `runTool`) and reports what happens
12
+ * as events the panel renders. Rejection at the gate is not an error here —
13
+ * the `REJECTED` result goes back to the model, which gets to explain or ask.
14
+ *
15
+ * The final outcome also carries `failed`/`rejected` counts over the whole
16
+ * turn, so the panel can warn deterministically rather than trust the
17
+ * model's closing prose — a batch that failed and rolled back does not
18
+ * always stop the model from claiming success.
19
+ *
20
+ * @module chat/turnDriver
21
+ */
22
+ import type { ChatToolCall, ChatToolResult, ChatToolResultsRequest, ChatTurnRequest, ChatTurnResponse } from '../types/chat.js';
23
+ import type { ToolPreview, ToolResult } from '../webmcp/types.js';
24
+ /** The parsed `{ok, code, …}` payload of a tool result, when it parses. */
25
+ export interface ToolOutcome {
26
+ ok: boolean;
27
+ code?: string;
28
+ message?: string;
29
+ error?: string;
30
+ }
31
+ export type TurnEvent =
32
+ /**
33
+ * The model wrote text alongside its tool calls; shown in the trace, it
34
+ * is not the reply.
35
+ */
36
+ {
37
+ type: 'note';
38
+ content: string;
39
+ round: number;
40
+ }
41
+ /** A read or view call is about to run; nothing to approve. */
42
+ | {
43
+ type: 'reading';
44
+ call: ChatToolCall;
45
+ preview: ToolPreview | null;
46
+ }
47
+ /** The call is about to wait on the gate (`preview.asks`). */
48
+ | {
49
+ type: 'awaiting-approval';
50
+ call: ChatToolCall;
51
+ preview: ToolPreview | null;
52
+ }
53
+ /** The call ran and reported `ok`. */
54
+ | {
55
+ type: 'applied';
56
+ call: ChatToolCall;
57
+ preview: ToolPreview | null;
58
+ outcome: ToolOutcome;
59
+ }
60
+ /** The person rejected the call in the dialog. */
61
+ | {
62
+ type: 'rejected';
63
+ call: ChatToolCall;
64
+ preview: ToolPreview | null;
65
+ outcome: ToolOutcome;
66
+ }
67
+ /** The call failed for any other reason; the result goes back to the model. */
68
+ | {
69
+ type: 'failed';
70
+ call: ChatToolCall;
71
+ preview: ToolPreview | null;
72
+ outcome: ToolOutcome;
73
+ }
74
+ /** Every call of a round ran; the results are being posted. */
75
+ | {
76
+ type: 'round-complete';
77
+ round: number;
78
+ results: ChatToolResult[];
79
+ }
80
+ /** The server ended the turn with text. */
81
+ | {
82
+ type: 'final';
83
+ content: string;
84
+ rounds: number;
85
+ failed: number;
86
+ rejected: number;
87
+ };
88
+ export type TurnOutcome =
89
+ /** A tool-calling server finished the turn. */
90
+ {
91
+ kind: 'final';
92
+ content: string;
93
+ rounds: number;
94
+ turnId: string;
95
+ /** Calls whose parsed outcome was not ok and not a `REJECTED` gate decision. */
96
+ failed: number;
97
+ /** Calls the person rejected at the gate (`code === 'REJECTED'`). */
98
+ rejected: number;
99
+ }
100
+ /**
101
+ * The first response had no `turnId`: a legacy server that answered a plain
102
+ * chat response. `content` is what it said; the caller falls back to the
103
+ * text mode for the rest of the session.
104
+ */
105
+ | {
106
+ kind: 'legacy';
107
+ content: string;
108
+ }
109
+ /**
110
+ * The driver stopped the loop itself: past `maxRounds`, or the server
111
+ * continued the turn (`done: false`) without a single tool call to run.
112
+ */
113
+ | {
114
+ kind: 'aborted';
115
+ reason: string;
116
+ rounds: number;
117
+ turnId: string;
118
+ };
119
+ export interface TurnDriverDeps {
120
+ send(request: ChatTurnRequest): Promise<ChatTurnResponse>;
121
+ sendToolResults(turnId: string, request: ChatToolResultsRequest): Promise<ChatTurnResponse>;
122
+ /** The tool runtime's `runTool`; never expected to throw for a bad call. */
123
+ runTool(name: string, input: unknown): Promise<ToolResult>;
124
+ /** The tool runtime's `preview`, for the events. Optional. */
125
+ preview?(name: string, input: unknown): ToolPreview | null;
126
+ onEvent?(event: TurnEvent): void;
127
+ /**
128
+ * Client-side bound on rounds, a backstop for a server whose own bound
129
+ * (`max_tool_rounds`, D6) failed. Default 32 — well above any server
130
+ * default, so the server's bound is the one that normally speaks.
131
+ */
132
+ maxRounds?: number;
133
+ }
134
+ /** The JSON text of a tool result, as the runtime writes it. */
135
+ export declare function toolResultText(result: ToolResult): string;
136
+ /** Parse the runtime's `{ok, code, …}` payload; a non-JSON text is an opaque success. */
137
+ export declare function parseOutcome(result: ToolResult): ToolOutcome;
138
+ /**
139
+ * Drive one turn to its end. Rejects only when a request fails (network,
140
+ * HTTP error) — the caller shows that as an error bubble; every tool-level
141
+ * failure is a result the model reads.
142
+ */
143
+ export declare function runTurn(request: ChatTurnRequest, deps: TurnDriverDeps): Promise<TurnOutcome>;
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Chat — the turn driver.
3
+ *
4
+ * One user message is one *turn*. The driver sends it with the tool
5
+ * catalogue, and while the server answers with tool calls it runs each call
6
+ * through the tool runtime — the same validation, gate and batch a WebMCP
7
+ * browser agent goes through — posts the results back, and repeats until the
8
+ * server says the turn is done or something stops it.
9
+ *
10
+ * The driver knows nothing of Svelte or the DOM: it takes the three functions
11
+ * it needs (`send`, `sendToolResults`, `runTool`) and reports what happens
12
+ * as events the panel renders. Rejection at the gate is not an error here —
13
+ * the `REJECTED` result goes back to the model, which gets to explain or ask.
14
+ *
15
+ * The final outcome also carries `failed`/`rejected` counts over the whole
16
+ * turn, so the panel can warn deterministically rather than trust the
17
+ * model's closing prose — a batch that failed and rolled back does not
18
+ * always stop the model from claiming success.
19
+ *
20
+ * @module chat/turnDriver
21
+ */
22
+ // ============================================================================
23
+ // Helpers
24
+ // ============================================================================
25
+ /** The JSON text of a tool result, as the runtime writes it. */
26
+ export function toolResultText(result) {
27
+ return result.content.map((c) => c.text).join('\n');
28
+ }
29
+ /** Parse the runtime's `{ok, code, …}` payload; a non-JSON text is an opaque success. */
30
+ export function parseOutcome(result) {
31
+ try {
32
+ const parsed = JSON.parse(toolResultText(result));
33
+ if (parsed && typeof parsed === 'object') {
34
+ return {
35
+ ok: parsed.ok !== false && !result.isError,
36
+ ...(typeof parsed.code === 'string' ? { code: parsed.code } : {}),
37
+ ...(typeof parsed.message === 'string' ? { message: parsed.message } : {}),
38
+ ...(typeof parsed.error === 'string' ? { error: parsed.error } : {})
39
+ };
40
+ }
41
+ }
42
+ catch {
43
+ // Not JSON — fall through.
44
+ }
45
+ return { ok: !result.isError };
46
+ }
47
+ function isLegacy(response) {
48
+ return typeof response.turnId !== 'string' || response.turnId.length === 0;
49
+ }
50
+ // ============================================================================
51
+ // runTurn
52
+ // ============================================================================
53
+ /**
54
+ * Drive one turn to its end. Rejects only when a request fails (network,
55
+ * HTTP error) — the caller shows that as an error bubble; every tool-level
56
+ * failure is a result the model reads.
57
+ */
58
+ export async function runTurn(request, deps) {
59
+ const emit = deps.onEvent ?? (() => undefined);
60
+ const preview = deps.preview ?? (() => null);
61
+ const maxRounds = deps.maxRounds ?? 32;
62
+ let response = await deps.send(request);
63
+ if (isLegacy(response)) {
64
+ return { kind: 'legacy', content: response.content ?? '' };
65
+ }
66
+ const turnId = response.turnId;
67
+ let rounds = 0;
68
+ let failed = 0;
69
+ let rejected = 0;
70
+ while (!response.done) {
71
+ if (!response.toolCalls || response.toolCalls.length === 0) {
72
+ // Not a reply and nothing to run: a protocol error, named as one rather
73
+ // than rendered as an empty answer.
74
+ return {
75
+ kind: 'aborted',
76
+ reason: 'The server continued the turn without any tool calls to run.',
77
+ rounds,
78
+ turnId
79
+ };
80
+ }
81
+ rounds++;
82
+ if (rounds > maxRounds) {
83
+ return {
84
+ kind: 'aborted',
85
+ reason: `The assistant made ${rounds} rounds of tool calls without finishing; stopped.`,
86
+ rounds: rounds - 1,
87
+ turnId
88
+ };
89
+ }
90
+ if (typeof response.content === 'string' && response.content.trim() !== '') {
91
+ emit({ type: 'note', content: response.content.trim(), round: rounds });
92
+ }
93
+ const results = [];
94
+ // Sequential on purpose: the gate can hold one decision at a time, and
95
+ // a batch's outcome may change what the next call finds.
96
+ for (const call of response.toolCalls) {
97
+ const seen = preview(call.name, call.args);
98
+ emit({ type: seen?.asks ? 'awaiting-approval' : 'reading', call, preview: seen });
99
+ const result = await deps.runTool(call.name, call.args);
100
+ const outcome = parseOutcome(result);
101
+ if (outcome.ok) {
102
+ emit({ type: 'applied', call, preview: seen, outcome });
103
+ }
104
+ else if (outcome.code === 'REJECTED') {
105
+ rejected++;
106
+ emit({ type: 'rejected', call, preview: seen, outcome });
107
+ }
108
+ else {
109
+ failed++;
110
+ emit({ type: 'failed', call, preview: seen, outcome });
111
+ }
112
+ results.push({
113
+ toolCallId: call.id,
114
+ content: toolResultText(result),
115
+ ...(result.isError ? { isError: true } : {})
116
+ });
117
+ }
118
+ emit({ type: 'round-complete', round: rounds, results });
119
+ response = await deps.sendToolResults(turnId, { results });
120
+ }
121
+ const content = response.content ?? '';
122
+ emit({ type: 'final', content, rounds, failed, rejected });
123
+ return { kind: 'final', content, rounds, turnId, failed, rejected };
124
+ }