@addai/flows-mcp 1.0.0-rc.5 → 1.1.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/dist/oauth.js ADDED
@@ -0,0 +1,322 @@
1
+ /**
2
+ * MCP OAuth 2.1 client using loopback PKCE.
3
+ *
4
+ * Flow:
5
+ * 1. Read cached client + tokens from ~/.addai/flows-mcp/.
6
+ * 2. If access token is fresh → return it.
7
+ * 3. If access token expired but refresh token valid → call /token with grant_type=refresh_token.
8
+ * 4. Otherwise → full auth code flow:
9
+ * a. (One-time) Register a client via /register if no client info cached.
10
+ * b. Generate PKCE verifier + challenge.
11
+ * c. Open a one-shot loopback HTTP server on a random port.
12
+ * d. Open the system browser at /authorize.
13
+ * e. User signs in via auth.add.ai, picks workspace, approves.
14
+ * f. Auth server 302s to http://127.0.0.1:<port>/callback?code=…
15
+ * g. Loopback handler captures the code, exchanges it at /token.
16
+ * h. Tokens cached; loopback server shut down.
17
+ *
18
+ * The flow is silent and non-interactive when tokens are cached and valid —
19
+ * only the first run and the refresh-failure path pop a browser.
20
+ */
21
+ import * as http from 'node:http';
22
+ import * as fs from 'node:fs/promises';
23
+ import * as path from 'node:path';
24
+ import * as os from 'node:os';
25
+ import { randomBytes, createHash } from 'node:crypto';
26
+ import { spawn } from 'node:child_process';
27
+ const ISSUER = 'https://auth.add.ai/oauth';
28
+ const DEFAULT_SCOPE = 'flows.read flows.write flows.publish vault.read';
29
+ const CONFIG_DIR = path.join(os.homedir(), '.addai', 'flows-mcp');
30
+ const CLIENT_FILE = path.join(CONFIG_DIR, 'client.json');
31
+ const TOKENS_FILE = path.join(CONFIG_DIR, 'tokens.json');
32
+ const ACCESS_TOKEN_REFRESH_SKEW_MS = 60 * 1000; // refresh 60s before expiry
33
+ const LOOPBACK_TIMEOUT_MS = 5 * 60 * 1000; // 5 min for user to log in
34
+ // ──────────────────────────────────────────────────────────────────────────
35
+ // File-backed store (chmod 600 for both files; dir is 700)
36
+ // ──────────────────────────────────────────────────────────────────────────
37
+ async function ensureConfigDir() {
38
+ await fs.mkdir(CONFIG_DIR, { recursive: true, mode: 0o700 });
39
+ }
40
+ async function readJson(file) {
41
+ try {
42
+ const text = await fs.readFile(file, 'utf-8');
43
+ return JSON.parse(text);
44
+ }
45
+ catch (err) {
46
+ if (err?.code === 'ENOENT')
47
+ return null;
48
+ throw err;
49
+ }
50
+ }
51
+ async function writeJson(file, value) {
52
+ await ensureConfigDir();
53
+ await fs.writeFile(file, JSON.stringify(value, null, 2), { mode: 0o600 });
54
+ }
55
+ // ──────────────────────────────────────────────────────────────────────────
56
+ // PKCE
57
+ // ──────────────────────────────────────────────────────────────────────────
58
+ function base64UrlEncode(buf) {
59
+ return buf.toString('base64')
60
+ .replace(/\+/g, '-')
61
+ .replace(/\//g, '_')
62
+ .replace(/=+$/, '');
63
+ }
64
+ function newCodeVerifier() {
65
+ return base64UrlEncode(randomBytes(48));
66
+ }
67
+ function challengeFromVerifier(verifier) {
68
+ return base64UrlEncode(createHash('sha256').update(verifier).digest());
69
+ }
70
+ function newState() {
71
+ return base64UrlEncode(randomBytes(16));
72
+ }
73
+ function startLoopback(expectedState) {
74
+ return new Promise((resolve, reject) => {
75
+ const server = http.createServer();
76
+ let resolveWait;
77
+ let rejectWait;
78
+ const wait = new Promise((res, rej) => { resolveWait = res; rejectWait = rej; });
79
+ server.on('request', (req, res) => {
80
+ try {
81
+ const url = new URL(req.url || '/', `http://127.0.0.1`);
82
+ if (url.pathname !== '/callback') {
83
+ res.writeHead(404).end('Not Found');
84
+ return;
85
+ }
86
+ const err = url.searchParams.get('error');
87
+ if (err) {
88
+ const desc = url.searchParams.get('error_description') ?? '';
89
+ res.writeHead(400, { 'Content-Type': 'text/html' }).end(`<html><body><h2>Sign-in failed</h2><p>${escapeHtml(err)}: ${escapeHtml(desc)}</p><p>You can close this tab.</p></body></html>`);
90
+ rejectWait(new Error(`Authorisation server returned ${err}: ${desc}`));
91
+ return;
92
+ }
93
+ const code = url.searchParams.get('code');
94
+ const state = url.searchParams.get('state');
95
+ if (!code || !state) {
96
+ res.writeHead(400).end('Missing code or state');
97
+ rejectWait(new Error('Missing code or state in callback'));
98
+ return;
99
+ }
100
+ if (state !== expectedState) {
101
+ res.writeHead(400).end('State mismatch');
102
+ rejectWait(new Error('State mismatch (possible CSRF)'));
103
+ return;
104
+ }
105
+ res.writeHead(200, { 'Content-Type': 'text/html' }).end(`<html><body style="font-family:system-ui;padding:48px;text-align:center">
106
+ <h2>You're signed in to +Ai Flows.</h2>
107
+ <p>You can close this tab and return to your terminal.</p>
108
+ </body></html>`);
109
+ resolveWait({ code, state });
110
+ }
111
+ catch (e) {
112
+ try {
113
+ res.writeHead(500).end('Internal error');
114
+ }
115
+ catch { }
116
+ rejectWait(e);
117
+ }
118
+ });
119
+ server.on('error', (e) => reject(e));
120
+ server.listen(0, '127.0.0.1', () => {
121
+ const address = server.address();
122
+ const port = typeof address === 'object' && address ? address.port : 0;
123
+ const timeout = setTimeout(() => rejectWait(new Error(`Auth flow timed out after ${LOOPBACK_TIMEOUT_MS / 1000}s`)), LOOPBACK_TIMEOUT_MS);
124
+ const close = () => {
125
+ clearTimeout(timeout);
126
+ server.close();
127
+ };
128
+ resolve({ port, wait, close });
129
+ });
130
+ });
131
+ }
132
+ function escapeHtml(s) {
133
+ return s.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
134
+ }
135
+ function openBrowser(url) {
136
+ const platform = process.platform;
137
+ const cmd = platform === 'darwin' ? 'open'
138
+ : platform === 'win32' ? 'cmd'
139
+ : 'xdg-open';
140
+ const args = platform === 'win32' ? ['/c', 'start', '""', url] : [url];
141
+ try {
142
+ const child = spawn(cmd, args, { stdio: 'ignore', detached: true });
143
+ child.unref();
144
+ }
145
+ catch {
146
+ // If spawning the browser fails (CI, no DE), print the URL.
147
+ process.stderr.write(`\nOpen this URL in your browser to sign in:\n ${url}\n\n`);
148
+ }
149
+ }
150
+ // ──────────────────────────────────────────────────────────────────────────
151
+ // Network helpers
152
+ // ──────────────────────────────────────────────────────────────────────────
153
+ async function registerClient(redirectUris) {
154
+ const res = await fetch(`${ISSUER}/register`, {
155
+ method: 'POST',
156
+ headers: { 'Content-Type': 'application/json' },
157
+ body: JSON.stringify({
158
+ redirect_uris: redirectUris,
159
+ client_name: `Claude (${safeHostname()})`,
160
+ scope: DEFAULT_SCOPE,
161
+ }),
162
+ });
163
+ if (!res.ok) {
164
+ const text = await res.text().catch(() => '');
165
+ throw new Error(`OAuth /register failed: ${res.status} ${text.slice(0, 200)}`);
166
+ }
167
+ const body = await res.json();
168
+ return {
169
+ client_id: body.client_id,
170
+ redirect_uris: body.redirect_uris,
171
+ client_name: body.client_name,
172
+ scope: body.scope,
173
+ };
174
+ }
175
+ async function exchangeCode(opts) {
176
+ const res = await fetch(`${ISSUER}/token`, {
177
+ method: 'POST',
178
+ headers: { 'Content-Type': 'application/json' },
179
+ body: JSON.stringify({
180
+ grant_type: 'authorization_code',
181
+ code: opts.code,
182
+ redirect_uri: opts.redirectUri,
183
+ client_id: opts.clientId,
184
+ code_verifier: opts.codeVerifier,
185
+ }),
186
+ });
187
+ if (!res.ok) {
188
+ const text = await res.text().catch(() => '');
189
+ throw new Error(`OAuth /token (code) failed: ${res.status} ${text.slice(0, 200)}`);
190
+ }
191
+ const body = await res.json();
192
+ return { ...body, obtained_at: Date.now() };
193
+ }
194
+ async function refreshTokens(opts) {
195
+ const res = await fetch(`${ISSUER}/token`, {
196
+ method: 'POST',
197
+ headers: { 'Content-Type': 'application/json' },
198
+ body: JSON.stringify({
199
+ grant_type: 'refresh_token',
200
+ refresh_token: opts.refreshToken,
201
+ client_id: opts.clientId,
202
+ }),
203
+ });
204
+ if (!res.ok) {
205
+ const text = await res.text().catch(() => '');
206
+ throw new Error(`OAuth /token (refresh) failed: ${res.status} ${text.slice(0, 200)}`);
207
+ }
208
+ const body = await res.json();
209
+ return { ...body, obtained_at: Date.now() };
210
+ }
211
+ function safeHostname() {
212
+ try {
213
+ return os.hostname();
214
+ }
215
+ catch {
216
+ return 'mcp-client';
217
+ }
218
+ }
219
+ function tokenIsFresh(t) {
220
+ if (!t)
221
+ return false;
222
+ const expiresAt = t.obtained_at + t.expires_in * 1000;
223
+ return Date.now() + ACCESS_TOKEN_REFRESH_SKEW_MS < expiresAt;
224
+ }
225
+ /**
226
+ * Returns a valid access token, performing whichever flow is needed:
227
+ * - cached and fresh → return as-is
228
+ * - cached, expired, refresh valid → refresh, return
229
+ * - cached client only, no tokens / refresh → full browser flow
230
+ * - nothing cached → register + full browser flow
231
+ */
232
+ export async function getOAuthAccessToken(opts = {}) {
233
+ await ensureConfigDir();
234
+ const cachedClient = await readJson(CLIENT_FILE);
235
+ const cachedTokens = await readJson(TOKENS_FILE);
236
+ // Fresh access token — fast path.
237
+ if (cachedClient && tokenIsFresh(cachedTokens)) {
238
+ return {
239
+ accessToken: cachedTokens.access_token,
240
+ expiresAt: cachedTokens.obtained_at + cachedTokens.expires_in * 1000,
241
+ scope: cachedTokens.scope,
242
+ };
243
+ }
244
+ // Try refresh.
245
+ if (cachedClient && cachedTokens?.refresh_token) {
246
+ try {
247
+ const refreshed = await refreshTokens({
248
+ clientId: cachedClient.client_id,
249
+ refreshToken: cachedTokens.refresh_token,
250
+ });
251
+ await writeJson(TOKENS_FILE, refreshed);
252
+ return {
253
+ accessToken: refreshed.access_token,
254
+ expiresAt: refreshed.obtained_at + refreshed.expires_in * 1000,
255
+ scope: refreshed.scope,
256
+ };
257
+ }
258
+ catch (err) {
259
+ // Refresh failed — fall through to full flow.
260
+ process.stderr.write(`[flows-mcp] refresh token rejected: ${err.message}\n`);
261
+ }
262
+ }
263
+ if (opts.interactive === false) {
264
+ throw new Error('OAuth flow required but interactive=false. Set ADDAI_API_KEY in env or run interactively once to authenticate.');
265
+ }
266
+ // Full browser flow.
267
+ const codeVerifier = newCodeVerifier();
268
+ const codeChallenge = challengeFromVerifier(codeVerifier);
269
+ const state = newState();
270
+ // We need the loopback port BEFORE we register so the redirect URI is known.
271
+ const placeholder = await startLoopback(state);
272
+ const redirectUri = `http://127.0.0.1:${placeholder.port}/callback`;
273
+ // Register (or reuse) the OAuth client.
274
+ let client = cachedClient;
275
+ const needsRegister = !client || !client.redirect_uris.some((u) => u.startsWith('http://127.0.0.1:'));
276
+ if (needsRegister) {
277
+ client = await registerClient([redirectUri]);
278
+ await writeJson(CLIENT_FILE, client);
279
+ }
280
+ else if (!client.redirect_uris.includes(redirectUri)) {
281
+ // Existing client doesn't know about this port. Re-register a new client
282
+ // entry rather than mutating the existing one (RFC 7591 simplicity).
283
+ client = await registerClient([redirectUri]);
284
+ await writeJson(CLIENT_FILE, client);
285
+ }
286
+ // Kick off the authorization request.
287
+ const authUrl = new URL(`${ISSUER}/authorize`);
288
+ authUrl.searchParams.set('response_type', 'code');
289
+ authUrl.searchParams.set('client_id', client.client_id);
290
+ authUrl.searchParams.set('redirect_uri', redirectUri);
291
+ authUrl.searchParams.set('state', state);
292
+ authUrl.searchParams.set('scope', client.scope);
293
+ authUrl.searchParams.set('code_challenge', codeChallenge);
294
+ authUrl.searchParams.set('code_challenge_method', 'S256');
295
+ process.stderr.write('[flows-mcp] opening browser to authenticate with +Ai...\n');
296
+ openBrowser(authUrl.toString());
297
+ let callback;
298
+ try {
299
+ callback = await placeholder.wait;
300
+ }
301
+ finally {
302
+ placeholder.close();
303
+ }
304
+ const tokens = await exchangeCode({
305
+ clientId: client.client_id,
306
+ code: callback.code,
307
+ redirectUri,
308
+ codeVerifier,
309
+ });
310
+ await writeJson(TOKENS_FILE, tokens);
311
+ return {
312
+ accessToken: tokens.access_token,
313
+ expiresAt: tokens.obtained_at + tokens.expires_in * 1000,
314
+ scope: tokens.scope,
315
+ };
316
+ }
317
+ /** Drop cached credentials. Useful for `flows-mcp logout`. */
318
+ export async function clearOAuthCache() {
319
+ await fs.rm(CLIENT_FILE, { force: true });
320
+ await fs.rm(TOKENS_FILE, { force: true });
321
+ }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W,CAAC,KAAK,EAAE,CAAC;IACtB,CAAC;IAED,MAAM,MAAM,GAAG,MAAM,YAAY,CAAC;QAChC,QAAQ,EAAE,MAAO,CAAC,SAAS;QAC3B,IAAI,EAAE,QAAQ,CAAC,IAAI;QACnB,WAAW;QACX,YAAY;KACb,CAAC,CAAC;IACH,MAAM,SAAS,CAAC,WAAW,EAAE,MAAM,CAAC,CAAC;IAErC,OAAO;QACL,WAAW,EAAE,MAAM,CAAC,YAAY;QAChC,SAAS,EAAE,MAAM,CAAC,WAAW,GAAG,MAAM,CAAC,UAAU,GAAG,IAAI;QACxD,KAAK,EAAE,MAAM,CAAC,KAAK;KACpB,CAAC;AACJ,CAAC;AAED,8DAA8D;AAC9D,MAAM,CAAC,KAAK,UAAU,eAAe;IACnC,MAAM,EAAE,CAAC,EAAE,CAAC,WAAW,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;IAC1C,MAAM,EAAE,CAAC,EAAE,CAAC,WAAW,EAAE,EAAE,KAAK,EAAE,IAAI,EAAE,CAAC,CAAC;AAC5C,CAAC"}
@@ -0,0 +1,18 @@
1
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';
2
+ import type { FlowsApiClient } from '../client.js';
3
+ /**
4
+ * MCP tools for custom triggers — mirror of custom-nodes tools but for
5
+ * the trigger system. Calls the public triggers-api edge function
6
+ * (Bearer ADDAI_API_KEY auth) — see docs/CUSTOM_TRIGGERS_API.md.
7
+ *
8
+ * Tools registered:
9
+ * list_custom_triggers Discover triggers in a workspace
10
+ * describe_custom_trigger Get one trigger + version schemas
11
+ * list_custom_trigger_instances Get webhook URLs per flow placement
12
+ * create_custom_trigger Create a draft (mode locked at create)
13
+ * update_custom_trigger Patch the draft version
14
+ * publish_custom_trigger Promote draft to immutable version
15
+ * set_custom_trigger_secret Set author-scoped secret value
16
+ * deprecate_custom_trigger Soft-delete (worker stops ticking it)
17
+ */
18
+ export declare function registerCustomTriggerTools(server: McpServer, client: FlowsApiClient): void;
@@ -0,0 +1,96 @@
1
+ import { z } from 'zod';
2
+ /**
3
+ * MCP tools for custom triggers — mirror of custom-nodes tools but for
4
+ * the trigger system. Calls the public triggers-api edge function
5
+ * (Bearer ADDAI_API_KEY auth) — see docs/CUSTOM_TRIGGERS_API.md.
6
+ *
7
+ * Tools registered:
8
+ * list_custom_triggers Discover triggers in a workspace
9
+ * describe_custom_trigger Get one trigger + version schemas
10
+ * list_custom_trigger_instances Get webhook URLs per flow placement
11
+ * create_custom_trigger Create a draft (mode locked at create)
12
+ * update_custom_trigger Patch the draft version
13
+ * publish_custom_trigger Promote draft to immutable version
14
+ * set_custom_trigger_secret Set author-scoped secret value
15
+ * deprecate_custom_trigger Soft-delete (worker stops ticking it)
16
+ */
17
+ export function registerCustomTriggerTools(server, client) {
18
+ server.tool('list_custom_triggers', 'List every custom trigger in the workspace (defaults to the API key\'s primary workspace; pass workspace_id to target a different one). Returns each trigger\'s id, slug, name, mode (webhook/schedule/poll), status, visibility, current_version_number, config_schema, output_schema, default_cadence, and verifier_kind. Filter UI by mode by inspecting the returned `mode` field.', {
19
+ workspace_id: z.string().optional().describe('UUID of the workspace to list (must be in the key\'s allowed_workspace_ids). Omit for the key\'s default workspace.'),
20
+ }, async ({ workspace_id }) => {
21
+ const result = await client.listCustomTriggers(workspace_id);
22
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
23
+ });
24
+ server.tool('describe_custom_trigger', 'Get one custom trigger\'s full definition + current version (handler_code, config_schema, output_schema, secret_requirements, capabilities, verifier, default_cadence).', {
25
+ trigger_id: z.string().describe('UUID of the custom trigger'),
26
+ workspace_id: z.string().optional().describe('Workspace UUID (omit for default)'),
27
+ }, async ({ trigger_id, workspace_id }) => {
28
+ const result = await client.getCustomTrigger(trigger_id, workspace_id);
29
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
30
+ });
31
+ server.tool('list_custom_trigger_instances', 'List every flow that uses this custom trigger, with the webhook_url filled in for each placement (webhook mode) or next_due_at / last_tick_at / consecutive_errors (schedule/poll mode). External systems POST to webhook_url to fire the flow.', {
32
+ trigger_id: z.string().describe('UUID of the custom trigger'),
33
+ workspace_id: z.string().optional().describe('Workspace UUID (omit for default)'),
34
+ }, async ({ trigger_id, workspace_id }) => {
35
+ const result = await client.listCustomTriggerInstances(trigger_id, workspace_id);
36
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
37
+ });
38
+ server.tool('create_custom_trigger', 'Create a draft custom trigger. Mode is locked at creation. Returns { trigger_id, version_id }. After this, call update_custom_trigger to set the code/schemas, then publish_custom_trigger when ready.\n\nFor WEBHOOK mode: the trigger fires when an external HTTP request hits a per-instance URL. Configure verifier on update (none/hmac-sha256/bearer/basic). handler_code is optional — empty = declarative passthrough from body→output via output_schema source paths.\n\nFor SCHEDULE mode: backend worker ticks on the cadence in default_cadence ({intervalSeconds}). onTick({inputs,secrets,state}) → {fire,output,newState?}. If handler_code is empty, fires every tick with inputs.staticPayload.\n\nFor POLL mode: backend worker calls onTick on cadence; handler_code is REQUIRED and must return {events:[{dedup_key,output}], newState}. The runtime drops events whose dedup_key has been seen before.', {
39
+ name: z.string().describe('Display name (e.g. "Stripe Checkout")'),
40
+ slug: z.string().describe('URL-safe slug, lowercase + hyphens (e.g. "stripe-checkout")'),
41
+ mode: z.enum(['webhook', 'schedule', 'poll']).describe('Locked at create. webhook=HTTP-driven, schedule=time-driven, poll=time-driven with multi-event emission'),
42
+ description: z.string().optional().describe('One-line summary'),
43
+ icon: z.object({
44
+ type: z.enum(['builtin', 'emoji', 'url']).describe('builtin=lucide icon by name, emoji=single emoji, url=remote image'),
45
+ value: z.string().describe('Lucide icon name (e.g. "Bolt"), emoji character, or HTTPS image URL'),
46
+ color: z.enum(['amber', 'blue', 'emerald', 'purple', 'pink', 'red', 'orange', 'teal', 'slate']).optional(),
47
+ }).optional().describe('Branding — defaults to amber Bolt'),
48
+ workspace_id: z.string().optional().describe('Workspace UUID (omit for default)'),
49
+ }, async ({ name, slug, mode, description, icon, workspace_id }) => {
50
+ const result = await client.createCustomTrigger({ name, slug, mode, description, icon }, workspace_id);
51
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
52
+ });
53
+ server.tool('update_custom_trigger', 'Patch the draft version of a custom trigger. Only provided fields are updated. If no draft exists (trigger has been published), a new draft is forked from the current version automatically. The handler runs in a sandbox with inputs (resolved per-instance config), secrets, state (poll/schedule only), and fetch (capability-allowlist-gated). Code shape per mode:\n webhook → onRequest({inputs, body, headers, query, secrets, state, fetch}) → {fire, output}\n schedule → onTick({inputs, secrets, state, fetch}) → {fire, output, newState?}\n poll → onTick({inputs, secrets, state, fetch}) → {events:[{dedup_key, output}], newState}', {
54
+ trigger_id: z.string().describe('UUID of the custom trigger'),
55
+ name: z.string().optional(),
56
+ description: z.string().optional(),
57
+ icon: z.any().optional().describe('Same shape as create_custom_trigger.icon'),
58
+ handler_code: z.string().optional().describe('JS source. Pass empty string to clear (webhook → falls back to declarative passthrough, schedule → static payload). Required for poll mode.'),
59
+ config_schema: z.array(z.any()).optional().describe('Per-instance inputs. Array of { key, label, type (string|text|number|boolean|select|json|object|array|any), description?, default?, required?, options?: [{value,label}] (select only), noDuplicates? (select only) }'),
60
+ output_schema: z.array(z.any()).optional().describe('Fields emitted into the flow. Array of { key, label, type, description?, source? (dot-path on the request body for passthrough), required? }'),
61
+ secret_requirements: z.array(z.any()).optional().describe('Array of { key } — secret names the handler expects in `secrets`. Values are set via set_custom_trigger_secret.'),
62
+ capabilities: z.any().optional().describe('{ fetch: { domains: ["api.stripe.com", ...] } } — handler\'s fetch() is restricted to these. Empty/missing = no fetch allowed.'),
63
+ verifier: z.any().optional().describe('Webhook signature verifier: { kind: "none"|"hmac-sha256"|"bearer"|"basic", header?, secretKey?, encoding?, tolerance_seconds? }. Verifier runs before user code; rejects with 401 on mismatch.'),
64
+ default_cadence: z.any().optional().describe('Schedule/poll default cadence: { intervalSeconds: number (≥15) }. Per-instance configs can override.'),
65
+ workspace_id: z.string().optional(),
66
+ }, async ({ trigger_id, workspace_id, ...patch }) => {
67
+ const result = await client.updateCustomTrigger(trigger_id, patch, workspace_id);
68
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
69
+ });
70
+ server.tool('publish_custom_trigger', 'Promote the current draft to an immutable published version. version_number must not collide with any existing version. Publishing also resets consecutive_errors on every running instance, so the worker resumes ticking immediately.', {
71
+ trigger_id: z.string().describe('UUID of the custom trigger'),
72
+ version_number: z.string().describe('Semver (e.g. "1.0.0", "2.3.1")'),
73
+ changelog: z.string().optional().describe('What changed in this version'),
74
+ workspace_id: z.string().optional(),
75
+ }, async ({ trigger_id, version_number, changelog, workspace_id }) => {
76
+ const result = await client.publishCustomTrigger(trigger_id, { version_number, changelog }, workspace_id);
77
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
78
+ });
79
+ server.tool('set_custom_trigger_secret', 'Set an author-scoped secret value (e.g. STRIPE_WEBHOOK_SECRET). Secrets are read by the handler at runtime as secrets.KEY. Consumers (other workspaces installing this trigger) never see the values. Upsert semantics — calling twice with the same key overwrites.', {
80
+ trigger_id: z.string().describe('UUID of the custom trigger'),
81
+ key: z.string().describe('Secret key name (matches a secret_requirements entry, e.g. "STRIPE_WEBHOOK_SECRET")'),
82
+ value: z.string().describe('The raw secret value'),
83
+ workspace_id: z.string().optional(),
84
+ }, async ({ trigger_id, key, value, workspace_id }) => {
85
+ const result = await client.setCustomTriggerSecret(trigger_id, key, value, workspace_id);
86
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
87
+ });
88
+ server.tool('deprecate_custom_trigger', 'Soft-delete a custom trigger. Worker stops ticking it (for schedule/poll), the picker hides it, and external API list calls exclude it. Existing flow instances keep their pinned version until manually removed. Reversible only by direct SQL (no resurrect RPC).', {
89
+ trigger_id: z.string().describe('UUID of the custom trigger'),
90
+ workspace_id: z.string().optional(),
91
+ }, async ({ trigger_id, workspace_id }) => {
92
+ const result = await client.deprecateCustomTrigger(trigger_id, workspace_id);
93
+ return { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }] };
94
+ });
95
+ }
96
+ //# sourceMappingURL=custom-triggers.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"custom-triggers.js","sourceRoot":"","sources":["../../src/tools/custom-triggers.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAGxB;;;;;;;;;;;;;;GAcG;AACH,MAAM,UAAU,0BAA0B,CAAC,MAAiB,EAAE,MAAsB;IAElF,MAAM,CAAC,IAAI,CACT,sBAAsB,EACtB,wXAAwX,EACxX;QACE,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,qHAAqH,CAAC;KACpK,EACD,KAAK,EAAE,EAAE,YAAY,EAAE,EAAE,EAAE;QACzB,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,kBAAkB,CAAC,YAAY,CAAQ,CAAC;QACpE,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;IAChF,CAAC,CACF,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,yBAAyB,EACzB,yKAAyK,EACzK;QACE,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,4BAA4B,CAAC;QAC7D,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,QAAQ,CAAC,mCAAmC,CAAC;KAClF,EACD,KAAK,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,gBAAgB,CAAC,UAAU,EAAE,YAAY,CAAQ,CAAC;QAC9E,OAAO,EAAE,OAAO,EAAE,CAAC,EAA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AAE;QACjD,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,sBAAsB,CAAC,UAAU,EAAE,GAAG,EAAE,KAAK,EAAE,YAAY,CAAQ,CAAC;QAChG,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;IAChF,CAAC,CACF,CAAC;IAEF,MAAM,CAAC,IAAI,CACT,0BAA0B,EAC1B,qQAAqQ,EACrQ;QACE,UAAU,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,CAAC,4BAA4B,CAAC;QAC7D,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;KACpC,EACD,KAAK,EAAE,EAAE,UAAU,EAAE,YAAY,EAAE,EAAE,EAAE;QACrC,MAAM,MAAM,GAAG,MAAM,MAAM,CAAC,sBAAsB,CAAC,UAAU,EAAE,YAAY,CAAQ,CAAC;QACpF,OAAO,EAAE,OAAO,EAAE,CAAC,EAAE,IAAI,EAAE,MAAM,EAAE,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;IAChF,CAAC,CACF,CAAC;AACJ,CAAC"}
@@ -1,6 +1,11 @@
1
1
  import { z } from 'zod';
