@omnidim-ai/mcp-server 0.14.0 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/procedures.ts CHANGED
@@ -13,6 +13,8 @@ import {
13
13
  ReadResourceRequestSchema,
14
14
  } from "@modelcontextprotocol/sdk/types.js";
15
15
 
16
+ import { WORKFLOW_CANVAS_HTML, WORKFLOW_CANVAS_URI } from "./workflow-canvas.js";
17
+
16
18
  interface PromptArg { name: string; description: string; required?: boolean; }
17
19
  interface PromptDef {
18
20
  name: string;
@@ -630,6 +632,13 @@ const RESOURCES: ResourceDef[] = [
630
632
  mimeType: "text/markdown",
631
633
  text: WORKFLOWS_GUIDE,
632
634
  },
635
+ {
636
+ uri: WORKFLOW_CANVAS_URI,
637
+ name: "Workflow canvas",
638
+ description: "Interactive view of a workflow draft, shown by clients that support MCP Apps.",
639
+ mimeType: "text/html;profile=mcp-app",
640
+ text: WORKFLOW_CANVAS_HTML,
641
+ },
633
642
  ];
634
643
 
635
644
  const PROMPTS: PromptDef[] = [
@@ -854,6 +863,9 @@ export function getResourceText(uri: string): string | null {
854
863
  }
855
864
  export const PROMPT_NAMES = PROMPTS.map((p) => p.name);
856
865
  export const RESOURCE_URIS = RESOURCES.map((r) => r.uri);
866
+ export function listResources(): Omit<ResourceDef, "text">[] {
867
+ return RESOURCES.map(({ uri, name, description, mimeType }) => ({ uri, name, description, mimeType }));
868
+ }
857
869
 
858
870
  export function registerProcedures(server: Server): void {
859
871
  server.setRequestHandler(ListPromptsRequestSchema, async () => ({
@@ -869,7 +881,7 @@ export function registerProcedures(server: Server): void {
869
881
  };
870
882
  });
871
883
  server.setRequestHandler(ListResourcesRequestSchema, async () => ({
872
- resources: RESOURCES.map(({ uri, name, description, mimeType }) => ({ uri, name, description, mimeType })),
884
+ resources: listResources(),
873
885
  }));
874
886
  server.setRequestHandler(ReadResourceRequestSchema, async (request) => {
875
887
  const r = RESOURCES.find((x) => x.uri === request.params.uri);
package/src/setup.ts CHANGED
@@ -16,7 +16,7 @@ import {
16
16
  type SetupKeyOutcome,
17
17
  } from "./telemetry.js";
18
18
 
19
- const PROD_API = "https://backend.omnidim.io/api/v1";
19
+ const PROD_API = "https://omnidim.io/api/v1";
20
20
 
21
21
  const dim = (s: string): string => `\x1b[2m${s}\x1b[0m`;
22
22
  const italicDim = (s: string): string => `\x1b[2;3m${s}\x1b[0m`;
@@ -71,6 +71,7 @@ const TOOL_TITLES: Record<string, string> = {
71
71
  listWorkflows: "List workflows",
72
72
  createWorkflow: "Create workflow",
73
73
  getWorkflow: "Get workflow",
74
+ showWorkflow: "Show workflow canvas",
74
75
  editWorkflow: "Edit workflow draft",
75
76
  deleteWorkflow: "Delete workflow",
76
77
  validateWorkflow: "Validate workflow",
@@ -0,0 +1,586 @@
1
+ // MCP Apps view (ui:// resource) that shows and edits a workflow draft inside the chat.
2
+ // The page holds no API key: every read and edit goes back through this
3
+ // server's own tools via the host, so it runs on the user's existing login.
4
+
5
+ export const WORKFLOW_CANVAS_URI = "ui://omnidim/workflow-canvas";
6
+
7
+ // Only showWorkflow draws the canvas. Linking get/create/edit posted one canvas per build step.
8
+ export function toolMeta(name: string): { ui: { resourceUri: string } } | undefined {
9
+ return name === "showWorkflow" ? { ui: { resourceUri: WORKFLOW_CANVAS_URI } } : undefined;
10
+ }
11
+
12
+ const SHOW_WORKFLOW_DESCRIPTION = `Show a workflow to the user as an interactive canvas in the chat, where they can move, rename, edit and delete nodes. Call it when the user asks to see a workflow, and once after you finish building or changing one. Do not call it before every edit: use \`getWorkflow\` to read the draft.
13
+
14
+ (Tags: Workflows)`;
15
+
16
+ interface ToolDef {
17
+ name: string;
18
+ description: string;
19
+ inputSchema: any;
20
+ executionParameters: Array<{ name: string; in: string }>;
21
+ }
22
+
23
+ // showWorkflow reads the same endpoint as getWorkflow; it exists so the canvas has one trigger.
24
+ export function addShowWorkflow<T extends ToolDef>(map: Map<string, T>): void {
25
+ const get = map.get("getWorkflow");
26
+ if (!get) return;
27
+ map.set("showWorkflow", {
28
+ ...get,
29
+ name: "showWorkflow",
30
+ description: SHOW_WORKFLOW_DESCRIPTION,
31
+ inputSchema: {
32
+ type: "object",
33
+ properties: { workflow_id: get.inputSchema.properties.workflow_id },
34
+ required: ["workflow_id"],
35
+ },
36
+ executionParameters: get.executionParameters.filter((p) => p.name === "workflow_id"),
37
+ });
38
+ }
39
+
40
+ interface ToolResult { isError?: boolean; content?: Array<{ type: string; text?: string }>; }
41
+
42
+ // The three helpers below are embedded into the page with toString(), so they must not
43
+ // reference anything outside themselves.
44
+ export function readWorkflow(result: ToolResult): { workflow: any; workflowId: number | null; issues: any[]; error: string | null } {
45
+ const text = (result.content || []).filter((c) => c.type === "text").map((c) => c.text || "").join("\n");
46
+ if (result.isError) return { workflow: null, workflowId: null, issues: [], error: text };
47
+ const body = text.startsWith("API Response") ? text.slice(text.indexOf("\n") + 1) : text;
48
+ let data: any;
49
+ try { data = JSON.parse(body); } catch { return { workflow: null, workflowId: null, issues: [], error: text }; }
50
+ const wf = data && (data.workflow || data);
51
+ const id = wf && (wf.id ?? wf.workflow_id);
52
+ const workflowId = typeof id === "number" ? id : null;
53
+ const src = data && data.issues ? data.issues : data;
54
+ const issues = src && Array.isArray(src.errors) ? src.errors : [];
55
+ return { workflow: wf && wf.draft ? wf : null, workflowId, issues, error: null };
56
+ }
57
+
58
+ // The hosted server takes edit fields flat; the npm server takes them under requestBody.
59
+ // Each drops the shape it does not use, and the API ignores the extra key.
60
+ export function editArgs(workflowId: number, revision: string, ops: any[]): Record<string, unknown> {
61
+ return { workflow_id: workflowId, revision, ops, requestBody: { revision, ops } };
62
+ }
63
+
64
+ export function errorText(text: string): string {
65
+ const start = text.indexOf("{");
66
+ if (start >= 0) {
67
+ try {
68
+ const data = JSON.parse(text.slice(start));
69
+ const msg = data.error_description || data.message || data.detail || data.error;
70
+ if (typeof msg === "string" && msg) return msg;
71
+ } catch { /* not JSON: fall through to the plain text */ }
72
+ }
73
+ return text.length > 160 ? text.slice(0, 157) + "..." : text;
74
+ }
75
+
76
+ // Icon shapes copied from lucide (the set the dashboard's workflow editor uses).
77
+ const ICONS: Record<string, string> = {
78
+ zap: '<path d="M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z"/>',
79
+ phone: '<path d="M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z"/>',
80
+ clock: '<circle cx="12" cy="12" r="10"/><polyline points="12 6 12 12 16 14"/>',
81
+ branch: '<line x1="6" x2="6" y1="3" y2="15"/><circle cx="18" cy="6" r="3"/><circle cx="6" cy="18" r="3"/><path d="M18 9a9 9 0 0 1-9 9"/>',
82
+ mail: '<rect width="20" height="16" x="2" y="4" rx="2"/><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"/>',
83
+ globe: '<circle cx="12" cy="12" r="10"/><path d="M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20"/><path d="M2 12h20"/>',
84
+ braces: '<path d="M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1"/><path d="M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1"/>',
85
+ workflow: '<rect width="8" height="8" x="3" y="3" rx="2"/><path d="M7 11v4a2 2 0 0 0 2 2h4"/><rect width="8" height="8" x="13" y="13" rx="2"/>',
86
+ message: '<path d="M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z"/>',
87
+ sparkles: '<path d="M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z"/>',
88
+ user: '<path d="M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2"/><circle cx="9" cy="7" r="4"/><line x1="19" x2="19" y1="8" y2="14"/><line x1="22" x2="16" y1="11" y2="11"/>',
89
+ note: '<path d="M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z"/><path d="M15 3v4a2 2 0 0 0 2 2h4"/>',
90
+ };
91
+
92
+ export const WORKFLOW_CANVAS_HTML = `<!doctype html>
93
+ <html lang="en">
94
+ <head>
95
+ <meta charset="utf-8">
96
+ <meta name="viewport" content="width=device-width, initial-scale=1">
97
+ <title>Workflow canvas</title>
98
+ <style>
99
+ /* Colors follow the dashboard's workflow editor tokens. */
100
+ :root {
101
+ --bg: hsl(210 30% 96%); --card: hsl(210 30% 99%); --fg: hsl(222 47% 9%); --muted: hsl(215 19% 36%);
102
+ --line: hsl(214 25% 87%); --edge: #94a3b8; --dot: hsl(214 25% 84%); --primary: hsl(172.5 66% 40.4%);
103
+ --primary-soft: hsl(172.5 66% 40.4% / .12); --sel: #fbbf24; --err: #dc2626; --err-soft: hsl(0 84% 60% / .08);
104
+ color-scheme: light;
105
+ }
106
+ :root[data-theme="dark"] {
107
+ --bg: hsl(0 0% 3.9%); --card: hsl(0 0% 7%); --fg: hsl(0 0% 98%); --muted: hsl(0 0% 64%);
108
+ --line: hsl(0 0% 16%); --edge: #64748b; --dot: hsl(0 0% 14%); --primary: hsl(180 100% 35.1%);
109
+ --primary-soft: hsl(180 100% 35.1% / .16); --sel: #fbbf24; --err: #f87171; --err-soft: hsl(0 91% 71% / .1);
110
+ color-scheme: dark;
111
+ }
112
+ * { box-sizing: border-box; }
113
+ body { margin: 0; font: 13px/1.4 ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; color: var(--fg); background: var(--bg); }
114
+ header { display: flex; align-items: center; gap: 8px; padding: 10px 12px; border-bottom: 1px solid var(--line); flex-wrap: wrap; background: var(--card); }
115
+ header h1 { font-size: 14px; margin: 0; font-weight: 600; flex: 1 1 200px; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
116
+ .pill { font-size: 11px; padding: 2px 8px; border-radius: 999px; border: 1px solid var(--line); color: var(--muted); white-space: nowrap; }
117
+ .pill.bad { color: var(--err); border-color: var(--err); }
118
+ button, input, textarea { font: inherit; font-size: 12px; color: var(--fg); }
119
+ button { background: var(--card); border: 1px solid var(--line); border-radius: 6px; padding: 4px 10px; cursor: pointer; }
120
+ button:hover { border-color: var(--edge); }
121
+ button:disabled { opacity: .6; cursor: progress; }
122
+ button.danger { color: var(--err); }
123
+ button:focus-visible, input:focus-visible, textarea:focus-visible { outline: 2px solid var(--primary); outline-offset: 1px; }
124
+ #stage { overflow: auto; background-color: var(--bg); background-image: radial-gradient(var(--dot) 1px, transparent 1px); background-size: 16px 16px; }
125
+ :root[data-mode="fullscreen"] #stage { height: calc(100vh - 52px - var(--panel-h, 0px)); }
126
+ svg { display: block; touch-action: none; }
127
+ .card { fill: var(--card); stroke: var(--line); stroke-width: 1; }
128
+ .node:hover .card { stroke: var(--primary); }
129
+ .node.selected .card { stroke: var(--sel); stroke-width: 2; }
130
+ .node.invalid .card { stroke: var(--err); stroke-width: 1.5; }
131
+ .node { cursor: grab; }
132
+ .node.dragging { cursor: grabbing; }
133
+ .icon-box { fill: var(--primary-soft); }
134
+ .icon { fill: none; stroke: var(--primary); stroke-width: 2; stroke-linecap: round; stroke-linejoin: round; }
135
+ .label { font-size: 13px; font-weight: 600; fill: var(--fg); }
136
+ .sub { font-size: 11.5px; fill: var(--muted); }
137
+ .handle { fill: var(--edge); stroke: var(--card); stroke-width: 2; }
138
+ .edge { fill: none; stroke: var(--edge); stroke-width: 2; }
139
+ .chip rect { fill: var(--card); stroke: var(--line); }
140
+ .chip text { font-size: 10px; font-weight: 700; letter-spacing: .04em; fill: var(--muted); text-transform: uppercase; }
141
+ .skel { fill: var(--card); stroke: var(--line); }
142
+ @media (prefers-reduced-motion: no-preference) { .skel { animation: pulse 1.2s ease-in-out infinite; } }
143
+ @keyframes pulse { 50% { opacity: .5; } }
144
+ #panel { padding: 10px 12px; border-top: 1px solid var(--line); background: var(--card); display: grid; gap: 8px; }
145
+ #panel[hidden] { display: none; }
146
+ .row { display: flex; gap: 8px; align-items: center; flex-wrap: wrap; }
147
+ .muted { color: var(--muted); }
148
+ #n-label { flex: 1 1 180px; min-width: 0; padding: 4px 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); }
149
+ #n-config { width: 100%; min-height: 120px; max-height: 240px; padding: 8px; border: 1px solid var(--line); border-radius: 6px; background: var(--bg); font: 11px/1.45 ui-monospace, SFMono-Regular, Menlo, monospace; resize: vertical; }
150
+ #n-errors { color: var(--err); background: var(--err-soft); border-radius: 6px; padding: 6px 8px; font-size: 12px; }
151
+ #n-errors[hidden] { display: none; }
152
+ #notice { font-size: 12px; color: var(--err); padding: 6px 12px; border-top: 1px solid var(--line); background: var(--err-soft); }
153
+ #notice.info { color: var(--muted); background: var(--card); }
154
+ #notice[hidden] { display: none; }
155
+ </style>
156
+ </head>
157
+ <body>
158
+ <header>
159
+ <h1 id="title">Loading workflow</h1>
160
+ <span class="pill" id="state" hidden></span>
161
+ <span class="pill bad" id="issues" hidden></span>
162
+ <button id="refresh" type="button">Reload</button>
163
+ <button id="full" type="button">Full screen</button>
164
+ <button id="open" type="button">Open in dashboard</button>
165
+ </header>
166
+ <div id="stage"><svg id="canvas" role="img" aria-label="Workflow graph"></svg></div>
167
+ <div id="notice" role="status" hidden></div>
168
+ <div id="panel" hidden>
169
+ <div class="row">
170
+ <input id="n-label" aria-label="Node name">
171
+ <span class="pill" id="n-type"></span>
172
+ <span class="muted" id="n-id"></span>
173
+ </div>
174
+ <div id="n-errors" hidden></div>
175
+ <textarea id="n-config" aria-label="Node settings (JSON)" spellcheck="false"></textarea>
176
+ <div class="row">
177
+ <button id="save" type="button">Save changes</button>
178
+ <button id="delete" type="button" class="danger">Delete node</button>
179
+ <button id="ask" type="button">Ask Claude about this node</button>
180
+ </div>
181
+ </div>
182
+ <script>
183
+ const readWorkflow = ${readWorkflow.toString()};
184
+ const editArgs = ${editArgs.toString()};
185
+ const errorText = ${errorText.toString()};
186
+ const ICONS = ${JSON.stringify(ICONS)};
187
+ // Card size and handles match the dashboard editor: inputs on top, outputs at the bottom.
188
+ const NODE_W = 220, NODE_H = 62, PAD = 40, MIN_SCALE = 0.7, FALLBACK_MS = 800;
189
+ const SVG_NS = "http://www.w3.org/2000/svg";
190
+ const $ = (id) => document.getElementById(id);
191
+ const state = { wf: null, id: null, issues: [], selected: null, busy: false, dirty: false, dragging: false, redraw: false, form: null };
192
+
193
+ // JSON-RPC over postMessage to the host (MCP Apps protocol 2026-01-26).
194
+ let nextId = 1;
195
+ const pending = new Map();
196
+ function send(msg) { window.parent.postMessage(Object.assign({ jsonrpc: "2.0" }, msg), "*"); }
197
+ function request(method, params) {
198
+ const id = nextId++;
199
+ send({ id, method, params });
200
+ return new Promise((resolve, reject) => pending.set(id, { resolve, reject }));
201
+ }
202
+ function notify(method, params) { send({ method, params }); }
203
+
204
+ window.addEventListener("message", (event) => {
205
+ if (event.source !== window.parent) return;
206
+ const msg = event.data;
207
+ if (!msg || msg.jsonrpc !== "2.0") return;
208
+ if (msg.id !== undefined && pending.has(msg.id) && !msg.method) {
209
+ const p = pending.get(msg.id); pending.delete(msg.id);
210
+ msg.error ? p.reject(new Error(msg.error.message || "Request failed")) : p.resolve(msg.result);
211
+ return;
212
+ }
213
+ if (msg.method === "ui/notifications/tool-input") {
214
+ const id = msg.params && msg.params.arguments && msg.params.arguments.workflow_id;
215
+ if (typeof id === "number") state.id = id;
216
+ // Some hosts hand over the result late; load it ourselves instead of sitting empty.
217
+ setTimeout(() => { if (!state.wf) refresh(); }, FALLBACK_MS);
218
+ } else if (msg.method === "ui/notifications/tool-result") {
219
+ applyResult(msg.params);
220
+ } else if (msg.method === "ui/notifications/host-context-changed") {
221
+ applyContext(msg.params);
222
+ } else if (msg.method === "ui/resource-teardown" && msg.id !== undefined) {
223
+ send({ id: msg.id, result: {} });
224
+ } else if (msg.id !== undefined && msg.method) {
225
+ send({ id: msg.id, error: { code: -32601, message: "Method not found" } });
226
+ }
227
+ });
228
+
229
+ function applyContext(ctx) {
230
+ if (!ctx) return;
231
+ if (ctx.theme) document.documentElement.dataset.theme = ctx.theme;
232
+ if (ctx.displayMode) document.documentElement.dataset.mode = ctx.displayMode;
233
+ }
234
+
235
+ // The bar under the canvas stays hidden unless something needs the user's attention.
236
+ function notice(text, kind) {
237
+ const el = $("notice");
238
+ el.hidden = !text;
239
+ el.textContent = text || "";
240
+ el.className = kind === "info" ? "info" : "";
241
+ }
242
+
243
+ function callTool(name, args) { return request("tools/call", { name, arguments: args }); }
244
+
245
+ async function refresh() {
246
+ if (state.id == null || state.busy) return;
247
+ state.busy = true;
248
+ try {
249
+ const r = readWorkflow(await callTool("getWorkflow", { workflow_id: state.id }));
250
+ if (r.error) notice("Could not load the workflow: " + errorText(r.error));
251
+ else if (r.workflow) show(r.workflow, null);
252
+ } catch (e) { notice("Could not load the workflow: " + e.message); }
253
+ finally { state.busy = false; }
254
+ }
255
+
256
+ function applyResult(result) {
257
+ const r = readWorkflow(result || {});
258
+ if (r.error) { notice(errorText(r.error)); return; }
259
+ if (r.workflowId != null) state.id = r.workflowId;
260
+ if (!r.workflow) { refresh(); return; }
261
+ show(r.workflow, r.issues);
262
+ }
263
+
264
+ function show(wf, issues) {
265
+ state.wf = wf;
266
+ if (issues) state.issues = issues;
267
+ notice("");
268
+ render();
269
+ validate();
270
+ }
271
+
272
+ // getWorkflow carries no problems, so ask validateWorkflow which nodes to mark, like the dashboard does.
273
+ async function validate() {
274
+ try {
275
+ const r = readWorkflow(await callTool("validateWorkflow", { workflow_id: state.id }));
276
+ if (!r.error) { state.issues = r.issues; render(); }
277
+ } catch { /* the marks are a hint; the canvas works without them */ }
278
+ }
279
+
280
+ function iconFor(type) {
281
+ if (type === "trigger" || type.endsWith("_trigger") || type.endsWith("_inbound")) return "zap";
282
+ if (type === "voice_ai" || type.includes("dialer")) return "phone";
283
+ if (type === "wait" || type === "wait_for_time" || type === "time_condition") return "clock";
284
+ if (type === "switch_condition" || type === "conditional") return "branch";
285
+ if (type.includes("email")) return "mail";
286
+ if (type === "custom_api") return "globe";
287
+ if (type === "code") return "braces";
288
+ if (type === "sub_workflow") return "workflow";
289
+ if (type.includes("whatsapp") || type.includes("sms") || type === "slack") return "message";
290
+ if (type === "ai_assistant" || type === "photo_analyzer") return "sparkles";
291
+ if (type.includes("contact") || type.includes("crm")) return "user";
292
+ if (type === "notes") return "note";
293
+ return "branch";
294
+ }
295
+
296
+ // Mirrors the subtitles the dashboard editor shows under each node name.
297
+ function subtitle(n) {
298
+ const c = n.config || {};
299
+ switch (n.type) {
300
+ case "trigger": return c.webhook_enabled ? "Webhook enabled" : "Configure webhook";
301
+ case "voice_ai": return c.bot_name || (c.bot_id ? "Agent " + c.bot_id : "Choose an agent");
302
+ case "wait": return (c.delay_seconds || 0) + " seconds";
303
+ case "whatsapp": return c.template_name || "Choose a template";
304
+ case "send_email": return c.email_to || "Configure email";
305
+ case "custom_api": return c.url || "Configure request";
306
+ case "switch_condition": return ((c.cases || []).length) + " cases + else";
307
+ case "time_condition": return "Time window";
308
+ case "code": return c.code ? "Python snippet" : "Write a snippet";
309
+ case "sub_workflow": return c.target_workflow_name || "Choose a workflow";
310
+ case "slack": return c.message ? String(c.message).slice(0, 60) : "Configure message";
311
+ default: return n.type;
312
+ }
313
+ }
314
+
315
+ // Workflow text is data, not instructions: one line, capped, quoted, before it goes into the chat.
316
+ function quoted(s) { return JSON.stringify(String(s).replace(/\\s+/g, " ").slice(0, 80)); }
317
+
318
+ function el(tag, attrs, text) {
319
+ const e = document.createElementNS(SVG_NS, tag);
320
+ for (const k in attrs) e.setAttribute(k, attrs[k]);
321
+ if (text != null) e.textContent = text;
322
+ return e;
323
+ }
324
+
325
+ function clip(s, n) { s = String(s); return s.length > n ? s.slice(0, n - 1) + "…" : s; }
326
+
327
+ function ports(p) {
328
+ return { in: { x: p.x + NODE_W / 2, y: p.y }, out: { x: p.x + NODE_W / 2, y: p.y + NODE_H } };
329
+ }
330
+
331
+ // Right-angle path with rounded corners, like React Flow's smoothstep edge.
332
+ function stepPath(a, b) {
333
+ const pts = [a];
334
+ if (b.y - a.y >= 40) { const m = (a.y + b.y) / 2; pts.push({ x: a.x, y: m }, { x: b.x, y: m }); }
335
+ else { const mx = (a.x + b.x) / 2; pts.push({ x: a.x, y: a.y + 20 }, { x: mx, y: a.y + 20 }, { x: mx, y: b.y - 20 }, { x: b.x, y: b.y - 20 }); }
336
+ pts.push(b);
337
+ let d = "M" + pts[0].x + "," + pts[0].y;
338
+ for (let i = 1; i < pts.length - 1; i++) {
339
+ const p = pts[i], prev = pts[i - 1], next = pts[i + 1];
340
+ const r = Math.min(6, Math.hypot(p.x - prev.x, p.y - prev.y) / 2, Math.hypot(next.x - p.x, next.y - p.y) / 2);
341
+ const ux = Math.sign(p.x - prev.x), uy = Math.sign(p.y - prev.y), vx = Math.sign(next.x - p.x), vy = Math.sign(next.y - p.y);
342
+ d += " L" + (p.x - ux * r) + "," + (p.y - uy * r) + " Q" + p.x + "," + p.y + " " + (p.x + vx * r) + "," + (p.y + vy * r);
343
+ }
344
+ d += " L" + b.x + "," + b.y;
345
+ const mid = pts[Math.floor(pts.length / 2)], mid2 = pts[Math.floor(pts.length / 2) - 1];
346
+ return { d, label: { x: (mid.x + mid2.x) / 2, y: (mid.y + mid2.y) / 2 } };
347
+ }
348
+
349
+ function drawEdges(layer) {
350
+ layer.replaceChildren();
351
+ const pos = {};
352
+ for (const n of state.wf.draft.nodes) pos[n.id] = n.position;
353
+ for (const e of state.wf.draft.edges) {
354
+ const a = pos[e.from], b = pos[e.to];
355
+ if (!a || !b) continue;
356
+ const s = stepPath(ports(a).out, ports(b).in);
357
+ layer.append(el("path", { class: "edge", d: s.d, "marker-end": "url(#arrow)" }));
358
+ if (e.handle && e.handle !== "default") {
359
+ const text = clip(e.handle, 18), w = text.length * 6.4 + 14;
360
+ const chip = el("g", { class: "chip", transform: "translate(" + (s.label.x - w / 2) + "," + (s.label.y - 9) + ")" });
361
+ chip.append(el("rect", { width: w, height: 18, rx: 5 }), el("text", { x: 7, y: 12.5 }, text));
362
+ layer.append(chip);
363
+ }
364
+ }
365
+ }
366
+
367
+ function errorsFor(id) { return state.issues.filter((i) => i.node === id); }
368
+
369
+ function render() {
370
+ if (!state.wf) return;
371
+ // Redrawing replaces the node under the pointer and kills the drag, so wait for the drop.
372
+ if (state.dragging) { state.redraw = true; return; }
373
+ const wf = state.wf, draft = wf.draft, svg = $("canvas");
374
+ $("title").textContent = wf.name || "Workflow " + wf.id;
375
+ $("state").hidden = false;
376
+ $("state").textContent = (wf.status || "draft") + " · " + draft.nodes.length + " nodes";
377
+ $("issues").hidden = !state.issues.length;
378
+ $("issues").textContent = state.issues.length + (state.issues.length === 1 ? " problem" : " problems");
379
+ draft.nodes.forEach((n, i) => { if (!n.position) n.position = { x: i * 260, y: 0 }; });
380
+ const xs = draft.nodes.map((n) => n.position.x), ys = draft.nodes.map((n) => n.position.y);
381
+ const minX = Math.min(...xs, 0) - PAD, minY = Math.min(...ys, 0) - PAD;
382
+ const w = Math.max(...xs, 0) + NODE_W + PAD - minX, h = Math.max(...ys, 0) + NODE_H + PAD - minY;
383
+ const avail = $("stage").clientWidth || 600;
384
+ const scale = Math.max(MIN_SCALE, Math.min(1, avail / w));
385
+ svg.setAttribute("viewBox", minX + " " + minY + " " + w + " " + h);
386
+ svg.setAttribute("width", Math.round(w * scale));
387
+ svg.setAttribute("height", Math.round(h * scale));
388
+ svg.replaceChildren();
389
+ const defs = el("defs", {});
390
+ const marker = el("marker", { id: "arrow", viewBox: "0 0 10 10", refX: "8", refY: "5", markerWidth: "6", markerHeight: "6", orient: "auto-start-reverse" });
391
+ marker.append(el("path", { d: "M0,0 L10,5 L0,10 z", fill: "var(--edge)" }));
392
+ defs.append(marker);
393
+ const edges = el("g", {});
394
+ svg.append(defs, edges);
395
+ drawEdges(edges);
396
+
397
+ for (const n of draft.nodes) {
398
+ const bad = errorsFor(n.id).length > 0;
399
+ const cls = "node" + (state.selected === n.id ? " selected" : "") + (bad ? " invalid" : "");
400
+ const g = el("g", { class: cls, transform: "translate(" + n.position.x + "," + n.position.y + ")", tabindex: "0", role: "button", "aria-label": (n.label || n.id) + ", " + n.type + (bad ? ", has problems" : "") });
401
+ g.append(el("rect", { class: "card", width: NODE_W, height: NODE_H, rx: 8 }));
402
+ g.append(el("rect", { class: "icon-box", x: 10, y: 10, width: 24, height: 24, rx: 6 }));
403
+ const icon = el("g", { class: "icon", transform: "translate(15,15) scale(0.5833)" });
404
+ icon.innerHTML = ICONS[iconFor(n.type)];
405
+ g.append(icon);
406
+ g.append(el("text", { class: "label", x: 42, y: 26.5 }, clip(n.label || n.id, 23)));
407
+ g.append(el("text", { class: "sub", x: 12, y: NODE_H - 12 }, clip(subtitle(n), 31)));
408
+ const pt = ports({ x: 0, y: 0 });
409
+ if (!n.type.endsWith("trigger") && !n.type.endsWith("_inbound")) g.append(el("circle", { class: "handle", cx: pt.in.x, cy: pt.in.y, r: 4 }));
410
+ g.append(el("circle", { class: "handle", cx: pt.out.x, cy: pt.out.y, r: 4 }));
411
+ g.addEventListener("pointerdown", (ev) => startDrag(ev, n, g, edges));
412
+ g.addEventListener("keydown", (ev) => { if (ev.key === "Enter" || ev.key === " ") { ev.preventDefault(); select(n.id); } });
413
+ svg.append(g);
414
+ }
415
+ showPanel();
416
+ }
417
+
418
+ function placeholder() {
419
+ const svg = $("canvas");
420
+ svg.setAttribute("viewBox", "0 0 600 240"); svg.setAttribute("width", 600); svg.setAttribute("height", 240);
421
+ svg.replaceChildren();
422
+ [[40, 90], [320, 30], [320, 150]].forEach(([x, y]) => svg.append(el("rect", { class: "skel", x, y, width: 220, height: 62, rx: 8 })));
423
+ }
424
+
425
+ function toSvg(ev) {
426
+ const svg = $("canvas"), pt = svg.createSVGPoint();
427
+ pt.x = ev.clientX; pt.y = ev.clientY;
428
+ return pt.matrixTransform(svg.getScreenCTM().inverse());
429
+ }
430
+
431
+ // The drag is tracked on the whole document, not the node: a release outside the chat's
432
+ // frame never reaches the frame, so leaving the frame (or a move with no button held) drops the node there.
433
+ function startDrag(ev, node, g, edges) {
434
+ // One drag at a time, primary pointer only: a second finger must not start a drag nobody saves.
435
+ if (state.busy || state.dragging || ev.button !== 0 || !ev.isPrimary) return;
436
+ const start = toSvg(ev), origin = { x: node.position.x, y: node.position.y };
437
+ let moved = false;
438
+ state.dragging = true;
439
+ const move = (e) => {
440
+ if (e.buttons === 0) return up();
441
+ const cur = toSvg(e), dx = cur.x - start.x, dy = cur.y - start.y;
442
+ if (!moved && Math.hypot(dx, dy) < 4) return;
443
+ moved = true; g.classList.add("dragging");
444
+ node.position = { x: Math.round(origin.x + dx), y: Math.round(origin.y + dy) };
445
+ g.setAttribute("transform", "translate(" + node.position.x + "," + node.position.y + ")");
446
+ drawEdges(edges);
447
+ };
448
+ const up = () => {
449
+ document.removeEventListener("pointermove", move);
450
+ document.removeEventListener("pointerup", up);
451
+ document.documentElement.removeEventListener("pointerleave", up);
452
+ window.removeEventListener("blur", up);
453
+ g.classList.remove("dragging");
454
+ if (!state.dragging) return;
455
+ state.dragging = false;
456
+ if (state.redraw) { state.redraw = false; render(); }
457
+ if (!moved) { select(node.id); return; }
458
+ if (node.position.x === origin.x && node.position.y === origin.y) return;
459
+ save([{ op: "move_node", id: node.id, position: node.position }], "moved node " + quoted(node.id), () => { node.position = origin; });
460
+ };
461
+ document.addEventListener("pointermove", move);
462
+ document.addEventListener("pointerup", up);
463
+ document.documentElement.addEventListener("pointerleave", up);
464
+ window.addEventListener("blur", up);
465
+ }
466
+
467
+ // Every edit sends the draft revision, so a stale edit is refused instead of overwriting Claude's.
468
+ async function save(ops, what, rollback, button) {
469
+ if (!state.wf) return false;
470
+ if (state.busy) { if (rollback) rollback(); render(); notice("Still loading the workflow. Try again in a moment."); return false; }
471
+ state.busy = true;
472
+ if (button) { button.disabled = true; button.dataset.text = button.textContent; button.textContent = "Saving…"; }
473
+ let ok = false;
474
+ try {
475
+ const r = readWorkflow(await callTool("editWorkflow", editArgs(state.id, state.wf.draft.revision, ops)) || {});
476
+ if (r.error) throw new Error(errorText(r.error));
477
+ ok = true;
478
+ notify("ui/update-model-context", { content: [{ type: "text", text: "In the workflow canvas the user " + what + " on workflow " + state.id + ". Call getWorkflow for the new revision before your next edit." }] });
479
+ } catch (e) {
480
+ if (rollback) rollback();
481
+ notice("Not saved: " + e.message);
482
+ } finally {
483
+ state.busy = false;
484
+ if (button) { button.disabled = false; button.textContent = button.dataset.text; }
485
+ }
486
+ const failure = ok ? "" : $("notice").textContent;
487
+ await refresh();
488
+ if (!ok) notice(failure);
489
+ return ok;
490
+ }
491
+
492
+ function select(id) {
493
+ state.selected = id;
494
+ state.dirty = false;
495
+ render();
496
+ const n = state.wf.draft.nodes.find((x) => x.id === id);
497
+ if (!n) return;
498
+ notify("ui/update-model-context", { content: [{ type: "text", text: "In the workflow canvas the user selected node " + quoted(id) + " (type " + quoted(n.type) + ") on workflow " + state.id + "." }] });
499
+ }
500
+
501
+ function showPanel() {
502
+ const n = state.selected && state.wf.draft.nodes.find((x) => x.id === state.selected);
503
+ $("panel").hidden = !n;
504
+ if (!n) return;
505
+ if (state.dirty && $("panel").dataset.node === n.id) return;
506
+ $("panel").dataset.node = n.id;
507
+ state.dirty = false;
508
+ // What the form was loaded with: the base for working out what the user changed.
509
+ state.form = { id: n.id, label: n.label || "", config: JSON.parse(JSON.stringify(n.config || {})) };
510
+ $("n-label").value = n.label || "";
511
+ $("n-type").textContent = n.type;
512
+ $("n-id").textContent = "id " + n.id;
513
+ $("n-config").value = n.config ? JSON.stringify(n.config, null, 2) : "{}";
514
+ const errs = errorsFor(n.id);
515
+ $("n-errors").hidden = !errs.length;
516
+ $("n-errors").textContent = errs.map((e) => e.message).join(" ");
517
+ $("delete").textContent = "Delete node";
518
+ document.documentElement.style.setProperty("--panel-h", $("panel").offsetHeight + "px");
519
+ }
520
+
521
+ // Typed but unsaved settings survive the refresh that follows a move or another save.
522
+ for (const id of ["n-label", "n-config"]) $(id).addEventListener("input", () => { state.dirty = true; });
523
+
524
+ // Sends only what the user changed since the form loaded. If Claude changed the same field in the
525
+ // meantime the save is refused, so neither edit silently overwrites the other.
526
+ $("save").addEventListener("click", () => {
527
+ const n = state.wf && state.wf.draft.nodes.find((x) => x.id === state.selected);
528
+ const base = state.form;
529
+ if (!n || !base || base.id !== n.id) return;
530
+ let config;
531
+ try { config = JSON.parse($("n-config").value || "{}"); }
532
+ catch { notice("The settings are not valid JSON. Fix them and save again."); return; }
533
+ if (!config || typeof config !== "object" || Array.isArray(config)) { notice('The settings must be a JSON object, like {"key": "value"}.'); return; }
534
+ const same = (a, b) => JSON.stringify(a) === JSON.stringify(b);
535
+ const now = n.config || {}, op = { op: "update_node", id: n.id }, changed = Object.create(null), clash = [];
536
+ for (const k of Object.keys(config)) if (k !== "__proto__" && !same(config[k], base.config[k])) changed[k] = config[k];
537
+ for (const k of Object.keys(base.config)) if (!(k in config)) changed[k] = null;
538
+ for (const k of Object.keys(changed)) if (!same(now[k], base.config[k])) clash.push(k);
539
+ const label = $("n-label").value.trim();
540
+ if (label && label !== base.label) {
541
+ if ((n.label || "") !== base.label) clash.push("name");
542
+ op.label = label;
543
+ }
544
+ if (clash.length) { notice("Claude changed " + clash.join(", ") + " on this node while you were editing. Select the node again to load its version, then redo your change."); return; }
545
+ if (Object.keys(changed).length) op.config = changed;
546
+ if (!op.label && !op.config) { notice("Nothing changed.", "info"); return; }
547
+ save([op], "edited node " + quoted(n.id), null, $("save")).then((ok) => { if (ok) { state.dirty = false; showPanel(); } });
548
+ });
549
+
550
+ $("delete").addEventListener("click", () => {
551
+ const btn = $("delete"), id = state.selected;
552
+ if (!id) return;
553
+ if (btn.textContent !== "Click again to delete") { btn.textContent = "Click again to delete"; return; }
554
+ save([{ op: "delete_node", id }], "deleted node " + quoted(id), null, btn).then((ok) => { if (ok) { state.selected = null; render(); } });
555
+ });
556
+
557
+ $("refresh").addEventListener("click", refresh);
558
+ $("full").addEventListener("click", async () => {
559
+ const mode = document.documentElement.dataset.mode === "fullscreen" ? "inline" : "fullscreen";
560
+ try { const r = await request("ui/request-display-mode", { mode }); applyContext({ displayMode: r && r.mode }); render(); }
561
+ catch (e) { notice("Full screen is not available here."); }
562
+ });
563
+ $("open").addEventListener("click", () => {
564
+ if (state.id != null) request("ui/open-link", { url: "https://omnidim.io/workflow/" + state.id }).catch(() => {});
565
+ });
566
+ $("ask").addEventListener("click", () => {
567
+ const n = state.wf && state.wf.draft.nodes.find((x) => x.id === state.selected);
568
+ if (!n) return;
569
+ request("ui/message", { role: "user", content: [{ type: "text", text: "In workflow " + state.id + ", explain the node with id " + quoted(n.id) + " (type " + quoted(n.type) + ", named " + quoted(n.label || n.id) + ") and check its settings for problems." }] }).catch(() => notice("Could not send the message to the chat."));
570
+ });
571
+
572
+ new ResizeObserver(() => notify("ui/notifications/size-changed", { width: document.documentElement.scrollWidth, height: document.documentElement.scrollHeight })).observe(document.body);
573
+
574
+ placeholder();
575
+ request("ui/initialize", {
576
+ protocolVersion: "2026-01-26",
577
+ appInfo: { name: "omnidim-workflow-canvas", version: "0.2.0" },
578
+ appCapabilities: { availableDisplayModes: ["inline", "fullscreen"] },
579
+ }).then((r) => {
580
+ applyContext(r && r.hostContext);
581
+ notify("ui/notifications/initialized", {});
582
+ }).catch(() => notice("This chat app could not open the canvas."));
583
+ </script>
584
+ </body>
585
+ </html>
586
+ `;