2
2
  import { getDefaultNodeData } from '../node-defaults.js';
3
3
  import { healNodeData } from '../healing.js';
4
+ const H_SPACING = 280;
5
+ const V_SPACING = 160;
6
+ const BRANCHING_NODE_TYPES = new Set([
7
+ 'if', 'switch', 'loop', 'review', 'page', 'splitTest', 'aiSwitch', 'claudeSwitch',
8
+ ]);
4
9
  /**
5
10
  * Horizontal-by-default auto-position (P9). New nodes append to the right of
6
11
  * the rightmost existing node; y is preserved so the flow stays on one row by
@@ -13,7 +18,63 @@ function autoPosition(existingNodes) {
13
18
  // Find the y of the rightmost node — that's the "current row".
14
19
  const rightmost = existingNodes.find(n => (n.position?.x ?? 0) === maxX);
15
20
  const rowY = rightmost?.position?.y ?? 0;
16
- return { x: maxX + 280, y: rowY };
21
+ return { x: maxX + H_SPACING, y: rowY };
22
+ }
23
+ function autoPositionBatch(existingNodes, newNodes, newEdges, callerProvidedPositions) {
24
+ const all = new Map();
25
+ for (const n of existingNodes)
26
+ all.set(n.id, n);
27
+ for (const n of newNodes)
28
+ all.set(n.id, n);
29
+ const positions = new Map();
30
+ for (const n of existingNodes) {
31
+ if (n.position)
32
+ positions.set(n.id, { x: n.position.x ?? 0, y: n.position.y ?? 0 });
33
+ }
34
+ for (const n of newNodes) {
35
+ if (callerProvidedPositions.has(n.id) && n.position) {
36
+ positions.set(n.id, n.position);
37
+ }
38
+ }
39
+ // Topo-ish order: place nodes whose parents already have positions first.
40
+ // Repeatedly scan until no progress, then fall back to autoPosition for orphans.
41
+ const pending = newNodes.filter((n) => !positions.has(n.id));
42
+ let safety = pending.length + 1;
43
+ while (pending.length > 0 && safety-- > 0) {
44
+ for (let i = pending.length - 1; i >= 0; i--) {
45
+ const node = pending[i];
46
+ const incoming = newEdges.filter((e) => e.target === node.id);
47
+ if (incoming.length === 0) {
48
+ positions.set(node.id, autoPosition(existingNodes));
49
+ pending.splice(i, 1);
50
+ continue;
51
+ }
52
+ const primary = incoming[0];
53
+ const parentPos = positions.get(primary.source);
54
+ if (!parentPos)
55
+ continue;
56
+ const parentNode = all.get(primary.source);
57
+ const parentType = parentNode?.type ?? '';
58
+ const isBranchParent = BRANCHING_NODE_TYPES.has(parentType) && !!primary.sourceHandle;
59
+ let y = parentPos.y;
60
+ if (isBranchParent) {
61
+ const siblings = newEdges
62
+ .filter((e) => e.source === primary.source)
63
+ .slice()
64
+ .sort((a, b) => (a.sourceHandle ?? '').localeCompare(b.sourceHandle ?? ''));
65
+ const idx = siblings.findIndex((e) => e.target === node.id);
66
+ const center = (siblings.length - 1) / 2;
67
+ y = parentPos.y + (idx - center) * V_SPACING;
68
+ }
69
+ positions.set(node.id, { x: parentPos.x + H_SPACING, y });
70
+ pending.splice(i, 1);
71
+ }
72
+ }
73
+ // Orphans (cycle / disconnected) get appended right of the existing graph.
74
+ for (const node of pending) {
75
+ positions.set(node.id, autoPosition(existingNodes));
76
+ }
77
+ return positions;
17
78
  }
18
79
  function generateEdgeId(source, target, sourceHandle, targetHandle) {
19
80
  let id = `edge_${source}_${target}`;
@@ -97,6 +158,9 @@ export function registerNodeTools(server, client, presence) {
97
158
  }
98
159
  }
99
160
  const allHealed = [];
161
+ const callerProvided = new Set();
162
+ const batchNodes = [];
163
+ const builtNodes = []; // mirror, pre-position
100
164
  for (const input of newNodes) {
101
165
  const id = crypto.randomUUID();
102
166
  const tempId = input.temp_id || id;
@@ -109,15 +173,31 @@ export function registerNodeTools(server, client, presence) {
109
173
  const node = {
110
174
  id,
111
175
  type: input.type,
112
- position: input.position || autoPosition(nodes),
176
+ position: input.position || null,
113
177
  data: healedData
114
178
  };
115
179
  if (input.parent_scope) {
116
180
  node.parentNodeId = idMap[input.parent_node_id] || input.parent_node_id;
117
181
  node.parentScope = input.parent_scope;
118
182
  }
119
- nodes.push(node);
120
- addedNodeObjects.push(node);
183
+ if (input.position)
184
+ callerProvided.add(id);
185
+ builtNodes.push(node);
186
+ batchNodes.push({ id, type: input.type, position: input.position ?? null });
187
+ }
188
+ // Resolve edge source/target tempIds to real IDs first so the batch
189
+ // placement can use the edge graph.
190
+ const resolvedNewEdges = (newEdges || []).map((e) => ({
191
+ source: idMap[e.source] || e.source,
192
+ target: idMap[e.target] || e.target,
193
+ sourceHandle: e.source_handle || null,
194
+ }));
195
+ // Branching-aware batch placement. Single source of truth for positions.
196
+ const placements = autoPositionBatch(nodes, batchNodes, resolvedNewEdges, callerProvided);
197
+ for (const n of builtNodes) {
198
+ n.position = placements.get(n.id) ?? autoPosition(nodes);
199
+ nodes.push(n);
200
+ addedNodeObjects.push(n);
121
201
  }
122
202
  for (const edge of newEdges || []) {
123
203
  const source = idMap[edge.source] || edge.source;