@beepflow/mcp 2026.5.2 → 2026.5.3

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 (2) hide show
  1. package/dist/index.js +9 -9
  2. package/package.json +1 -1
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  #!/usr/bin/env node
2
- import{stdin as Je,stdout as en}from"node:process";function tn(t){let e=new Map;for(let l of t.tools)e.set(l.name,l);let n=new Map;for(let l of t.resources??[])n.set(l.uri,l);let r=!1,o="",i={start:()=>{Je.setEncoding("utf8"),Je.on("data",l=>a(typeof l=="string"?l:l.toString("utf8"))),Je.on("end",()=>s("stdin-end")),Je.on("error",()=>s("stdin-error"))}};function s(l){if(!r){r=!0;try{en.write(JSON.stringify({jsonrpc:"2.0",method:"notifications/message",params:{level:"info",data:`server closing: ${l}`}})+`
2
+ import{stdin as Je,stdout as nn}from"node:process";function rn(t){let e=new Map;for(let l of t.tools)e.set(l.name,l);let n=new Map;for(let l of t.resources??[])n.set(l.uri,l);let r=!1,o="",i={start:()=>{Je.setEncoding("utf8"),Je.on("data",l=>a(typeof l=="string"?l:l.toString("utf8"))),Je.on("end",()=>s("stdin-end")),Je.on("error",()=>s("stdin-error"))}};function s(l){if(!r){r=!0;try{nn.write(JSON.stringify({jsonrpc:"2.0",method:"notifications/message",params:{level:"info",data:`server closing: ${l}`}})+`
3
3
  `)}catch{}}}function a(l){for(o+=l;;){let h=o.indexOf(`
4
- `);if(h===-1)return;let y=o.slice(0,h).trim();if(o=o.slice(h+1),!y)continue;let S;try{S=JSON.parse(y)}catch{continue}c(S)}}async function c(l){if(r)return;let h=l.id===void 0,y=l.id??null;try{switch(l.method){case"initialize":{let le={protocolVersion:(l.params??{}).protocolVersion??"2024-11-05",serverInfo:{name:t.serverName,version:t.serverVersion},capabilities:{tools:{},resources:{}},...t.instructions?{instructions:t.instructions}:{}};if(h)return;d({jsonrpc:"2.0",id:y,result:le});return}case"notifications/initialized":{t.onInitialized?.();return}case"notifications/cancelled":return;case"logging/setLevel":{if(h)return;d({jsonrpc:"2.0",id:y,result:{}});return}case"ping":{if(h)return;d({jsonrpc:"2.0",id:y,result:{}});return}case"tools/list":{if(h)return;let S=t.tools.map(O=>({name:O.name,description:O.description,inputSchema:O.inputSchema}));d({jsonrpc:"2.0",id:y,result:{tools:S}});return}case"tools/call":{if(h)return;let S=l.params??{},O=typeof S.name=="string"?S.name:"",le=e.get(O);if(!le){d({jsonrpc:"2.0",id:y,error:{code:-32601,message:`unknown tool: ${O}`}});return}let St=await le.call(S.arguments);d({jsonrpc:"2.0",id:y,result:St});return}case"resources/list":{if(h)return;let S=(t.resources??[]).map(O=>({uri:O.uri,name:O.name,description:O.description,mimeType:O.mimeType}));d({jsonrpc:"2.0",id:y,result:{resources:S}});return}case"resources/read":{if(h)return;let S=l.params??{},O=typeof S.uri=="string"?S.uri:"",le=n.get(O);if(!le){d({jsonrpc:"2.0",id:y,error:{code:-32602,message:`unknown resource: ${O}`}});return}let St=await le.read();d({jsonrpc:"2.0",id:y,result:St});return}case"prompts/list":{if(h)return;d({jsonrpc:"2.0",id:y,result:{prompts:[]}});return}default:{if(h)return;d({jsonrpc:"2.0",id:y,error:{code:-32601,message:`method not found: ${l.method}`}})}}}catch(S){if(h)return;d({jsonrpc:"2.0",id:y,error:{code:-32603,message:S?.message??"internal error"}})}}function d(l){r||en.write(JSON.stringify(l)+`
5
- `)}return{server:i,closeServer:s}}import{createHash as As}from"node:crypto";import on from"node:os";import be from"node:path";var ao={dev:{name:"dev",frontendUrl:"http://localhost:21073",backendUrl:"http://localhost:2451/api",authUrl:"https://auth.fewlogs.com",authDomain:"beepflow.com"},live:{name:"live",frontendUrl:"https://beepflow.com",backendUrl:"https://beepflow.com/api",authUrl:"https://auth.fewlogs.com",authDomain:"beepflow.com"}};function co(t){let n=nn(t,"--env")??nn(t,"--environment")??process.env.BEEPFLOW_ENV??"live";if(n==="dev"||n==="live")return n;throw new Error(`invalid BEEPFLOW_ENV: ${n}`)}function rn(t){let e=co(t);return ao[e]}function nn(t,e){for(let n=0;n<t.length;n+=1){let r=t[n];if(r===e){let i=t[n+1];if(!i)throw new Error(`missing value for ${e}`);return i}let o=`${e}=`;if(r&&r.startsWith(o)){let i=r.slice(o.length);if(!i)throw new Error(`missing value for ${e}`);return i}}}function k(){let t=process.argv.slice(2),e=rn(t),n=Ve("backend url",[fe(t,"--backend-url"),process.env.BEEPFLOW_BACKEND_URL,e.backendUrl]),r=Ve("frontend url",[fe(t,"--frontend-url"),process.env.BEEPFLOW_FRONTEND_URL,e.frontendUrl]),o=Ve("auth url",[fe(t,"--auth-url"),process.env.BEEPFLOW_AUTH_URL,e.authUrl]),i=Ve("auth domain",[fe(t,"--auth-domain"),process.env.BEEPFLOW_AUTH_DOMAIN,e.authDomain]),s=fe(t,"--token-store-path")??process.env.BEEPFLOW_TOKEN_STORE_PATH??po(),a=fe(t,"--replicated-state-db-path")??process.env.BEEPFLOW_REPLICATED_STATE_DB_PATH??uo();return{environmentName:e.name,frontendUrl:r.replace(/\/+$/,""),backendUrl:n.replace(/\/+$/,""),authUrl:o.replace(/\/+$/,""),authDomain:i,jwtFromEnvironment:fe(t,"--jwt")??process.env.BEEPFLOW_JWT,tokenStorePath:s,replicatedStateDatabasePath:a}}function fe(t,e){for(let n=0;n<t.length;n+=1){let r=t[n];if(r===e){let i=t[n+1];if(!i)throw new Error(`missing value for ${e}`);return i}let o=`${e}=`;if(r&&r.startsWith(o)){let i=r.slice(o.length);if(!i)throw new Error(`missing value for ${e}`);return i}}}function po(){let t=process.env.APPDATA;if(t)return be.join(t,"beepflow-mcp","backend-access-token.json");let e=process.env.XDG_CONFIG_HOME;return e?be.join(e,"beepflow-mcp","backend-access-token.json"):be.join(on.homedir(),".config","beepflow-mcp","backend-access-token.json")}function uo(){let t=process.env.LOCALAPPDATA;if(t)return be.join(t,"beepflow-mcp","replicated-state.sqlite");let e=process.env.XDG_CACHE_HOME;return e?be.join(e,"beepflow-mcp","replicated-state.sqlite"):be.join(on.homedir(),".cache","beepflow-mcp","replicated-state.sqlite")}function Ve(t,e){for(let n of e)if(typeof n=="string"&&n.trim())return n;throw new Error(`missing ${t}`)}import Ge from"node:fs/promises";import mo from"node:path";import lo from"node:crypto";function ne(t){let e=t.split(".");if(e.length<2)return{accessToken:t,email:void 0,exp:void 0,provider:void 0};let n=fo(e[1]??"");if(!n)return{accessToken:t,email:void 0,exp:void 0,provider:void 0};let r;try{r=JSON.parse(n)}catch{return{accessToken:t,email:void 0,exp:void 0,provider:void 0}}let o=typeof r.email=="string"?r.email.toLowerCase():void 0,i=typeof r.exp=="number"?r.exp:void 0,s=typeof r.provider=="string"?r.provider:void 0;return{accessToken:t,email:o,exp:i,provider:s}}function sn(t){return t?t.length<=12?`${t.slice(0,4)}\u2026`:`${t.slice(0,6)}\u2026${t.slice(-4)}`:""}function ze(){return lo.randomBytes(9).toString("base64url")}function fo(t){if(!t)return;let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4,r=e+"=".repeat(n);try{return Buffer.from(r,"base64").toString("utf8")}catch{return}}async function X(){let t=k();return t.jwtFromEnvironment?t.jwtFromEnvironment:(await cn(t.tokenStorePath))?.accessToken}async function we(t){let e=k(),n=ne(t),r={accessToken:t,email:n.email,provider:n.provider,exp:n.exp};return await go(e.tokenStorePath,r),r}async function an(){let t=k(),e=await cn(t.tokenStorePath)!==void 0;return await Ge.rm(t.tokenStorePath,{force:!0}),{backendUrl:t.backendUrl,deleted:e}}function Ke(t){return{email:t.email,provider:t.provider,exp:t.exp,accessToken:sn(t.accessToken)}}async function cn(t){try{let e=await Ge.readFile(t,"utf8"),n=JSON.parse(e);return!n||typeof n!="object"||typeof n.accessToken!="string"?void 0:n}catch{return}}async function go(t,e){await Ge.mkdir(mo.dirname(t),{recursive:!0}),await Ge.writeFile(t,JSON.stringify(e,null,2)+`
6
- `,"utf8")}async function pn(t){let e=k(),n=await fetch(`${e.authUrl}/email/request-code`,{method:"POST",headers:{"content-type":"application/json",domain:e.authDomain},body:JSON.stringify({email:t})});if(!n.ok){let r=await n.text().catch(()=>"");throw new Error(`email/request-code failed: ${n.status} ${r}`.trim())}}async function dn(t,e){let n=k(),r=await fetch(`${n.authUrl}/email/verify-code`,{method:"POST",headers:{"content-type":"application/json",domain:n.authDomain},body:JSON.stringify({email:t,code:e})}),o=await r.json().catch(()=>{});if(!r.ok)throw new Error(`email/verify-code failed: ${r.status}`);let i=typeof o?.access_token=="string"?o.access_token:"";if(!i)throw new Error("email/verify-code failed: missing access_token");let s=await we(i);return{backendUrl:n.backendUrl,...Ke(s)}}import ho from"node:crypto";import{spawn as yo}from"node:child_process";import{setTimeout as bo}from"node:timers/promises";async function un(){let t=await wo(),e=Date.now()+12e4;for(;Date.now()<e;){let n=await Ro(t.requestId);if(n.status!=="pending")return{...t,...n};await bo(1500)}return{...t,status:"pending",message:"Timed out waiting for Google sign-in. Run auth_google_sign_in again to retry."}}async function wo(){let t=k(),e=ho.randomUUID(),n=new URL(`${t.authUrl}/google-form`);return n.searchParams.set("requestId",e),n.searchParams.set("scopes","openid email profile"),{requestId:e,url:n.toString(),browserOpened:ko(n.toString())}}async function Ro(t){let e=k(),n=new URL(`${e.authUrl}/google-auth-token`);n.searchParams.set("id",t);let r=await fetch(n.toString(),{headers:{domain:e.authDomain}}),o=await r.json().catch(()=>{});if(r.status===400&&o?.error==="Token not found")return{status:"pending",requestId:t};if(!r.ok)return{status:"failed",requestId:t,message:`google-auth-token failed: ${r.status}`};let i=typeof o?.access_token=="string"?o.access_token:"";if(!i)return{status:"pending",requestId:t};let s=await we(i);return{status:"authenticated",requestId:t,backendUrl:e.backendUrl,...Ke(s)}}function ko(t){let e="xdg-open",n=[t];switch(process.platform){case"darwin":e="open";break;case"win32":e="rundll32",n=["url.dll,FileProtocolHandler",t];break}try{let r=yo(e,n,{detached:!0,stdio:"ignore"});return r.on("error",()=>{}),r.unref(),!0}catch{return!1}}async function Y(t){let e=ne(t);if(e.provider!=="google"||!e.exp)return t;let n=Date.now(),r=e.exp*1e3,o=300*1e3;if(r-n>=o)return t;let i=k(),s=await fetch(`${i.authUrl}/google-refresh`,{method:"GET",headers:{Authorization:`Bearer ${t}`}}),a=await s.json().catch(()=>{});if(!s.ok)return t;let c=typeof a?.access_token=="string"?a.access_token:"";return c?(await we(c),c):t}async function ln(t){let e=k(),n=await fetch(`${e.backendUrl}/users/is-member`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`users/is-member failed: ${n.status} ${o}`.trim())}if((await n.json().catch(()=>{}))?.isMember!==!0)throw new Error("user not member of workspace")}import{isDeepStrictEqual as ei}from"node:util";import To from"node:crypto";import So from"node:fs";import Io from"node:path";import{DatabaseSync as xo}from"node:sqlite";var Qe=class{database;databasePath;scope;constructor(e,n){this.databasePath=e,this.scope=n}async loadItems(e){let n=this.getDatabase().prepare("select key, value_json from replicated_items where scope = ? and resource = ?").all(this.scope,e),r={};for(let o of n)r[o.key]=JSON.parse(o.value_json);return n.length>0?r:null}async persistItem(e,n,r){this.getDatabase().prepare(`insert into replicated_items (scope, resource, key, value_json, saved_at_ms)
4
+ `);if(h===-1)return;let y=o.slice(0,h).trim();if(o=o.slice(h+1),!y)continue;let S;try{S=JSON.parse(y)}catch{continue}c(S)}}async function c(l){if(r)return;let h=l.id===void 0,y=l.id??null;try{switch(l.method){case"initialize":{let le={protocolVersion:(l.params??{}).protocolVersion??"2024-11-05",serverInfo:{name:t.serverName,version:t.serverVersion},capabilities:{tools:{},resources:{}},...t.instructions?{instructions:t.instructions}:{}};if(h)return;d({jsonrpc:"2.0",id:y,result:le});return}case"notifications/initialized":{t.onInitialized?.();return}case"notifications/cancelled":return;case"logging/setLevel":{if(h)return;d({jsonrpc:"2.0",id:y,result:{}});return}case"ping":{if(h)return;d({jsonrpc:"2.0",id:y,result:{}});return}case"tools/list":{if(h)return;let S=t.tools.map(O=>({name:O.name,description:O.description,inputSchema:O.inputSchema}));d({jsonrpc:"2.0",id:y,result:{tools:S}});return}case"tools/call":{if(h)return;let S=l.params??{},O=typeof S.name=="string"?S.name:"",le=e.get(O);if(!le){d({jsonrpc:"2.0",id:y,error:{code:-32601,message:`unknown tool: ${O}`}});return}let It=await le.call(S.arguments);d({jsonrpc:"2.0",id:y,result:It});return}case"resources/list":{if(h)return;let S=(t.resources??[]).map(O=>({uri:O.uri,name:O.name,description:O.description,mimeType:O.mimeType}));d({jsonrpc:"2.0",id:y,result:{resources:S}});return}case"resources/read":{if(h)return;let S=l.params??{},O=typeof S.uri=="string"?S.uri:"",le=n.get(O);if(!le){d({jsonrpc:"2.0",id:y,error:{code:-32602,message:`unknown resource: ${O}`}});return}let It=await le.read();d({jsonrpc:"2.0",id:y,result:It});return}case"prompts/list":{if(h)return;d({jsonrpc:"2.0",id:y,result:{prompts:[]}});return}default:{if(h)return;d({jsonrpc:"2.0",id:y,error:{code:-32601,message:`method not found: ${l.method}`}})}}}catch(S){if(h)return;d({jsonrpc:"2.0",id:y,error:{code:-32603,message:S?.message??"internal error"}})}}function d(l){r||nn.write(JSON.stringify(l)+`
5
+ `)}return{server:i,closeServer:s}}import{createHash as Os}from"node:crypto";import an from"node:os";import be from"node:path";var fo={dev:{name:"dev",frontendUrl:"http://localhost:21073",backendUrl:"http://localhost:2451/api",authUrl:"https://auth.fewlogs.com",authDomain:"beepflow.com"},live:{name:"live",frontendUrl:"https://beepflow.com",backendUrl:"https://beepflow.com/api",authUrl:"https://auth.fewlogs.com",authDomain:"beepflow.com"}};function mo(t){let n=on(t,"--env")??on(t,"--environment")??process.env.BEEPFLOW_ENV??"live";if(n==="dev"||n==="live")return n;throw new Error(`invalid BEEPFLOW_ENV: ${n}`)}function sn(t){let e=mo(t);return fo[e]}function on(t,e){for(let n=0;n<t.length;n+=1){let r=t[n];if(r===e){let i=t[n+1];if(!i)throw new Error(`missing value for ${e}`);return i}let o=`${e}=`;if(r&&r.startsWith(o)){let i=r.slice(o.length);if(!i)throw new Error(`missing value for ${e}`);return i}}}function k(){let t=process.argv.slice(2),e=sn(t),n=Ve("backend url",[fe(t,"--backend-url"),process.env.BEEPFLOW_BACKEND_URL,e.backendUrl]),r=Ve("frontend url",[fe(t,"--frontend-url"),process.env.BEEPFLOW_FRONTEND_URL,e.frontendUrl]),o=Ve("auth url",[fe(t,"--auth-url"),process.env.BEEPFLOW_AUTH_URL,e.authUrl]),i=Ve("auth domain",[fe(t,"--auth-domain"),process.env.BEEPFLOW_AUTH_DOMAIN,e.authDomain]),s=fe(t,"--token-store-path")??process.env.BEEPFLOW_TOKEN_STORE_PATH??go(),a=fe(t,"--replicated-state-db-path")??process.env.BEEPFLOW_REPLICATED_STATE_DB_PATH??ho();return{environmentName:e.name,frontendUrl:r.replace(/\/+$/,""),backendUrl:n.replace(/\/+$/,""),authUrl:o.replace(/\/+$/,""),authDomain:i,jwtFromEnvironment:fe(t,"--jwt")??process.env.BEEPFLOW_JWT,tokenStorePath:s,replicatedStateDatabasePath:a}}function fe(t,e){for(let n=0;n<t.length;n+=1){let r=t[n];if(r===e){let i=t[n+1];if(!i)throw new Error(`missing value for ${e}`);return i}let o=`${e}=`;if(r&&r.startsWith(o)){let i=r.slice(o.length);if(!i)throw new Error(`missing value for ${e}`);return i}}}function go(){let t=process.env.APPDATA;if(t)return be.join(t,"beepflow-mcp","backend-access-token.json");let e=process.env.XDG_CONFIG_HOME;return e?be.join(e,"beepflow-mcp","backend-access-token.json"):be.join(an.homedir(),".config","beepflow-mcp","backend-access-token.json")}function ho(){let t=process.env.LOCALAPPDATA;if(t)return be.join(t,"beepflow-mcp","replicated-state.sqlite");let e=process.env.XDG_CACHE_HOME;return e?be.join(e,"beepflow-mcp","replicated-state.sqlite"):be.join(an.homedir(),".cache","beepflow-mcp","replicated-state.sqlite")}function Ve(t,e){for(let n of e)if(typeof n=="string"&&n.trim())return n;throw new Error(`missing ${t}`)}import Ge from"node:fs/promises";import wo from"node:path";import yo from"node:crypto";function ne(t){let e=t.split(".");if(e.length<2)return{accessToken:t,email:void 0,exp:void 0,provider:void 0};let n=bo(e[1]??"");if(!n)return{accessToken:t,email:void 0,exp:void 0,provider:void 0};let r;try{r=JSON.parse(n)}catch{return{accessToken:t,email:void 0,exp:void 0,provider:void 0}}let o=typeof r.email=="string"?r.email.toLowerCase():void 0,i=typeof r.exp=="number"?r.exp:void 0,s=typeof r.provider=="string"?r.provider:void 0;return{accessToken:t,email:o,exp:i,provider:s}}function cn(t){return t?t.length<=12?`${t.slice(0,4)}\u2026`:`${t.slice(0,6)}\u2026${t.slice(-4)}`:""}function ze(){return yo.randomBytes(9).toString("base64url")}function bo(t){if(!t)return;let e=t.replace(/-/g,"+").replace(/_/g,"/"),n=(4-e.length%4)%4,r=e+"=".repeat(n);try{return Buffer.from(r,"base64").toString("utf8")}catch{return}}async function X(){let t=k();return t.jwtFromEnvironment?t.jwtFromEnvironment:(await dn(t.tokenStorePath))?.accessToken}async function we(t){let e=k(),n=ne(t),r={accessToken:t,email:n.email,provider:n.provider,exp:n.exp};return await Ro(e.tokenStorePath,r),r}async function pn(){let t=k(),e=await dn(t.tokenStorePath)!==void 0;return await Ge.rm(t.tokenStorePath,{force:!0}),{backendUrl:t.backendUrl,deleted:e}}function Ke(t){return{email:t.email,provider:t.provider,exp:t.exp,accessToken:cn(t.accessToken)}}async function dn(t){try{let e=await Ge.readFile(t,"utf8"),n=JSON.parse(e);return!n||typeof n!="object"||typeof n.accessToken!="string"?void 0:n}catch{return}}async function Ro(t,e){await Ge.mkdir(wo.dirname(t),{recursive:!0}),await Ge.writeFile(t,JSON.stringify(e,null,2)+`
6
+ `,"utf8")}async function un(t){let e=k(),n=await fetch(`${e.authUrl}/email/request-code`,{method:"POST",headers:{"content-type":"application/json",domain:e.authDomain},body:JSON.stringify({email:t})});if(!n.ok){let r=await n.text().catch(()=>"");throw new Error(`email/request-code failed: ${n.status} ${r}`.trim())}}async function ln(t,e){let n=k(),r=await fetch(`${n.authUrl}/email/verify-code`,{method:"POST",headers:{"content-type":"application/json",domain:n.authDomain},body:JSON.stringify({email:t,code:e})}),o=await r.json().catch(()=>{});if(!r.ok)throw new Error(`email/verify-code failed: ${r.status}`);let i=typeof o?.access_token=="string"?o.access_token:"";if(!i)throw new Error("email/verify-code failed: missing access_token");let s=await we(i);return{backendUrl:n.backendUrl,...Ke(s)}}import ko from"node:crypto";import{spawn as To}from"node:child_process";import{setTimeout as So}from"node:timers/promises";async function fn(){let t=await Io(),e=Date.now()+12e4;for(;Date.now()<e;){let n=await xo(t.requestId);if(n.status!=="pending")return{...t,...n};await So(1500)}return{...t,status:"pending",message:"Timed out waiting for Google sign-in. Run auth_google_sign_in again to retry."}}async function Io(){let t=k(),e=ko.randomUUID(),n=new URL(`${t.authUrl}/google-form`);return n.searchParams.set("requestId",e),n.searchParams.set("scopes","openid email profile"),{requestId:e,url:n.toString(),browserOpened:vo(n.toString())}}async function xo(t){let e=k(),n=new URL(`${e.authUrl}/google-auth-token`);n.searchParams.set("id",t);let r=await fetch(n.toString(),{headers:{domain:e.authDomain}}),o=await r.json().catch(()=>{});if(r.status===400&&o?.error==="Token not found")return{status:"pending",requestId:t};if(!r.ok)return{status:"failed",requestId:t,message:`google-auth-token failed: ${r.status}`};let i=typeof o?.access_token=="string"?o.access_token:"";if(!i)return{status:"pending",requestId:t};let s=await we(i);return{status:"authenticated",requestId:t,backendUrl:e.backendUrl,...Ke(s)}}function vo(t){let e="xdg-open",n=[t];switch(process.platform){case"darwin":e="open";break;case"win32":e="rundll32",n=["url.dll,FileProtocolHandler",t];break}try{let r=To(e,n,{detached:!0,stdio:"ignore"});return r.on("error",()=>{}),r.unref(),!0}catch{return!1}}async function Y(t){let e=ne(t);if(e.provider!=="google"||!e.exp)return t;let n=Date.now(),r=e.exp*1e3,o=300*1e3;if(r-n>=o)return t;let i=k(),s=await fetch(`${i.authUrl}/google-refresh`,{method:"GET",headers:{Authorization:`Bearer ${t}`}}),a=await s.json().catch(()=>{});if(!s.ok)return t;let c=typeof a?.access_token=="string"?a.access_token:"";return c?(await we(c),c):t}async function mn(t){let e=k(),n=await fetch(`${e.backendUrl}/users/is-member`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});if(!n.ok){let o=await n.text().catch(()=>"");throw new Error(`users/is-member failed: ${n.status} ${o}`.trim())}if((await n.json().catch(()=>{}))?.isMember!==!0)throw new Error("user not member of workspace")}import{isDeepStrictEqual as ni}from"node:util";import Bo from"node:crypto";import Po from"node:fs";import Eo from"node:path";import{DatabaseSync as No}from"node:sqlite";var Qe=class{database;databasePath;scope;constructor(e,n){this.databasePath=e,this.scope=n}async loadItems(e){let n=this.getDatabase().prepare("select key, value_json from replicated_items where scope = ? and resource = ?").all(this.scope,e),r={};for(let o of n)r[o.key]=JSON.parse(o.value_json);return n.length>0?r:null}async persistItem(e,n,r){this.getDatabase().prepare(`insert into replicated_items (scope, resource, key, value_json, saved_at_ms)
7
7
  values (?, ?, ?, ?, ?)
8
8
  on conflict(scope, resource, key) do update set
9
9
  value_json = excluded.value_json,
10
- saved_at_ms = excluded.saved_at_ms`).run(this.scope,e,n,JSON.stringify(r),Date.now())}async deleteResource(e){this.getDatabase().prepare("delete from replicated_items where scope = ? and resource = ?").run(this.scope,e)}async clearAll(){this.getDatabase().prepare("delete from replicated_items where scope = ?").run(this.scope)}close(){this.database?.close(),this.database=void 0}getDatabase(){return this.database?this.database:(So.mkdirSync(Io.dirname(this.databasePath),{recursive:!0}),this.database=new xo(this.databasePath),this.database.exec(`
10
+ saved_at_ms = excluded.saved_at_ms`).run(this.scope,e,n,JSON.stringify(r),Date.now())}async deleteResource(e){this.getDatabase().prepare("delete from replicated_items where scope = ? and resource = ?").run(this.scope,e)}async clearAll(){this.getDatabase().prepare("delete from replicated_items where scope = ?").run(this.scope)}close(){this.database?.close(),this.database=void 0}getDatabase(){return this.database?this.database:(Po.mkdirSync(Eo.dirname(this.databasePath),{recursive:!0}),this.database=new No(this.databasePath),this.database.exec(`
11
11
  create table if not exists replicated_items (
12
12
  scope text not null,
13
13
  resource text not null,
@@ -16,10 +16,10 @@ import{stdin as Je,stdout as en}from"node:process";function tn(t){let e=new Map;
16
16
  saved_at_ms integer not null,
17
17
  primary key (scope, resource, key)
18
18
  )
19
- `),this.database)}};function fn(t){let e=t??"unknown-user";return To.createHash("sha256").update(e).digest("hex")}function mn(t,e,n){let r=t.replace(/^http/,"ws"),o=encodeURIComponent(e),i=encodeURIComponent(n);return`${r}/base/${o}/${i}`}var He=class{websocket;sessionId=ze();backendUrl;accessToken;channelListeners=new Map;disconnectListeners=new Set;ackWaiters=new Map;intentionallyClosed=!1;constructor(e,n){this.backendUrl=e,this.accessToken=n}async connect(e){this.intentionallyClosed=!1,this.sessionId=ze();let n=mn(this.backendUrl,this.accessToken,this.sessionId),r=new WebSocket(n,"echo");this.websocket=r,await new Promise((o,i)=>{let s=setTimeout(()=>i(new Error("websocket open timeout")),e);r.onopen=()=>{clearTimeout(s),o()},r.onerror=()=>{clearTimeout(s),i(new Error("websocket open failed"))}}),r.onmessage=o=>this.processMessage(o.data),r.onclose=()=>this.processClose(),r.onerror=()=>this.processClose()}getSessionId(){return this.sessionId}send(e,n){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("gateway websocket not connected");this.websocket.send(`${e};${JSON.stringify(n)}`)}sendWithAck(e,n,r=5e3){let o=ze(),i={...n,eventId:o};return new Promise(s=>{let a=setTimeout(()=>{this.ackWaiters.delete(o),s({ok:!1,reason:"timeout"})},r);this.ackWaiters.set(o,{resolve:s,timeout:a}),this.send(e,i)})}onChannel(e,n){return this.channelListeners.has(e)||this.channelListeners.set(e,new Set),this.channelListeners.get(e).add(n),()=>this.channelListeners.get(e)?.delete(n)}onDisconnected(e){return this.disconnectListeners.add(e),()=>this.disconnectListeners.delete(e)}waitForChannelEvent(e,n,r){return new Promise((o,i)=>{let s=setTimeout(()=>{a(),i(new Error(`channel event timeout: ${e}`))},r),a=this.onChannel(e,c=>{n(c)&&(clearTimeout(s),a(),o(c))})})}collectChannelEvents(e,n,r,o){return new Promise((i,s)=>{let a=[],c,d=setTimeout(()=>{h(),c&&clearTimeout(c),s(new Error(`channel event timeout: ${e}`))},r),l=()=>{clearTimeout(d),h(),i(a)},h=this.onChannel(e,y=>{n(y)&&(a.push(y),c&&clearTimeout(c),c=setTimeout(l,o))})})}close(){this.intentionallyClosed=!0,this.websocket?.close(),this.websocket=void 0;for(let e of this.ackWaiters.values())clearTimeout(e.timeout),e.resolve({ok:!1,reason:"closed"});this.ackWaiters.clear()}processMessage(e){let n=typeof e=="string"?e:"",r=n.indexOf(";");if(r===-1)return;let o=n.slice(0,r),i=n.slice(r+1),s;try{s=JSON.parse(i)}catch{return}if(o.startsWith("ack:")){this.resolveAck(o.slice(4),s);return}s=vo(s);let a=this.channelListeners.get(o);if(a)for(let c of a)c(s)}resolveAck(e,n){let r=this.ackWaiters.get(e);r&&(this.ackWaiters.delete(e),clearTimeout(r.timeout),r.resolve(n.value??{ok:!1}))}processClose(){if(!this.intentionallyClosed)for(let e of this.disconnectListeners)e()}};function vo(t){if(t.resource!=="connections")return t;switch(t.action){case"snapshot":return{...t,value:Bo(t.value)};case"delta":return{...t,value:Po(t.value)};default:return t}}function Bo(t){if(!It(t))return t;let e={};for(let n in t)e[n]=hn(t[n]);return e}function Po(t){return It(t)?{...t,pre:gn(t.pre),post:gn(t.post)}:t}function gn(t){return t===null?null:hn(t)}function hn(t){if(!It(t))return t;let e={...t};return delete e.config,e}function It(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var xt="beepflow://resource-schemas/",I={type:"number",description:"Nanoseconds since Unix epoch. Omit updatedAt on creates and manual edits unless preserving an existing value; replicated state updates it after accepted writes."},u={type:"string"},re={type:"number"},yn={type:"integer"},N={type:"boolean"};var bn={type:"object",additionalProperties:u},vt={type:"object",additionalProperties:N},Ze={type:"object",additionalProperties:{type:"object",additionalProperties:N,properties:{list:N,detail:N,create:N,edit:N,delete:N,authorize:N}}},me=["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"],wn=["ManualTick","AerospikeSet","ApacheKafkaTopic","MQTTTopic","KaggleFile","RabbitMQQueue","RabbitMQStream","ShopifyWebhook","QdrantCollection","BaseVectorCollection","BaseEventCollection","BaseLookupCollection","GorgiasEvent","GorgiasTicket","GoogleDriveFile","GmailMessage","GmailThread","GmailEvent"],ge={anyOf:[N,{type:"null"}]},Eo=["Use resource_query first when editing existing items; upsert sends whole item state, not a JSON patch. Preserve unchanged fields.","Omit updatedAt on creates and manual edits unless preserving an existing value; replicated state updates it after accepted writes."];function x(t,e,n){let r=`${xt}${t}`;return{resource:t,uri:r,sourceType:e,notes:Eo,itemSchema:{$schema:"https://json-schema.org/draft/2020-12/schema",title:`Beepflow ${t} item`,type:"object",additionalProperties:!1,required:n.required,properties:n.properties,...n.defs?{$defs:n.defs}:{}}}}var Bt={$ref:"#/$defs/operatorType"},No={type:"object",additionalProperties:!1,required:["value"],properties:{value:{description:"Raw option value written to node input literal when selected."},label:{...u,description:"Optional label shown in operator input dropdowns."}}},Ao={type:"object",additionalProperties:!1,required:["type"],properties:{type:{type:"string",enum:me,description:'Blueprint value type name. Use "list of X" for lists, never "list".'},options:{anyOf:[{type:"array",items:No},{type:"null"}],description:"Allowed literal values for dropdown-style widgets."},isArray:{type:"boolean",description:"Whether this pin accepts multiple values."},allowedTypes:{anyOf:[{type:"array",items:Bt},{type:"null"}],description:"Allowed concrete types for wildcard pins."},linkType:{...u,description:"Type-linking group used to propagate wildcard types across pins."},widgetType:{...u,description:'Frontend input widget id. Supports built-in widgets, integration selectors, and "<IntegrationType>-connection" connection dropdowns.'},defaultValue:{description:"Default literal value used when node input omits a value."},defaultValueForArrayElement:{description:"Default literal value for newly added array input elements."}}},Do={type:"object",additionalProperties:!1,required:["name","doc","type"],properties:{name:{...u,description:"Output pin name."},doc:{...u,description:"Operator output documentation shown to users."},type:Bt}},Oo={type:"object",additionalProperties:!1,required:["name","doc","type"],properties:{name:{...u,description:"Input pin name; node inputs are keyed by this value."},doc:{...u,description:"Operator input documentation shown to users."},type:Bt,isLiteral:{...N,description:"Whether this input must be edited as literal value instead of upstream connection."}}},Rn=x("blueprint-operators","frontend/src/tabs/blueprint/types.ts:Operator",{required:["id","type","name","doc","categoryPath","inputs"],properties:{id:{...u,description:"Stable registered operator id referenced by blueprint nodes."},type:{...u,description:"Operator kind, usually function, variable, or localVariable."},name:{...u,description:"Display name used in operator search and node labels."},aliases:{type:"array",items:u,description:"Additional search terms for this operator."},doc:{...u,description:"Operator documentation shown to users."},categoryPath:{type:"array",items:u,description:"Menu category path segments."},inputs:{type:"array",items:Oo,description:"Input pins in display order."},output:{anyOf:[Do,{type:"null"}],description:"Output pin definition, or null for side-effect-only operators."},isDeprecated:{...N,description:"Whether operator is deprecated and hidden from default search."},hidden:{...N,description:"Whether operator is hidden from menus and search."},canMock:{...N,description:"Whether test mode can mock this operator."},updatedAt:I},defs:{operatorType:Ao}});var Co={type:"object",additionalProperties:!1,properties:{x:{...re,description:"Optional node world x coordinate in blueprint editor. For new nodes, never specify style.x; omit it so the frontend can place nodes after measuring dimensions."},y:{...re,description:"Optional node world y coordinate in blueprint editor. For new nodes, never specify style.y; omit it so the frontend can place nodes after measuring dimensions."},title:{...u,description:"Optional display title shown on node."},comment:{...u,description:"Optional user-authored node comment."}}},_o={type:"object",additionalProperties:!0,description:"Blueprint view node. For new nodes, never specify style.x or style.y; omit coordinates so the frontend can place nodes after measuring dimensions. Known visualization blocks are intentionally accepted as additional properties.",required:["id"],properties:{id:{...u,description:"Node id; must match key in blueprint view nodes record."},style:Co}},kn=x("blueprint-views","frontend/src/tabs/blueprint/types.ts:BlueprintView",{required:["id","nodes"],properties:{id:{...u,description:"Blueprint tab id; must match tabs and blueprints resource id."},updatedAt:I,nodes:{type:"object",additionalProperties:_o,description:"Editor view state keyed by node id."}}});var Xe={type:"string",description:"Integration resource type processed by this blueprint, such as ApacheKafkaTopic or QdrantCollection. Call integration_blueprint_contexts_list first; use only resource types returned by that tool. The returned executionKind determines trigger choice: managed resources use executor, finite resources use manual/cron/loop/blueprint/webhook based on user intent."},Ye={type:"object",additionalProperties:!0,description:"Integration-specific config for context.type. Start from contextTemplate.config returned by integration_blueprint_contexts_list, fill every configFields item where required=true, and preserve optional defaults such as consumerGroupId, clientId, parser, offsetResetStrategy, orderBy, or webhook topic maps when provided."},Pt={type:"object",additionalProperties:!1,required:["enabled"],properties:{enabled:{type:"boolean",enum:[!0],description:"Must be true. Backend ignores this trigger branch when enabled is false."}}},Mo=["auto","application/json","text/plain","text/html","application/xml","application/x-www-form-urlencoded","multipart/form-data","application/octet-stream"],$o={type:"object",additionalProperties:!1,required:["count"],description:"Run immediately when explore runtime starts or restarts. Use for finite resource sampling, one-shot imports, and ad hoc reads.",properties:{count:{type:"integer",minimum:1,description:"Number of executions to run back-to-back. Frontend default is 1; backend coerces values below 1 to 1."}}},Fo={type:"object",additionalProperties:!1,required:["expression"],description:"Run on a seconds-field cron schedule while explore runtime is active. Use for scheduled finite-resource refreshes.",properties:{expression:{type:"string",description:"Cron expression with six fields including seconds, parsed by robfig/cron. Example: 0 */5 * * * * runs every five minutes."},timezone:{type:"string",description:"Optional IANA timezone name such as UTC or America/New_York. Backend uses UTC when omitted or empty."}}},Wo={type:"object",additionalProperties:!1,required:["delayMs"],description:"Run immediately, then wait delayMs before repeating while explore runtime is active. Use only for deliberate fixed-delay polling.",properties:{delayMs:{type:"integer",minimum:1,description:"Delay between executions in milliseconds. Must be positive to avoid a hot loop."}}},qo={...Pt,description:"Wait while active until another blueprint or Trigger Self operator invokes this blueprint. Trigger argument is available through Get Trigger Argument."},jo={type:"object",additionalProperties:!1,required:["enabled"],description:"Wait while active for generic GET/POST /:tabId/trigger HTTP calls. Request method, URL, parsed body, headers, and timestamp become trigger argument. Webhook URL is `${status.backendUrl}/${encodeURIComponent(blueprint.id)}/trigger` and runs only while blueprint is active in explore mode.",properties:{enabled:Pt.properties.enabled,timeoutMs:{type:"integer",minimum:1,description:"Maximum synchronous webhook execution time in milliseconds. Backend uses 30000 when omitted or below 1."},contentType:{type:"string",enum:Mo,description:"Request body parser. Omit or use auto to infer from incoming Content-Type, then fall back to JSON sniffing, UTF-8 text, then binary. Not for integration webhook resources such as ShopifyWebhook or GorgiasEvent; those use executor."}}},Uo={...Pt,description:"Use for managed integration resources where runtime owns stream, event, webhook, or poll lifecycle, such as ApacheKafkaTopic, RabbitMQStream, ShopifyWebhook, GorgiasEvent, GmailMessage, GmailThread, GmailEvent, BaseEventCollection, and MQTTTopic."},et={type:"object",additionalProperties:!1,minProperties:1,maxProperties:1,description:"Exactly one trigger branch. For executionKind=managed from integration_blueprint_contexts_list, use executor. For executionKind=finite, choose manual for ad hoc/sample/start-once runs, cron for scheduled refresh, loop for fixed-delay polling, blueprint for invocation by another blueprint, or webhook for generic GET/POST /:tabId/trigger HTTP calls.",properties:{manual:$o,cron:Fo,loop:Wo,blueprint:qo,webhook:jo,executor:Uo},oneOf:[{required:["manual"]},{required:["cron"]},{required:["loop"]},{required:["blueprint"]},{required:["webhook"]},{required:["executor"]}]};var Lo={type:"object",additionalProperties:!1,required:["literal"],properties:{literal:{description:"Literal JSON value for this input element; null is valid when connected upstream."},nodeId:{...u,description:"Upstream node id when this value is connected to another node output."},operatorInputId:{...u,description:"Upstream output pin name used by this connection."},nodeInputIndex:{...u,description:'CRDT list index of upstream output value. Use "0.5" for any connected node output.'}}},Jo={type:"object",additionalProperties:!1,required:["values"],properties:{isArray:{...ge,description:"Whether input accepts multiple values for one operator input."},values:{type:"object",additionalProperties:Lo,description:"Input values keyed by CRDT list index strings."},type:{type:"string",enum:me,description:"Resolved input type override."},forceZipping:{...ge,description:"Force list zipping behavior for multiple upstream values."}}},Vo={type:"object",additionalProperties:!1,required:["id","operatorId","inputs"],properties:{id:{...u,description:"Stable node id; must match key in blueprint nodes record."},operatorId:{...u,description:"Id of registered blueprint operator this node executes."},inputs:{type:"object",additionalProperties:Jo,description:"Node inputs keyed by operator input name."},mockNever:{...ge,description:"Disable mocking for this node while testing."},skipBehavior:{type:"string",enum:["skip","null"],description:"Behavior when upstream value is skipped."},disabled:{...ge,description:"Whether this node and downstream dependent nodes are disabled."},outputType:{type:"string",enum:me,description:"Resolved output type for wildcard operators."}}},zo={type:"object",additionalProperties:!1,required:["type","trigger"],properties:{type:Xe,trigger:et,config:Ye}},Tn=x("blueprints","frontend/src/tabs/blueprint/types.ts:Blueprint",{required:["id","mode","nodes","context"],properties:{id:{...u,description:"Blueprint tab id; must match tabs resource id."},updatedAt:I,mode:{type:"string",enum:["test","explore"],description:'Execution mode; result id is blueprint id plus "-test" or "-explore".'},nodes:{type:"object",additionalProperties:Vo,description:"Blueprint nodes keyed by node id."},context:zo,testRecordsAmount:{...yn,description:"Target number of test records to keep for test mode."},recomputeOnChange:{type:"string",enum:["always","manual"],description:"Whether edits automatically restart execution."},mockNever:{...N,description:"Global flag to disable node mocking while testing."},desiredState:{type:"string",enum:["active","inactive"],description:"Requested runtime state for test or explore mode."}}});var Go=["Aerospike","ApacheKafka","MQTT","Kaggle","FacebookAds","RabbitMQ","Shopify","YouTube","Webshare","Playwright","AWS","Qdrant","OpenAI","BaseVector","BaseEvent","BaseLookup","Gorgias","LMStudio","OpenRouter","VoyageAI","GoogleDrive","GoogleSheets","Gmail","DiscordChannelWebhook"],Sn=x("connections","frontend/src/integrations/types.ts:Connection",{required:["id","label","type","spaceId"],properties:{id:u,updatedAt:I,label:u,type:{type:"string",enum:Go},spaceId:u}});var In=x("roles","frontend/src/auth/roles/types.ts:Role",{required:["id","label","authorizations"],properties:{id:u,updatedAt:I,label:u,authorizations:Ze}});var xn=x("schemas","frontend/src/integrations/types.ts:Schema",{required:["id","type","connectionId","path","schema"],properties:{id:u,updatedAt:I,type:{type:"string",enum:wn},connectionId:u,path:bn,schema:{type:"object",additionalProperties:{type:"string",enum:me}},keySerdeType:{type:"string"},valueSerdeType:{type:"string"}}});var vn=x("space-join-requests","frontend/src/spaces/space-join-requests/types.ts:SpaceJoinRequest",{required:["id","createdAt","requestedBy","kind","status","spaceId","userId"],properties:{id:u,createdAt:{type:"number",description:"Nanoseconds since Unix epoch."},updatedAt:I,requestedBy:u,kind:{type:"string",enum:["invite","request"]},status:{type:"string",enum:["pending","granted","denied"]},spaceId:u,userId:u}});var Bn=x("spaces","frontend/src/spaces/types.ts:Space",{required:["id","label"],properties:{id:u,updatedAt:I,label:u,thumbnailUrl:u,description:u,isUserSpace:ge}});var Pn=x("tabs","frontend/src/tabs/types.ts:Tab",{required:["id","name","order","type","parent","spaceId"],properties:{id:{...u,description:"Stable tab id. Blueprint tabs normally have matching blueprints and blueprint-views records keyed by this id."},updatedAt:I,name:u,order:re,type:{type:"string",enum:["blueprint","folder"],description:"Navigation item kind; blueprint tabs normally have matching blueprints and blueprint-views records."},parent:u,spaceId:u}});var En=x("user-locations","frontend/src/workspace/user-location/types.ts:UserLocation",{required:["id"],properties:{id:u,updatedAt:I,blueprint:{type:"object",additionalProperties:!1,required:["id"],properties:{id:u,worldPosition:{type:"object",additionalProperties:!1,required:["x","y"],properties:{x:re,y:re}}}}}});var Nn=x("users","frontend/src/auth/users/types.ts:User",{required:["id","displayName","roleIds","authorizations","spaces"],properties:{id:u,updatedAt:I,displayName:u,avatarUrl:u,roleIds:vt,authorizations:Ze,spaces:vt}});var tt=[Nn,In,Bn,Pn,Sn,xn,Tn,kn,Rn,En,vn];function nt(t){return tt.find(e=>e.resource===t)}var Et=[U("users","Workspace users and authorizations.",!0),U("roles","Workspace roles and resource authorizations.",!0),U("spaces","Workspace spaces.",!0),U("tabs","Tabs and folders visible to authorized user; blueprint tabs normally share an id with blueprints and blueprint-views records.",!0),U("connections","Read-only integration connections without secret-bearing config; config is redacted and cannot be read through MCP.",!1),U("schemas","Integration schema metadata.",!0),U("blueprints","Blueprint definitions keyed by matching blueprint tab id.",!0),U("blueprint-views","Blueprint editor view state keyed by matching blueprint tab id.",!0),U("blueprint-operators","Registered blueprint operator definitions.",!1),U("user-locations","Live user location records.",!0),U("space-join-requests","Space invitation and join requests.",!0)],Ko=["tabs","blueprints","blueprint-views"],Nt=new Set(Ko),he=Et.filter(t=>!Nt.has(t.name)),Ne=he.map(t=>t.name),An=Et.map(t=>t.name);function Qo(t){return Et.find(e=>e.name===t)}function Dn(t){return he.find(e=>e.name===t)}function On(t){if(Qo(t))return t;throw new Error(`unsupported resource: ${t}`)}function At(t){if(Nt.has(t))throw new Error(`dedicated resource ${t}: use tab and blueprint intent tools instead of generic resource_* tools`);if(Dn(t))return t;throw new Error(`unsupported resource: ${t}`)}function Dt(t){let e=Dn(t);if(Nt.has(t))throw new Error(`dedicated resource ${t}: use tab and blueprint intent tools instead of generic resource_* tools`);if(!e)throw new Error(`unsupported resource: ${t}`);if(!e.writable)throw new Error(`resource is read-only: ${t}`);return e.name}function U(t,e,n){return{name:t,description:e,writable:n,schemaUri:`${xt}${t}`}}function z(){return Date.now()*1e6}function Ct(t,e){if(t===null&&e===null)return{pre:null,post:null};if(t===null&&e!==null)return{pre:null,post:e};if(t!==null&&e===null)return{pre:t,post:null};if(typeof t!="object"||typeof e!="object")return t!==e?{pre:t,post:e}:{pre:null,post:null};if(Array.isArray(t)||Array.isArray(e))return{pre:null,post:null};let{pre:n,post:r}=Cn(t,e);return n===null&&r===null?{pre:null,post:null}:{pre:n,post:r}}function Cn(t,e){let n={},r={},o=!1,i=new Set([...V(t),...V(e)]);for(let s of i){if(s==="updatedAt")continue;let a=t[s],c=e[s];if(Array.isArray(a)||Array.isArray(c))continue;let d=oe(a),l=oe(c);if(!(s in e))d||(n[s]=a,r[s]=null,o=!0);else if(!(s in t))l||(n[s]=null,r[s]=c,o=!0);else{if(d&&l)continue;if(d&&!l)n[s]=null,r[s]=c,o=!0;else if(!d&&l)n[s]=a,r[s]=null,o=!0;else{let{pre:h,post:y}=Ho(a,c);(h!==void 0||y!==void 0)&&(h!==void 0&&(n[s]=Ot(h)),y!==void 0&&(r[s]=Ot(y)),o=!0)}}}return o?V(n).length===0&&V(r).length===0?{pre:null,post:null}:V(n).length===0?{pre:null,post:r}:V(r).length===0?{pre:n,post:null}:{pre:n,post:r}:{pre:null,post:null}}function Ho(t,e){if(Zo(t,e))return{pre:void 0,post:void 0};let n=oe(t),r=oe(e);if(n&&r)return{pre:void 0,post:void 0};if(n)return{pre:null,post:e};if(r)return{pre:t,post:null};if(Array.isArray(t)||Array.isArray(e))return{pre:void 0,post:void 0};if(typeof t!=typeof e)return{pre:t,post:e};if(typeof t=="object"&&t!==null&&typeof e=="object"&&e!==null){let{pre:o,post:i}=Cn(t,e);return o===null&&i===null?{pre:void 0,post:void 0}:{pre:o===null?void 0:o,post:i===null?void 0:i}}return{pre:t,post:e}}function oe(t){return t==null?!0:typeof t=="object"&&t!==null?Array.isArray(t)?t.length===0:V(t).length===0:!1}function Zo(t,e){return oe(t)&&oe(e)?!0:_t(t,e)}function _t(t,e){if(t===e)return!0;if(t==null||e==null||typeof t!="object"||typeof e!="object")return!1;let n=V(t),r=V(e);if(n.length!==r.length)return!1;for(let o of n)if(!(o in e)||!_t(t[o],e[o]))return!1;return!0}function rt(t,e){return e.pre===null?t===null:t===null||typeof t!="object"||Array.isArray(t)?!1:_n(t,e.pre)}function _n(t,e){for(let n in e)if(n!=="updatedAt"&&!Xo(t[n],e[n]))return!1;return!0}function Xo(t,e){return e===null||Yo(e)?oe(t):t===void 0?!1:typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof t=="object"&&t!==null&&!Array.isArray(t)?_n(t,e):_t(t,e)}function Yo(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&V(t).length===0}function Ot(t){if(t==null)return null;if(typeof t=="object"&&t!==null){if(Array.isArray(t)&&t.length===0)return null;if(!Array.isArray(t)){let e={},n=!1;for(let r in t)e[r]=Ot(t[r]),e[r]!==void 0&&(n=!0);return n?e:null}}return t}function Mt(t,e){let n=$t(t,e);return n!==null&&typeof n=="object"&&!Array.isArray(n)&&(n.updatedAt=e.updatedAt),n}function $t(t,e){return e.post===null?null:t===null?e.post:typeof t!="object"||Array.isArray(t)?e.post:Mn(t,e.post)}function Mn(t,e){let n={};for(let r in t)if(r in e){let o=e[r];if(o===null)continue;typeof o=="object"&&!Array.isArray(o)&&typeof t[r]=="object"&&!Array.isArray(t[r])&&t[r]!==null?n[r]=Mn(t[r],o):n[r]=o}else n[r]=t[r];for(let r in e)!(r in t)&&e[r]!==null&&(n[r]=e[r]);return n}function V(t){let e=[];for(let n in t)e.push(n);return e}var $n="replicated-state",ot=class{ackedResources={};dirtyResources={};unauthorizedKeys={};loadingResources={};loadingPromises=new Map;loadedResources=new Set;registeredResources=new Set;resourceChangeListeners=new Set;snapshotWaiters=new Map;storage;socketSession;logger;inflightItems=new Map;constructor(e,n,r){this.storage=e,this.socketSession=n,this.logger=r}onResourceChange(e){return this.resourceChangeListeners.add(e),()=>this.resourceChangeListeners.delete(e)}registerResource(e){this.registeredResources.add(e),this.initializeResource(e)}isResourceRegistered(e){return this.registeredResources.has(e)}getRegisteredResources(){return Array.from(this.registeredResources)}setDirtyItems(e,n){this.registerResource(e),this.dirtyResources[e]=C(n)}setDirtyItem(e,n,r){if(this.registerResource(e),r===void 0){delete this.dirtyResources[e][n];return}this.dirtyResources[e][n]=C(r)}clearSessionState(){this.ackedResources={},this.loadingResources={},this.loadingPromises.clear(),this.loadedResources.clear(),this.inflightItems.clear();for(let e of this.registeredResources)this.dirtyResources[e]={},this.unauthorizedKeys[e]={},this.loadingResources[e]=!0,this.emitResourceChange(e)}async loadRegisteredResourcesFromStorage(){await Promise.all(Array.from(this.registeredResources,e=>this.loadResourceFromStorage(e)))}async hydrate(e,n){this.registerResource(e),await this.loadResourceFromStorage(e),this.logger.info(`Calculating lastUpdatedAtSeen from ${Wn(this.ackedResources[e])} items`);let r=this.prepareSnapshotQuery(e,n);this.logger.info(`\u{1F4F8} ${e} requested with query:`,r),this.socketSession.send($n,{resource:e,action:"snapshot",value:r})}hydrateAll(e){return this.hydrate(e,{all:!0})}async waitForSnapshot(e,n){await new Promise((r,o)=>{let i,s=()=>{clearTimeout(i),r()};i=setTimeout(()=>{this.snapshotWaiters.get(e)?.delete(s),o(new Error(`snapshot timeout for ${e}`))},n),this.snapshotWaiters.has(e)||this.snapshotWaiters.set(e,new Set),this.snapshotWaiters.get(e).add(s)})}processSocketEvent(e){switch(e.action){case"snapshot":this.applySnapshot(e.resource,e.value??{});break;case"delta":this.applyRemoteDelta(e);break}}async upsertItem(e,n){this.registerResource(e);let r=this.getAckedValue(e,n.id),o=Ct(r,n);return o.pre===null&&o.post===null?!0:this.sendDelta(e,n.id,o,n)}async deleteItem(e,n){this.registerResource(e);let r=this.getAckedValue(e,n),o=Ct(r,null);return o.pre===null&&o.post===null?!0:this.sendDelta(e,n,o,null)}isItemInflight(e,n){return this.inflightItems.get(e)?.has(n)===!0}async sendDelta(e,n,r,o){this.registerResource(e),this.inflightItems.has(e)||this.inflightItems.set(e,new Set);let i=this.inflightItems.get(e);if(i.has(n))return!1;let s=this.getDirtyValue(e,n);rt(s,r)&&(arguments.length>=4?this.setDirtyValue(e,n,C(o)):this.setDirtyValue(e,n,$t(s,C(r))),this.emitResourceChange(e)),i.add(n);let a;try{a=await this.socketSession.sendWithAck($n,{resource:e,action:"delta",key:n,value:r})}catch(c){a={ok:!1,reason:c instanceof Error?c.message:"error"}}return i.delete(n),a.ok?!0:(this.revertDirtyToAckedValue(e,n),this.emitResourceChange(e),this.logger.error(`!ack[${e}] Reverting to acked state for ${e}:${n}`,a.reason),!1)}getAckedValue(e,n){return this.initializeResource(e),this.ackedResources[e][n]??null}getDirtyValue(e,n){return this.initializeResource(e),this.dirtyResources[e][n]??null}getVisibleItems(e){this.initializeResource(e);let n={};for(let r in this.dirtyResources[e]){let o=this.dirtyResources[e][r];o!=null&&(n[r]=o)}return n}getRawItems(e){return this.initializeResource(e),C(this.dirtyResources[e])}getAckedItems(e){return this.initializeResource(e),C(this.ackedResources[e])}getUnauthorizedKeys(e){return this.initializeResource(e),C(this.unauthorizedKeys[e])}isResourceLoading(e){return this.initializeResource(e),this.loadingResources[e]}initializeResource(e){this.ackedResources[e]===void 0&&(this.ackedResources[e]={}),this.dirtyResources[e]===void 0&&(this.dirtyResources[e]={}),this.unauthorizedKeys[e]===void 0&&(this.unauthorizedKeys[e]={}),this.loadingResources[e]===void 0&&(this.loadingResources[e]=!0)}prepareSnapshotQuery(e,n){this.initializeResource(e);let r=C(n);if(r.lastUpdatedAtSeen!==void 0)return r;let o=this.buildLastUpdatedAtSeen(e,r);return Fn(o)||(r.lastUpdatedAtSeen=o),r}async loadResourceFromStorage(e){if(this.initializeResource(e),this.loadedResources.has(e))return;if(this.loadingPromises.has(e))return this.loadingPromises.get(e);let n=this.loadResourceItemsFromStorage(e);this.loadingPromises.set(e,n);try{await n}finally{this.loadingPromises.delete(e),this.loadedResources.add(e)}}async loadResourceItemsFromStorage(e){let n=!1,r=0;try{let o=await this.storage.loadItems(e);if(o&&Fn(this.ackedResources[e])){n=!0;for(let i in o)this.applyCachedItem(e,i,o[i])&&(r+=1)}}catch(o){this.logger.warn(`Failed to load cached ${e}: ${String(o)}`)}finally{this.loadingResources[e]=!1,this.emitResourceChange(e),n?this.logger.info(`\u{1F4C2} ${r}x ${e} from cache`):this.logger.info(`\u{1F4C2} no cached data for ${e}`)}}applyCachedItem(e,n,r){return r===null?(this.ackedResources[e][n]=null,this.dirtyResources[e][n]=null,!0):r==="unauthorized"?(this.unauthorizedKeys[e][n]=!0,!1):(this.ackedResources[e][n]=C(r),this.dirtyResources[e][n]=C(r),!0)}applySnapshot(e,n){this.initializeResource(e);for(let r in n){let o=n[r];o===null?(this.ackedResources[e][r]=null,this.dirtyResources[e][r]=null,delete this.unauthorizedKeys[e][r]):o==="unauthorized"?(delete this.ackedResources[e][r],delete this.dirtyResources[e][r],this.unauthorizedKeys[e][r]=!0):(this.ackedResources[e][r]=C(o),this.dirtyResources[e][r]=C(o),delete this.unauthorizedKeys[e][r]),this.storage.persistItem(e,r,o).catch(i=>{this.logger.warn(`Failed to persist ${e}:${r}: ${String(i)}`)})}this.loadingResources[e]=!1,this.emitResourceChange(e),this.logger.info(`\u{1F4F8} ${Wn(n)}x ${e} `),this.resolveSnapshotWaiters(e)}applyRemoteDelta(e){let n=e.resource,r=e.key;if(!r)return;this.initializeResource(n);let o=e.value,i={pre:o.pre,post:o.post},s=this.getAckedValue(n,r);if(!rt(s,i))this.logger.error(`\u{1D6AB}S precondition invalid on last acked for ${n}:${r}`,{pre:i.pre,post:i.post,current:s});else{let c=Mt(s,C(o));this.ackedResources[n][r]=c,this.storage.persistItem(n,r,c).catch(d=>{this.logger.warn(`Failed to persist ${n}:${r}: ${String(d)}`)}),this.logger.info(Ft(`\u{1D6AB}S[${n}] acked`,i))}let a=this.getDirtyValue(n,r);e.by!==this.socketSession.getSessionId()?rt(a,i)?i.post===null?(this.dirtyResources[n][r]=null,this.logger.info(Ft(`\u{1D6AB}S[${n}] dirty`,i))):(this.dirtyResources[n][r]=Mt(a,C(o)),this.logger.info(Ft(`\u{1D6AB}S[${n}] dirty`,i))):(this.logger.warn(`Skip delta on dirty for ${n}:${r}`,{pre:i.pre,post:i.post,current:s}),this.revertDirtyToAckedValue(n,r)):i.post!=null&&a!=null&&typeof a=="object"&&(a.updatedAt=o.updatedAt,this.dirtyResources[n][r]=a,this.logger.info(`\u{1D6AB}S[${n}] dirty updatedAt for ${r}`)),this.emitResourceChange(n)}buildLastUpdatedAtSeen(e,n){let r=this.ackedResources[e],o={};if(n.all){for(let i in r)this.copyItemUpdatedAt(r[i],i,o);return o}if(n.keys&&n.keys.length>0)for(let i of n.keys)this.copyItemUpdatedAt(r[i],i,o);return o}copyItemUpdatedAt(e,n,r){e&&typeof e=="object"&&typeof e.updatedAt=="number"&&(r[n]=e.updatedAt)}setDirtyValue(e,n,r){if(r===null){this.dirtyResources[e][n]=null;return}this.dirtyResources[e][n]=r}revertDirtyToAckedValue(e,n){let r=this.ackedResources[e][n];if(r===void 0){delete this.dirtyResources[e][n];return}if(r===null){this.dirtyResources[e][n]=null;return}this.dirtyResources[e][n]=C(r)}emitResourceChange(e){let n={resource:e,acked:this.getAckedItems(e),dirty:this.getRawItems(e),unauthorized:this.getUnauthorizedKeys(e),loading:this.loadingResources[e]};for(let r of this.resourceChangeListeners)r(n)}resolveSnapshotWaiters(e){let n=this.snapshotWaiters.get(e);if(n){this.snapshotWaiters.delete(e);for(let r of n)r()}}};function C(t){if(t===void 0)return t;if(typeof structuredClone=="function")try{return structuredClone(t)}catch{}try{return JSON.parse(JSON.stringify(t))}catch{return t}}function Fn(t){for(let e in t)return!1;return!0}function Wn(t){let e=0;for(let n in t)e+=1;return e}function Ft(t,e){return`${t}
19
+ `),this.database)}};function gn(t){let e=t??"unknown-user";return Bo.createHash("sha256").update(e).digest("hex")}function hn(t,e,n){let r=t.replace(/^http/,"ws"),o=encodeURIComponent(e),i=encodeURIComponent(n);return`${r}/base/${o}/${i}`}var He=class{websocket;sessionId=ze();backendUrl;accessToken;channelListeners=new Map;disconnectListeners=new Set;ackWaiters=new Map;intentionallyClosed=!1;constructor(e,n){this.backendUrl=e,this.accessToken=n}async connect(e){this.intentionallyClosed=!1,this.sessionId=ze();let n=hn(this.backendUrl,this.accessToken,this.sessionId),r=new WebSocket(n,"echo");this.websocket=r,await new Promise((o,i)=>{let s=setTimeout(()=>i(new Error("websocket open timeout")),e);r.onopen=()=>{clearTimeout(s),o()},r.onerror=()=>{clearTimeout(s),i(new Error("websocket open failed"))}}),r.onmessage=o=>this.processMessage(o.data),r.onclose=()=>this.processClose(),r.onerror=()=>this.processClose()}getSessionId(){return this.sessionId}send(e,n){if(!this.websocket||this.websocket.readyState!==WebSocket.OPEN)throw new Error("gateway websocket not connected");this.websocket.send(`${e};${JSON.stringify(n)}`)}sendWithAck(e,n,r=5e3){let o=ze(),i={...n,eventId:o};return new Promise(s=>{let a=setTimeout(()=>{this.ackWaiters.delete(o),s({ok:!1,reason:"timeout"})},r);this.ackWaiters.set(o,{resolve:s,timeout:a}),this.send(e,i)})}onChannel(e,n){return this.channelListeners.has(e)||this.channelListeners.set(e,new Set),this.channelListeners.get(e).add(n),()=>this.channelListeners.get(e)?.delete(n)}onDisconnected(e){return this.disconnectListeners.add(e),()=>this.disconnectListeners.delete(e)}waitForChannelEvent(e,n,r){return new Promise((o,i)=>{let s=setTimeout(()=>{a(),i(new Error(`channel event timeout: ${e}`))},r),a=this.onChannel(e,c=>{n(c)&&(clearTimeout(s),a(),o(c))})})}collectChannelEvents(e,n,r,o){return new Promise((i,s)=>{let a=[],c,d=setTimeout(()=>{h(),c&&clearTimeout(c),s(new Error(`channel event timeout: ${e}`))},r),l=()=>{clearTimeout(d),h(),i(a)},h=this.onChannel(e,y=>{n(y)&&(a.push(y),c&&clearTimeout(c),c=setTimeout(l,o))})})}close(){this.intentionallyClosed=!0,this.websocket?.close(),this.websocket=void 0;for(let e of this.ackWaiters.values())clearTimeout(e.timeout),e.resolve({ok:!1,reason:"closed"});this.ackWaiters.clear()}processMessage(e){let n=typeof e=="string"?e:"",r=n.indexOf(";");if(r===-1)return;let o=n.slice(0,r),i=n.slice(r+1),s;try{s=JSON.parse(i)}catch{return}if(o.startsWith("ack:")){this.resolveAck(o.slice(4),s);return}s=Ao(s);let a=this.channelListeners.get(o);if(a)for(let c of a)c(s)}resolveAck(e,n){let r=this.ackWaiters.get(e);r&&(this.ackWaiters.delete(e),clearTimeout(r.timeout),r.resolve(n.value??{ok:!1}))}processClose(){if(!this.intentionallyClosed)for(let e of this.disconnectListeners)e()}};function Ao(t){if(t.resource!=="connections")return t;switch(t.action){case"snapshot":return{...t,value:Do(t.value)};case"delta":return{...t,value:Oo(t.value)};default:return t}}function Do(t){if(!xt(t))return t;let e={};for(let n in t)e[n]=bn(t[n]);return e}function Oo(t){return xt(t)?{...t,pre:yn(t.pre),post:yn(t.post)}:t}function yn(t){return t===null?null:bn(t)}function bn(t){if(!xt(t))return t;let e={...t};return delete e.config,e}function xt(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}var vt="beepflow://resource-schemas/",I={type:"number",description:"Nanoseconds since Unix epoch. Omit updatedAt on creates and manual edits unless preserving an existing value; replicated state updates it after accepted writes."},u={type:"string"},re={type:"number"},wn={type:"integer"},N={type:"boolean"};var Rn={type:"object",additionalProperties:u},Bt={type:"object",additionalProperties:N},Ze={type:"object",additionalProperties:{type:"object",additionalProperties:N,properties:{list:N,detail:N,create:N,edit:N,delete:N,authorize:N}}},me=["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"],kn=["ManualTick","AerospikeSet","ApacheKafkaTopic","MQTTTopic","KaggleFile","RabbitMQQueue","RabbitMQStream","ShopifyWebhook","QdrantCollection","BaseVectorCollection","BaseEventCollection","BaseLookupCollection","GorgiasEvent","GorgiasTicket","GoogleDriveFile","GmailMessage","GmailThread","GmailEvent"],ge={anyOf:[N,{type:"null"}]},Co=["Use resource_query first when editing existing items; upsert sends whole item state, not a JSON patch. Preserve unchanged fields.","Omit updatedAt on creates and manual edits unless preserving an existing value; replicated state updates it after accepted writes."];function x(t,e,n){let r=`${vt}${t}`;return{resource:t,uri:r,sourceType:e,notes:Co,itemSchema:{$schema:"https://json-schema.org/draft/2020-12/schema",title:`Beepflow ${t} item`,type:"object",additionalProperties:!1,required:n.required,properties:n.properties,...n.defs?{$defs:n.defs}:{}}}}var Pt={$ref:"#/$defs/operatorType"},_o={type:"object",additionalProperties:!1,required:["value"],properties:{value:{description:"Raw option value written to node input literal when selected."},label:{...u,description:"Optional label shown in operator input dropdowns."}}},Mo={type:"object",additionalProperties:!1,required:["type"],properties:{type:{type:"string",enum:me,description:'Blueprint value type name. Use "list of X" for lists, never "list".'},options:{anyOf:[{type:"array",items:_o},{type:"null"}],description:"Allowed literal values for dropdown-style widgets."},isArray:{type:"boolean",description:"Whether this pin accepts multiple values."},allowedTypes:{anyOf:[{type:"array",items:Pt},{type:"null"}],description:"Allowed concrete types for wildcard pins."},linkType:{...u,description:"Type-linking group used to propagate wildcard types across pins."},widgetType:{...u,description:'Frontend input widget id. Supports built-in widgets, integration selectors, and "<IntegrationType>-connection" connection dropdowns.'},defaultValue:{description:"Default literal value used when node input omits a value."},defaultValueForArrayElement:{description:"Default literal value for newly added array input elements."}}},$o={type:"object",additionalProperties:!1,required:["name","doc","type"],properties:{name:{...u,description:"Output pin name."},doc:{...u,description:"Operator output documentation shown to users."},type:Pt}},Fo={type:"object",additionalProperties:!1,required:["name","doc","type"],properties:{name:{...u,description:"Input pin name; node inputs are keyed by this value."},doc:{...u,description:"Operator input documentation shown to users."},type:Pt,isLiteral:{...N,description:"Whether this input must be edited as literal value instead of upstream connection."}}},Tn=x("blueprint-operators","frontend/src/tabs/blueprint/types.ts:Operator",{required:["id","type","name","doc","categoryPath","inputs"],properties:{id:{...u,description:"Stable registered operator id referenced by blueprint nodes."},type:{...u,description:"Operator kind, usually function, variable, or localVariable."},name:{...u,description:"Display name used in operator search and node labels."},aliases:{type:"array",items:u,description:"Additional search terms for this operator."},doc:{...u,description:"Operator documentation shown to users."},categoryPath:{type:"array",items:u,description:"Menu category path segments."},inputs:{type:"array",items:Fo,description:"Input pins in display order."},output:{anyOf:[$o,{type:"null"}],description:"Output pin definition, or null for side-effect-only operators."},isDeprecated:{...N,description:"Whether operator is deprecated and hidden from default search."},hidden:{...N,description:"Whether operator is hidden from menus and search."},canMock:{...N,description:"Whether test mode can mock this operator."},updatedAt:I},defs:{operatorType:Mo}});var Wo={type:"object",additionalProperties:!1,properties:{x:{...re,description:"Optional node world x coordinate in blueprint editor. For new nodes, never specify style.x; omit it so the frontend can place nodes after measuring dimensions."},y:{...re,description:"Optional node world y coordinate in blueprint editor. For new nodes, never specify style.y; omit it so the frontend can place nodes after measuring dimensions."},title:{...u,description:"Optional display title shown on node."},comment:{...u,description:"Optional user-authored node comment."}}},qo={type:"object",additionalProperties:!0,description:"Blueprint view node. For new nodes, never specify style.x or style.y; omit coordinates so the frontend can place nodes after measuring dimensions. Known visualization blocks are intentionally accepted as additional properties.",required:["id"],properties:{id:{...u,description:"Node id; must match key in blueprint view nodes record."},style:Wo}},Sn=x("blueprint-views","frontend/src/tabs/blueprint/types.ts:BlueprintView",{required:["id","nodes"],properties:{id:{...u,description:"Blueprint tab id; must match tabs and blueprints resource id."},updatedAt:I,nodes:{type:"object",additionalProperties:qo,description:"Editor view state keyed by node id."}}});var Ye={type:"string",description:"Integration resource type processed by this blueprint, such as ApacheKafkaTopic or QdrantCollection. Call integration_blueprint_contexts_list first; use only resource types returned by that tool. The returned executionKind determines trigger choice: managed resources use executor, finite resources use manual/cron/loop/blueprint/webhook based on user intent."},et={type:"object",additionalProperties:!0,description:"Integration-specific config for context.type. Start from contextTemplate.config returned by integration_blueprint_contexts_list, fill every configFields item where required=true, and preserve optional defaults such as consumerGroupId, clientId, parser, offsetResetStrategy, orderBy, or webhook topic maps when provided."},tt={type:"object",additionalProperties:!1,required:["enabled"],properties:{enabled:{type:"boolean",description:"Must be true. Backend ignores this trigger branch when enabled is false."}}},Et={...tt.properties.enabled,enum:[!0]},jo=["auto","application/json","text/plain","text/html","application/xml","application/x-www-form-urlencoded","multipart/form-data","application/octet-stream"],Uo={type:"object",additionalProperties:!1,required:["count"],description:"Run immediately when explore runtime starts or restarts. Use for finite resource sampling, one-shot imports, and ad hoc reads.",properties:{count:{type:"integer",minimum:1,description:"Number of executions to run back-to-back. Frontend default is 1; backend coerces values below 1 to 1."}}},Lo={type:"object",additionalProperties:!1,required:["expression"],description:"Run on a seconds-field cron schedule while explore runtime is active. Use for scheduled finite-resource refreshes.",properties:{expression:{type:"string",description:"Cron expression with six fields including seconds, parsed by robfig/cron. Example: 0 */5 * * * * runs every five minutes."},timezone:{type:"string",description:"Optional IANA timezone name such as UTC or America/New_York. Backend uses UTC when omitted or empty."}}},Jo={type:"object",additionalProperties:!1,required:["delayMs"],description:"Run immediately, then wait delayMs before repeating while explore runtime is active. Use only for deliberate fixed-delay polling.",properties:{delayMs:{type:"integer",minimum:1,description:"Delay between executions in milliseconds. Must be positive to avoid a hot loop."}}},In={...tt,description:"Wait while active until another blueprint or Trigger Self operator invokes this blueprint. Trigger argument is available through Get Trigger Argument."},Nt={type:"object",additionalProperties:!1,required:["enabled"],description:"Wait while active for generic GET/POST /:tabId/trigger HTTP calls. Request method, URL, parsed body, headers, and timestamp become trigger argument. Webhook URL is `${status.backendUrl}/${encodeURIComponent(blueprint.id)}/trigger` and runs only while blueprint is active in explore mode.",properties:{enabled:tt.properties.enabled,timeoutMs:{type:"integer",minimum:1,description:"Maximum synchronous webhook execution time in milliseconds. Backend uses 30000 when omitted or below 1."},contentType:{type:"string",enum:jo,description:"Request body parser. Omit or use auto to infer from incoming Content-Type, then fall back to JSON sniffing, UTF-8 text, then binary. Not for integration webhook resources such as ShopifyWebhook or GorgiasEvent; those use executor."}}},xn={...tt,description:"Use for managed integration resources where runtime owns stream, event, webhook, or poll lifecycle, such as ApacheKafkaTopic, RabbitMQStream, ShopifyWebhook, GorgiasEvent, GmailMessage, GmailThread, GmailEvent, BaseEventCollection, and MQTTTopic."},Xe={type:"object",additionalProperties:!1,minProperties:1,maxProperties:1,description:"Exactly one trigger branch. For executionKind=managed from integration_blueprint_contexts_list, use executor. For executionKind=finite, choose manual for ad hoc/sample/start-once runs, cron for scheduled refresh, loop for fixed-delay polling, blueprint for invocation by another blueprint, or webhook for generic GET/POST /:tabId/trigger HTTP calls.",properties:{manual:Uo,cron:Lo,loop:Jo,blueprint:In,webhook:Nt,executor:xn},oneOf:[{required:["manual"]},{required:["cron"]},{required:["loop"]},{required:["blueprint"]},{required:["webhook"]},{required:["executor"]}]},vn={...Xe,properties:{...Xe.properties,blueprint:{...In,properties:{enabled:Et}},webhook:{...Nt,properties:{...Nt.properties,enabled:Et}},executor:{...xn,properties:{enabled:Et}}}};var Vo={type:"object",additionalProperties:!1,required:["literal"],properties:{literal:{description:"Literal JSON value for this input element; null is valid when connected upstream."},nodeId:{...u,description:"Upstream node id when this value is connected to another node output."},operatorInputId:{...u,description:"Upstream output pin name used by this connection."},nodeInputIndex:{...u,description:'CRDT list index of upstream output value. Use "0.5" for any connected node output.'}}},zo={type:"object",additionalProperties:!1,required:["values"],properties:{isArray:{...ge,description:"Whether input accepts multiple values for one operator input."},values:{type:"object",additionalProperties:Vo,description:"Input values keyed by CRDT list index strings."},type:{type:"string",enum:me,description:"Resolved input type override."},forceZipping:{...ge,description:"Force list zipping behavior for multiple upstream values."}}},Go={type:"object",additionalProperties:!1,required:["id","operatorId","inputs"],properties:{id:{...u,description:"Stable node id; must match key in blueprint nodes record."},operatorId:{...u,description:"Id of registered blueprint operator this node executes."},inputs:{type:"object",additionalProperties:zo,description:"Node inputs keyed by operator input name."},mockNever:{...ge,description:"Disable mocking for this node while testing."},skipBehavior:{type:"string",enum:["skip","null"],description:"Behavior when upstream value is skipped."},disabled:{...ge,description:"Whether this node and downstream dependent nodes are disabled."},outputType:{type:"string",enum:me,description:"Resolved output type for wildcard operators."}}},Ko={type:"object",additionalProperties:!1,required:["type","trigger"],properties:{type:Ye,trigger:vn,config:et}},Bn=x("blueprints","frontend/src/tabs/blueprint/types.ts:Blueprint",{required:["id","mode","nodes","context"],properties:{id:{...u,description:"Blueprint tab id; must match tabs resource id."},updatedAt:I,mode:{type:"string",enum:["test","explore"],description:'Execution mode; result id is blueprint id plus "-test" or "-explore".'},nodes:{type:"object",additionalProperties:Go,description:"Blueprint nodes keyed by node id."},context:Ko,testRecordsAmount:{...wn,description:"Target number of test records to keep for test mode."},recomputeOnChange:{type:"string",enum:["always","manual"],description:"Whether edits automatically restart execution."},mockNever:{...N,description:"Global flag to disable node mocking while testing."},desiredState:{type:"string",enum:["active","inactive"],description:"Requested runtime state for test or explore mode."}}});var Qo=["Aerospike","ApacheKafka","MQTT","Kaggle","FacebookAds","RabbitMQ","Shopify","YouTube","Webshare","Playwright","AWS","Qdrant","OpenAI","BaseVector","BaseEvent","BaseLookup","Gorgias","LMStudio","OpenRouter","VoyageAI","GoogleDrive","GoogleSheets","Gmail","DiscordChannelWebhook"],Pn=x("connections","frontend/src/integrations/types.ts:Connection",{required:["id","label","type","spaceId"],properties:{id:u,updatedAt:I,label:u,type:{type:"string",enum:Qo},spaceId:u}});var En=x("roles","frontend/src/auth/roles/types.ts:Role",{required:["id","label","authorizations"],properties:{id:u,updatedAt:I,label:u,authorizations:Ze}});var Nn=x("schemas","frontend/src/integrations/types.ts:Schema",{required:["id","type","connectionId","path","schema"],properties:{id:u,updatedAt:I,type:{type:"string",enum:kn},connectionId:u,path:Rn,schema:{type:"object",additionalProperties:{type:"string",enum:me}},keySerdeType:{type:"string"},valueSerdeType:{type:"string"}}});var An=x("space-join-requests","frontend/src/spaces/space-join-requests/types.ts:SpaceJoinRequest",{required:["id","createdAt","requestedBy","kind","status","spaceId","userId"],properties:{id:u,createdAt:{type:"number",description:"Nanoseconds since Unix epoch."},updatedAt:I,requestedBy:u,kind:{type:"string",enum:["invite","request"]},status:{type:"string",enum:["pending","granted","denied"]},spaceId:u,userId:u}});var Dn=x("spaces","frontend/src/spaces/types.ts:Space",{required:["id","label"],properties:{id:u,updatedAt:I,label:u,thumbnailUrl:u,description:u,isUserSpace:ge}});var On=x("tabs","frontend/src/tabs/types.ts:Tab",{required:["id","name","order","type","parent","spaceId"],properties:{id:{...u,description:"Stable tab id. Blueprint tabs normally have matching blueprints and blueprint-views records keyed by this id."},updatedAt:I,name:u,order:re,type:{type:"string",enum:["blueprint","folder"],description:"Navigation item kind; blueprint tabs normally have matching blueprints and blueprint-views records."},parent:u,spaceId:u}});var Cn=x("user-locations","frontend/src/workspace/user-location/types.ts:UserLocation",{required:["id"],properties:{id:u,updatedAt:I,blueprint:{type:"object",additionalProperties:!1,required:["id"],properties:{id:u,worldPosition:{type:"object",additionalProperties:!1,required:["x","y"],properties:{x:re,y:re}}}}}});var _n=x("users","frontend/src/auth/users/types.ts:User",{required:["id","displayName","roleIds","authorizations","spaces"],properties:{id:u,updatedAt:I,displayName:u,avatarUrl:u,roleIds:Bt,authorizations:Ze,spaces:Bt}});var nt=[_n,En,Dn,On,Pn,Nn,Bn,Sn,Tn,Cn,An];function rt(t){return nt.find(e=>e.resource===t)}var At=[U("users","Workspace users and authorizations.",!0),U("roles","Workspace roles and resource authorizations.",!0),U("spaces","Workspace spaces.",!0),U("tabs","Tabs and folders visible to authorized user; blueprint tabs normally share an id with blueprints and blueprint-views records.",!0),U("connections","Read-only integration connections without secret-bearing config; config is redacted and cannot be read through MCP.",!1),U("schemas","Integration schema metadata.",!0),U("blueprints","Blueprint definitions keyed by matching blueprint tab id.",!0),U("blueprint-views","Blueprint editor view state keyed by matching blueprint tab id.",!0),U("blueprint-operators","Registered blueprint operator definitions.",!1),U("user-locations","Live user location records.",!0),U("space-join-requests","Space invitation and join requests.",!0)],Ho=["tabs","blueprints","blueprint-views"],Dt=new Set(Ho),he=At.filter(t=>!Dt.has(t.name)),Ne=he.map(t=>t.name),Mn=At.map(t=>t.name);function Zo(t){return At.find(e=>e.name===t)}function $n(t){return he.find(e=>e.name===t)}function Fn(t){if(Zo(t))return t;throw new Error(`unsupported resource: ${t}`)}function Ot(t){if(Dt.has(t))throw new Error(`dedicated resource ${t}: use tab and blueprint intent tools instead of generic resource_* tools`);if($n(t))return t;throw new Error(`unsupported resource: ${t}`)}function Ct(t){let e=$n(t);if(Dt.has(t))throw new Error(`dedicated resource ${t}: use tab and blueprint intent tools instead of generic resource_* tools`);if(!e)throw new Error(`unsupported resource: ${t}`);if(!e.writable)throw new Error(`resource is read-only: ${t}`);return e.name}function U(t,e,n){return{name:t,description:e,writable:n,schemaUri:`${vt}${t}`}}function z(){return Date.now()*1e6}function Mt(t,e){if(t===null&&e===null)return{pre:null,post:null};if(t===null&&e!==null)return{pre:null,post:e};if(t!==null&&e===null)return{pre:t,post:null};if(typeof t!="object"||typeof e!="object")return t!==e?{pre:t,post:e}:{pre:null,post:null};if(Array.isArray(t)||Array.isArray(e))return{pre:null,post:null};let{pre:n,post:r}=Wn(t,e);return n===null&&r===null?{pre:null,post:null}:{pre:n,post:r}}function Wn(t,e){let n={},r={},o=!1,i=new Set([...V(t),...V(e)]);for(let s of i){if(s==="updatedAt")continue;let a=t[s],c=e[s];if(Array.isArray(a)||Array.isArray(c))continue;let d=oe(a),l=oe(c);if(!(s in e))d||(n[s]=a,r[s]=null,o=!0);else if(!(s in t))l||(n[s]=null,r[s]=c,o=!0);else{if(d&&l)continue;if(d&&!l)n[s]=null,r[s]=c,o=!0;else if(!d&&l)n[s]=a,r[s]=null,o=!0;else{let{pre:h,post:y}=Xo(a,c);(h!==void 0||y!==void 0)&&(h!==void 0&&(n[s]=_t(h)),y!==void 0&&(r[s]=_t(y)),o=!0)}}}return o?V(n).length===0&&V(r).length===0?{pre:null,post:null}:V(n).length===0?{pre:null,post:r}:V(r).length===0?{pre:n,post:null}:{pre:n,post:r}:{pre:null,post:null}}function Xo(t,e){if(Yo(t,e))return{pre:void 0,post:void 0};let n=oe(t),r=oe(e);if(n&&r)return{pre:void 0,post:void 0};if(n)return{pre:null,post:e};if(r)return{pre:t,post:null};if(Array.isArray(t)||Array.isArray(e))return{pre:void 0,post:void 0};if(typeof t!=typeof e)return{pre:t,post:e};if(typeof t=="object"&&t!==null&&typeof e=="object"&&e!==null){let{pre:o,post:i}=Wn(t,e);return o===null&&i===null?{pre:void 0,post:void 0}:{pre:o===null?void 0:o,post:i===null?void 0:i}}return{pre:t,post:e}}function oe(t){return t==null?!0:typeof t=="object"&&t!==null?Array.isArray(t)?t.length===0:V(t).length===0:!1}function Yo(t,e){return oe(t)&&oe(e)?!0:$t(t,e)}function $t(t,e){if(t===e)return!0;if(t==null||e==null||typeof t!="object"||typeof e!="object")return!1;let n=V(t),r=V(e);if(n.length!==r.length)return!1;for(let o of n)if(!(o in e)||!$t(t[o],e[o]))return!1;return!0}function ot(t,e){return e.pre===null?t===null:t===null||typeof t!="object"||Array.isArray(t)?!1:qn(t,e.pre)}function qn(t,e){for(let n in e)if(n!=="updatedAt"&&!ei(t[n],e[n]))return!1;return!0}function ei(t,e){return e===null||ti(e)?oe(t):t===void 0?!1:typeof e=="object"&&e!==null&&!Array.isArray(e)&&typeof t=="object"&&t!==null&&!Array.isArray(t)?qn(t,e):$t(t,e)}function ti(t){return t!==null&&typeof t=="object"&&!Array.isArray(t)&&V(t).length===0}function _t(t){if(t==null)return null;if(typeof t=="object"&&t!==null){if(Array.isArray(t)&&t.length===0)return null;if(!Array.isArray(t)){let e={},n=!1;for(let r in t)e[r]=_t(t[r]),e[r]!==void 0&&(n=!0);return n?e:null}}return t}function Ft(t,e){let n=Wt(t,e);return n!==null&&typeof n=="object"&&!Array.isArray(n)&&(n.updatedAt=e.updatedAt),n}function Wt(t,e){return e.post===null?null:t===null?e.post:typeof t!="object"||Array.isArray(t)?e.post:jn(t,e.post)}function jn(t,e){let n={};for(let r in t)if(r in e){let o=e[r];if(o===null)continue;typeof o=="object"&&!Array.isArray(o)&&typeof t[r]=="object"&&!Array.isArray(t[r])&&t[r]!==null?n[r]=jn(t[r],o):n[r]=o}else n[r]=t[r];for(let r in e)!(r in t)&&e[r]!==null&&(n[r]=e[r]);return n}function V(t){let e=[];for(let n in t)e.push(n);return e}var Un="replicated-state",it=class{ackedResources={};dirtyResources={};unauthorizedKeys={};loadingResources={};loadingPromises=new Map;loadedResources=new Set;registeredResources=new Set;resourceChangeListeners=new Set;snapshotWaiters=new Map;storage;socketSession;logger;inflightItems=new Map;constructor(e,n,r){this.storage=e,this.socketSession=n,this.logger=r}onResourceChange(e){return this.resourceChangeListeners.add(e),()=>this.resourceChangeListeners.delete(e)}registerResource(e){this.registeredResources.add(e),this.initializeResource(e)}isResourceRegistered(e){return this.registeredResources.has(e)}getRegisteredResources(){return Array.from(this.registeredResources)}setDirtyItems(e,n){this.registerResource(e),this.dirtyResources[e]=C(n)}setDirtyItem(e,n,r){if(this.registerResource(e),r===void 0){delete this.dirtyResources[e][n];return}this.dirtyResources[e][n]=C(r)}clearSessionState(){this.ackedResources={},this.loadingResources={},this.loadingPromises.clear(),this.loadedResources.clear(),this.inflightItems.clear();for(let e of this.registeredResources)this.dirtyResources[e]={},this.unauthorizedKeys[e]={},this.loadingResources[e]=!0,this.emitResourceChange(e)}async loadRegisteredResourcesFromStorage(){await Promise.all(Array.from(this.registeredResources,e=>this.loadResourceFromStorage(e)))}async hydrate(e,n){this.registerResource(e),await this.loadResourceFromStorage(e),this.logger.info(`Calculating lastUpdatedAtSeen from ${Jn(this.ackedResources[e])} items`);let r=this.prepareSnapshotQuery(e,n);this.logger.info(`\u{1F4F8} ${e} requested with query:`,r),this.socketSession.send(Un,{resource:e,action:"snapshot",value:r})}hydrateAll(e){return this.hydrate(e,{all:!0})}async waitForSnapshot(e,n){await new Promise((r,o)=>{let i,s=()=>{clearTimeout(i),r()};i=setTimeout(()=>{this.snapshotWaiters.get(e)?.delete(s),o(new Error(`snapshot timeout for ${e}`))},n),this.snapshotWaiters.has(e)||this.snapshotWaiters.set(e,new Set),this.snapshotWaiters.get(e).add(s)})}processSocketEvent(e){switch(e.action){case"snapshot":this.applySnapshot(e.resource,e.value??{});break;case"delta":this.applyRemoteDelta(e);break}}async upsertItem(e,n){this.registerResource(e);let r=this.getAckedValue(e,n.id),o=Mt(r,n);return o.pre===null&&o.post===null?!0:this.sendDelta(e,n.id,o,n)}async deleteItem(e,n){this.registerResource(e);let r=this.getAckedValue(e,n),o=Mt(r,null);return o.pre===null&&o.post===null?!0:this.sendDelta(e,n,o,null)}isItemInflight(e,n){return this.inflightItems.get(e)?.has(n)===!0}async sendDelta(e,n,r,o){this.registerResource(e),this.inflightItems.has(e)||this.inflightItems.set(e,new Set);let i=this.inflightItems.get(e);if(i.has(n))return!1;let s=this.getDirtyValue(e,n);ot(s,r)&&(arguments.length>=4?this.setDirtyValue(e,n,C(o)):this.setDirtyValue(e,n,Wt(s,C(r))),this.emitResourceChange(e)),i.add(n);let a;try{a=await this.socketSession.sendWithAck(Un,{resource:e,action:"delta",key:n,value:r})}catch(c){a={ok:!1,reason:c instanceof Error?c.message:"error"}}return i.delete(n),a.ok?!0:(this.revertDirtyToAckedValue(e,n),this.emitResourceChange(e),this.logger.error(`!ack[${e}] Reverting to acked state for ${e}:${n}`,a.reason),!1)}getAckedValue(e,n){return this.initializeResource(e),this.ackedResources[e][n]??null}getDirtyValue(e,n){return this.initializeResource(e),this.dirtyResources[e][n]??null}getVisibleItems(e){this.initializeResource(e);let n={};for(let r in this.dirtyResources[e]){let o=this.dirtyResources[e][r];o!=null&&(n[r]=o)}return n}getRawItems(e){return this.initializeResource(e),C(this.dirtyResources[e])}getAckedItems(e){return this.initializeResource(e),C(this.ackedResources[e])}getUnauthorizedKeys(e){return this.initializeResource(e),C(this.unauthorizedKeys[e])}isResourceLoading(e){return this.initializeResource(e),this.loadingResources[e]}initializeResource(e){this.ackedResources[e]===void 0&&(this.ackedResources[e]={}),this.dirtyResources[e]===void 0&&(this.dirtyResources[e]={}),this.unauthorizedKeys[e]===void 0&&(this.unauthorizedKeys[e]={}),this.loadingResources[e]===void 0&&(this.loadingResources[e]=!0)}prepareSnapshotQuery(e,n){this.initializeResource(e);let r=C(n);if(r.lastUpdatedAtSeen!==void 0)return r;let o=this.buildLastUpdatedAtSeen(e,r);return Ln(o)||(r.lastUpdatedAtSeen=o),r}async loadResourceFromStorage(e){if(this.initializeResource(e),this.loadedResources.has(e))return;if(this.loadingPromises.has(e))return this.loadingPromises.get(e);let n=this.loadResourceItemsFromStorage(e);this.loadingPromises.set(e,n);try{await n}finally{this.loadingPromises.delete(e),this.loadedResources.add(e)}}async loadResourceItemsFromStorage(e){let n=!1,r=0;try{let o=await this.storage.loadItems(e);if(o&&Ln(this.ackedResources[e])){n=!0;for(let i in o)this.applyCachedItem(e,i,o[i])&&(r+=1)}}catch(o){this.logger.warn(`Failed to load cached ${e}: ${String(o)}`)}finally{this.loadingResources[e]=!1,this.emitResourceChange(e),n?this.logger.info(`\u{1F4C2} ${r}x ${e} from cache`):this.logger.info(`\u{1F4C2} no cached data for ${e}`)}}applyCachedItem(e,n,r){return r===null?(this.ackedResources[e][n]=null,this.dirtyResources[e][n]=null,!0):r==="unauthorized"?(this.unauthorizedKeys[e][n]=!0,!1):(this.ackedResources[e][n]=C(r),this.dirtyResources[e][n]=C(r),!0)}applySnapshot(e,n){this.initializeResource(e);for(let r in n){let o=n[r];o===null?(this.ackedResources[e][r]=null,this.dirtyResources[e][r]=null,delete this.unauthorizedKeys[e][r]):o==="unauthorized"?(delete this.ackedResources[e][r],delete this.dirtyResources[e][r],this.unauthorizedKeys[e][r]=!0):(this.ackedResources[e][r]=C(o),this.dirtyResources[e][r]=C(o),delete this.unauthorizedKeys[e][r]),this.storage.persistItem(e,r,o).catch(i=>{this.logger.warn(`Failed to persist ${e}:${r}: ${String(i)}`)})}this.loadingResources[e]=!1,this.emitResourceChange(e),this.logger.info(`\u{1F4F8} ${Jn(n)}x ${e} `),this.resolveSnapshotWaiters(e)}applyRemoteDelta(e){let n=e.resource,r=e.key;if(!r)return;this.initializeResource(n);let o=e.value,i={pre:o.pre,post:o.post},s=this.getAckedValue(n,r);if(!ot(s,i))this.logger.error(`\u{1D6AB}S precondition invalid on last acked for ${n}:${r}`,{pre:i.pre,post:i.post,current:s});else{let c=Ft(s,C(o));this.ackedResources[n][r]=c,this.storage.persistItem(n,r,c).catch(d=>{this.logger.warn(`Failed to persist ${n}:${r}: ${String(d)}`)}),this.logger.info(qt(`\u{1D6AB}S[${n}] acked`,i))}let a=this.getDirtyValue(n,r);e.by!==this.socketSession.getSessionId()?ot(a,i)?i.post===null?(this.dirtyResources[n][r]=null,this.logger.info(qt(`\u{1D6AB}S[${n}] dirty`,i))):(this.dirtyResources[n][r]=Ft(a,C(o)),this.logger.info(qt(`\u{1D6AB}S[${n}] dirty`,i))):(this.logger.warn(`Skip delta on dirty for ${n}:${r}`,{pre:i.pre,post:i.post,current:s}),this.revertDirtyToAckedValue(n,r)):i.post!=null&&a!=null&&typeof a=="object"&&(a.updatedAt=o.updatedAt,this.dirtyResources[n][r]=a,this.logger.info(`\u{1D6AB}S[${n}] dirty updatedAt for ${r}`)),this.emitResourceChange(n)}buildLastUpdatedAtSeen(e,n){let r=this.ackedResources[e],o={};if(n.all){for(let i in r)this.copyItemUpdatedAt(r[i],i,o);return o}if(n.keys&&n.keys.length>0)for(let i of n.keys)this.copyItemUpdatedAt(r[i],i,o);return o}copyItemUpdatedAt(e,n,r){e&&typeof e=="object"&&typeof e.updatedAt=="number"&&(r[n]=e.updatedAt)}setDirtyValue(e,n,r){if(r===null){this.dirtyResources[e][n]=null;return}this.dirtyResources[e][n]=r}revertDirtyToAckedValue(e,n){let r=this.ackedResources[e][n];if(r===void 0){delete this.dirtyResources[e][n];return}if(r===null){this.dirtyResources[e][n]=null;return}this.dirtyResources[e][n]=C(r)}emitResourceChange(e){let n={resource:e,acked:this.getAckedItems(e),dirty:this.getRawItems(e),unauthorized:this.getUnauthorizedKeys(e),loading:this.loadingResources[e]};for(let r of this.resourceChangeListeners)r(n)}resolveSnapshotWaiters(e){let n=this.snapshotWaiters.get(e);if(n){this.snapshotWaiters.delete(e);for(let r of n)r()}}};function C(t){if(t===void 0)return t;if(typeof structuredClone=="function")try{return structuredClone(t)}catch{}try{return JSON.parse(JSON.stringify(t))}catch{return t}}function Ln(t){for(let e in t)return!1;return!0}function Jn(t){let e=0;for(let n in t)e+=1;return e}function qt(t,e){return`${t}
20
20
  delta.pre: ${JSON.stringify(e.pre)}
21
- delta.post: ${JSON.stringify(e.post)}`}var it=15e3,ti=2e3,jt=class{replicatedState;recordStorage;gatewaySocketSession;startPromise;reconnectTimer;registeredResources=new Set(An);closed=!1;start(){return this.startPromise?this.startPromise:(this.closed=!1,this.startPromise=this.connectAndHydrate().catch(e=>{throw this.startPromise=void 0,e}),this.startPromise)}async hydrateResource(e,n={all:!0}){this.registerResource(e),await this.start(),await this.hydrateConnectedResource(e,n)}async readResourceItems(e,n={all:!0}){return this.registerResource(e),await this.start(),this.filterVisibleItems(e,n)}async readResourceItem(e,n){this.registerResource(e),await this.start();let r=this.replicatedState?.getVisibleItems(e)[n]??null;return qn(e,r)}async upsertResourceItem(e,n){if(this.registerResource(e),await this.start(),!this.replicatedState)throw new Error("replicated state not initialized");return this.replicatedState.upsertItem(e,n)}async deleteResourceItem(e,n){if(this.registerResource(e),await this.start(),!this.replicatedState)throw new Error("replicated state not initialized");return this.replicatedState.deleteItem(e,n)}waitForChannelEvent(e,n,r=it){if(!this.gatewaySocketSession)throw new Error("gateway websocket not connected");return this.gatewaySocketSession.waitForChannelEvent(e,o=>n(o),r)}collectChannelEvents(e,n,r=it,o=250){if(!this.gatewaySocketSession)throw new Error("gateway websocket not connected");return this.gatewaySocketSession.collectChannelEvents(e,i=>n(i),r,o)}sendChannelEvent(e,n){if(!this.gatewaySocketSession)throw new Error("gateway websocket not connected");this.gatewaySocketSession.send(e,n)}close(){this.closed=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.startPromise=void 0,this.gatewaySocketSession?.close(),this.recordStorage?.close(),this.gatewaySocketSession=void 0,this.recordStorage=void 0,this.replicatedState=void 0}registerResource(e){On(e),this.registeredResources.add(e),this.replicatedState?.registerResource(e)}async connectAndHydrate(){let e=await X();if(!e)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let n=await Y(e);await ln(n);let r=k(),o=ne(n),i=fn(o.email);this.gatewaySocketSession?.close(),this.recordStorage?.close(),this.recordStorage=new Qe(r.replicatedStateDatabasePath,i),this.gatewaySocketSession=new He(r.backendUrl,n),this.replicatedState=new ot(this.recordStorage,this.gatewaySocketSession,ii),this.gatewaySocketSession.onChannel("replicated-state",s=>this.replicatedState?.processSocketEvent(s)),this.gatewaySocketSession.onDisconnected(()=>this.scheduleReconnect());for(let s of this.registeredResources)this.replicatedState.registerResource(s);await this.gatewaySocketSession.connect(it),await this.replicatedState.loadRegisteredResourcesFromStorage(),await this.hydrateRegisteredResources()}async hydrateRegisteredResources(){await Promise.all(Array.from(this.registeredResources,e=>this.hydrateConnectedResource(e,{all:!0})))}async hydrateConnectedResource(e,n){if(!this.replicatedState)throw new Error("replicated state not initialized");let r=this.replicatedState.waitForSnapshot(e,it);await this.replicatedState.hydrate(e,n),await r}filterVisibleItems(e,n){let r=this.replicatedState?.getVisibleItems(e)??{},o={};for(let i in r)ni(i,r[i],n)&&(o[i]=qn(e,r[i]));return o}scheduleReconnect(){this.closed||this.reconnectTimer||(this.startPromise=void 0,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.start().catch(()=>this.scheduleReconnect())},ti))}};function ni(t,e,n){return ri(t,e,n.lastUpdatedAtSeen)?!!(n.all||n.keys?.includes(t)||oi(e,n.fieldEqualTo)):!1}function qn(t,e){if(t!=="connections"||!e||typeof e!="object"||Array.isArray(e))return e;let n={...e};return delete n.config,n}function ri(t,e,n){let r=n?.[t];if(r===void 0||!e||typeof e!="object")return!0;let o=e.updatedAt;return typeof o!="number"||o>r}function oi(t,e){if(!e||!t||typeof t!="object")return!1;let n=t,r=!1;for(let o in e)if(r=!0,!ei(n[o],e[o]))return!1;return r}var ii={info(t,e){Wt("info",t,e)},warn(t,e){Wt("warn",t,e)},error(t,e){Wt("error",t,e)}};function Wt(t,e,n){let r=n===void 0?"":` ${JSON.stringify(n)}`;process.stderr.write(`[replicated-state:${t}] ${e}${r}
22
- `)}var qt;function Re(){return qt||(qt=new jt),qt}import{isDeepStrictEqual as si}from"node:util";function E(t,e){let n=nt(t);if(!n)throw new Error(`missing schema for resource: ${t}`);let r={failures:[],rootSchema:n.itemSchema};if(ke(n.itemSchema,e,"$",r),r.failures.length===0)return;let o=r.failures.slice(0,5).map(i=>`${i.path} ${i.message}`).join("; ");throw new Error(`item does not match ${t} schema: ${o}`)}function ke(t,e,n,r){if(t===!0)return;if(t===!1)return G(r,n,"is not allowed");if(!yi(t))return;let o=t.$ref;if(typeof o=="string"){ke(gi(o,r.rootSchema),e,n,r);return}ai(t,e,n,r)&&(ci(t,e,n,r),pi(t,e,n,r),di(t,e,n,r),li(t,e,n,r))}function ai(t,e,n,r){if(!Array.isArray(t.anyOf))return!0;for(let o of t.anyOf){let i={failures:[],rootSchema:r.rootSchema};if(ke(o,e,n,i),i.failures.length===0)return!1}return G(r,n,"does not match any allowed schema"),!1}function ci(t,e,n,r){let o=t.enum;if(Array.isArray(o)){for(let i of o)if(si(e,i))return;G(r,n,`must be one of ${o.map(String).join(", ")}`)}}function pi(t,e,n,r){let o=t.type;if(typeof o=="string"&&!jn(e,o)){G(r,n,`must be ${o}`);return}if(Array.isArray(o)){for(let i of o)if(typeof i=="string"&&jn(e,i))return;G(r,n,`must be ${o.map(String).join(" or ")}`)}}function di(t,e,n,r){if(t.type!=="object"||!Ae(e))return;let o=Ae(t.properties)?t.properties:{};ui(t,e,n,r);for(let i of mi(t))(!(i in e)||e[i]===void 0)&&G(r,`${n}.${i}`,"is required");for(let i in e){if(e[i]===void 0){G(r,`${n}.${i}`,"must not be undefined");continue}if(i in o){ke(o[i],e[i],`${n}.${i}`,r);continue}fi(t,e[i],`${n}.${i}`,r)}}function ui(t,e,n,r){let o=0;for(let a in e)Object.prototype.hasOwnProperty.call(e,a)&&o++;let i=t.minProperties;typeof i=="number"&&o<i&&G(r,n,`must have at least ${i} properties`);let s=t.maxProperties;typeof s=="number"&&o>s&&G(r,n,`must have at most ${s} properties`)}function li(t,e,n,r){if(t.type!=="array"||!Array.isArray(e))return;let o=t.items;if(o!==void 0)for(let i=0;i<e.length;i++)ke(o,e[i],`${n}[${i}]`,r)}function fi(t,e,n,r){let o=t.additionalProperties;if(o===!1){G(r,n,"is not allowed");return}o===void 0||o===!0||ke(o,e,n,r)}function mi(t){return Array.isArray(t.required)?t.required.filter(e=>typeof e=="string"):[]}function gi(t,e){if(!t.startsWith("#/"))return!1;let n=e,r=t.slice(2).split("/").map(hi);for(let o of r){if(!Ae(n)||!(o in n))return!1;n=n[o]}return n}function hi(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function jn(t,e){switch(e){case"array":return Array.isArray(t);case"boolean":return typeof t=="boolean";case"integer":return Number.isInteger(t);case"null":return t===null;case"number":return typeof t=="number"&&Number.isFinite(t);case"object":return Ae(t);case"string":return typeof t=="string";default:return!0}}function yi(t){return Ae(t)}function Ae(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function G(t,e,n){t.failures.push({path:e,message:n})}import Ut from"node:fs/promises";import bi from"node:os";import Un from"node:path";var wi=15e3;async function st(t){let e=await Jn({method:"GET",path:t});if(!e.ok)throw await Vn(t,e);return await e.json()}async function Ln(t){let e=await Jn(t),n={status:e.status,statusText:e.statusText,headers:xi(e.headers)};if(e.status>=300&&e.status<400)return{...n,location:e.headers.get("location")};if(!e.ok)throw await Vn(t.path,e);return t.responseMode==="binary"?await Ei(e,t,n):(e.headers.get("content-type")??"").includes("application/json")?{...n,body:await e.json().catch(()=>null)}:{...n,body:await e.text().catch(()=>"")}}async function Jn(t){let e=await ki(),n=Si(t.path,t.query),r=new Headers({Authorization:`Bearer ${e}`}),o=t.timeoutMs??wi;Ti(r,t.headers);let i={method:t.method,headers:r,redirect:"manual",signal:AbortSignal.timeout(o)};t.requestMode==="multipart"?i.body=await vi(t):t.requestMode==="form"?(i.body=Pi(t.body),r.set("Content-Type","application/x-www-form-urlencoded")):t.body!==void 0&&t.method!=="GET"&&t.method!=="HEAD"&&(r.set("Content-Type","application/json"),i.body=JSON.stringify(t.body));try{return await fetch(n,i)}catch(s){throw Ri(s)?new Error(`backend endpoint timed out after ${o}ms: ${t.path}`):s}}function Ri(t){return t instanceof DOMException&&(t.name==="TimeoutError"||t.name==="AbortError")}async function ki(){let t=await X();if(!t)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");return await Y(t)}function Ti(t,e){if(e)for(let n in e){let r=e[n];r!=null&&t.set(n,String(r))}}function Si(t,e){if(!t.startsWith("/"))throw new Error(`backend endpoint path must start with /: ${t}`);let n=k(),r=new URL(`${n.backendUrl}${t}`);return Ii(r,e),r.toString()}function Ii(t,e){if(e)for(let n in e){let r=e[n];if(r!=null){if(Array.isArray(r)){for(let o of r)t.searchParams.append(n,String(o));continue}t.searchParams.set(n,String(r))}}}function xi(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}async function vi(t){let e=new FormData,n=t.body;if(n&&typeof n=="object"&&!Array.isArray(n))for(let o in n){let i=n[o];i!=null&&e.set(o,String(i))}let r=t.files??{};for(let o in r)e.set(o,await Bi(r[o]),r[o].fileName??o);return e}async function Bi(t){if(t.filePath)return new Blob([await Ut.readFile(t.filePath)],{type:t.contentType});if(t.base64)return new Blob([Buffer.from(t.base64,"base64")],{type:t.contentType});throw new Error("multipart file input must include filePath or base64")}function Pi(t){let e=new URLSearchParams;if(!t||typeof t!="object"||Array.isArray(t))return e;for(let n in t){let r=t[n];r!=null&&e.set(n,String(r))}return e}async function Ei(t,e,n){let r=Buffer.from(await t.arrayBuffer()),o=e.outputFilePath??Ni(t);return await Ut.mkdir(Un.dirname(o),{recursive:!0}),await Ut.writeFile(o,r),{...n,filePath:o,sizeBytes:r.byteLength,contentType:t.headers.get("content-type")}}function Ni(t){let e=t.headers.get("content-disposition")??"",r=/filename="?([^";]+)"?/i.exec(e)?.[1]?.replace(/[^A-Za-z0-9._-]/g,"_")||`beepflow-download-${Date.now()}.bin`;return Un.join(bi.tmpdir(),"beepflow-mcp-downloads",r)}async function Vn(t,e){let n=await e.text().catch(()=>"");return new Error(`${t} failed: ${e.status} ${n}`.trim())}async function Lt(t){return Oi(await Jt(t))}async function Gn(){return await st("/integrations")}async function Kn(t,e){return await st(`/integrations/blueprint-contexts${Ai(t,e)}`)}async function Jt(t){return Di(await st(`/integrations/${encodeURIComponent(t)}/openapi`))}function Ai(t,e){let n=new URLSearchParams;t&&n.set("integrationType",t),e&&n.set("resourceType",e);let r=n.toString();return r?`?${r}`:""}async function Qn(t){let n=(await Lt(t.integrationType)).find(o=>o.operationId===t.operationId);if(!n)throw new Error(`unsupported integration endpoint: ${t.operationId}`);qi(n,t.confirm);let r=ji(n,t.payload);if(n.requestMode==="none"&&r.body!==void 0)throw new Error(`integration endpoint ${n.operationId} has requestBody=null; remove body-only fields from payload`);return await Ln({method:n.method,path:zi(n,r.path),query:r.query,headers:r.headers,body:r.body,requestMode:n.requestMode,responseMode:n.responseMode,files:r.files,outputFilePath:t.outputFilePath})}function Di(t){let e=De(t,"paths");for(let n in e){let r=e[n];if(T(r))for(let o in r){let i=r[o];T(i)&&(i.payloadSchema=Hn(i))}}return t}function Oi(t){let e=De(t,"paths"),n=[];for(let r in e){let o=e[r];if(T(o))for(let i in o){let s=o[i];T(s)&&n.push(Ci(i.toUpperCase(),r,s))}}return n}function Ci(t,e,n){let r=De(n,"x-beepflow");return{operationId:ye(n,"operationId"),integrationType:ye(r,"integrationType"),resourceType:Ki(r,"resourceType"),method:t,path:e,originalPath:ye(r,"originalPath"),summary:ye(n,"summary"),access:ye(r,"access"),sideEffect:ye(r,"sideEffect"),mcpExposure:ye(r,"mcpExposure"),requestMode:Yn(n),responseMode:Fi(n),pathParameters:Gi(e),parameters:Xn(n),payloadSchema:Hn(n),requestBody:_(n,"requestBody"),responses:De(n,"responses"),runtimeUse:"mcp-only",externalAppUse:"forbidden",externalAppAlternative:"Create/use a blueprint with webhook trigger and call /api/:tabId/trigger."}}function Hn(t){let e=Yn(t),n=$i(t,e),r={type:"object",additionalProperties:!1,properties:{}},o=r.properties,i=[];for(let s of Xn(t))!T(s)||typeof s.name!="string"||!T(s.schema)||(o[s.name]=s.schema,s.required===!0&&i.push(s.name));return _i(r,o,i,n,e),i.length&&(r.required=i),r}function _i(t,e,n,r,o){if(!r)return;let i=_(r,"properties");if(!i){t.additionalProperties=r.additionalProperties??!0;return}for(let a in i)e[a]=Mi(i[a],o);r.additionalProperties!==void 0&&r.additionalProperties!==!1&&(t.additionalProperties=r.additionalProperties);let s=r.required;if(Array.isArray(s))for(let a of s)typeof a=="string"&&n.push(a)}function Mi(t,e){return e!=="multipart"||!T(t)||t.format!=="binary"?t:{type:"object",additionalProperties:!1,description:"Multipart file input. Provide filePath or base64 content.",properties:{filePath:{type:"string",description:"Local file path to read and upload."},base64:{type:"string",description:"Base64-encoded file content."},fileName:{type:"string",description:"File name to send for base64 content."},contentType:{type:"string",description:"MIME type for uploaded content."}}}}function $i(t,e){let n=_(t,"requestBody");if(!n)return null;let r=_(n,"content");if(!r)return null;let o=Zn(e),i=_(r,o);return i?_(i,"schema"):null}function Zn(t){switch(t){case"multipart":return"multipart/form-data";case"form":return"application/x-www-form-urlencoded";default:return"application/json"}}function Xn(t){let e=t.parameters;if(e==null)return[];if(!Array.isArray(e))throw new Error("invalid integration OpenAPI schema: parameters must be array");return e}function Yn(t){let e=_(t,"requestBody");if(!e)return"none";let n=_(e,"content");return n?T(n["multipart/form-data"])?"multipart":T(n["application/x-www-form-urlencoded"])?"form":(T(n["application/json"]),"json"):"none"}function Fi(t){let e=De(t,"responses");for(let o in e)if(o.startsWith("3")&&T(e[o]))return"redirect";let n=Wi(e);if(!n)return"empty";let r=_(n,"content");return r?T(r["application/octet-stream"])?"binary":T(r["text/plain"])?"text":(T(r["application/json"]),"json"):"empty"}function Wi(t){if(T(t[200]))return t[200];for(let e in t)if(e.startsWith("2")&&T(t[e]))return t[e];return null}function qi(t,e){if(!(t.mcpExposure==="safe"&&t.sideEffect!=="destructive")&&e!==!0)throw new Error(`integration endpoint requires confirm=true: ${t.operationId}`)}function ji(t,e){let n={path:{},query:{},headers:{}},r=e??{},o=Vi(t);for(let i of t.parameters){if(!T(i)||typeof i.name!="string"||typeof i.in!="string")continue;let s=r[i.name];s!==void 0&&(i.in==="path"&&(n.path[i.name]=s),i.in==="query"&&(n.query[i.name]=s),i.in==="header"&&(n.headers[i.name]=s))}if(t.requestMode!=="none")Ui(t,r,o,n);else for(let i in r)o.has(i)||(n.body={[i]:r[i]});return n}function Ui(t,e,n,r){let o=Ji(t),i=o?_(o,"properties"):null,s={},a={};if(i){for(let c in i)Li(t,c,e[c],s,a);if(o?.additionalProperties!==void 0&&o.additionalProperties!==!1)for(let c in e)!n.has(c)&&i[c]===void 0&&(s[c]=e[c])}else if(o?.additionalProperties!==!1)for(let c in e)n.has(c)||(s[c]=e[c]);zn(s)&&(r.body=s),zn(a)&&(r.files=a)}function Li(t,e,n,r,o){if(n!==void 0){if(t.requestMode==="multipart"&&T(n)&&(typeof n.filePath=="string"||typeof n.base64=="string")){o[e]=n;return}r[e]=n}}function Ji(t){if(!t.requestBody)return null;let e=_(t.requestBody,"content"),n=e?_(e,Zn(t.requestMode)):null;return n?_(n,"schema"):null}function Vi(t){let e=new Set;for(let n of t.parameters)T(n)&&typeof n.name=="string"&&e.add(n.name);return e}function zn(t){for(let e in t)if(t[e]!==void 0)return!0;return!1}function zi(t,e){let n=t.path;for(let r of t.pathParameters){let o=e?.[r];if(typeof o!="string"&&typeof o!="number")throw new Error(`integration endpoint path parameter required: ${r}`);n=n.replace(`{${r}}`,encodeURIComponent(String(o)))}return n}function Gi(t){let e=[];for(let n of t.matchAll(/\{([^}]+)\}/g))n[1]&&e.push(n[1]);return e}function De(t,e){if(!T(t)||!T(t[e]))throw new Error(`invalid integration OpenAPI schema: ${e} must be object`);return t[e]}function _(t,e){if(!T(t)||t[e]===void 0||t[e]===null)return null;if(!T(t[e]))throw new Error(`invalid integration OpenAPI schema: ${e} must be object`);return t[e]}function ye(t,e){if(typeof t[e]!="string")throw new Error(`invalid integration OpenAPI schema: ${e} must be string`);return t[e]}function Ki(t,e){if(t[e]===void 0||t[e]===null)return null;if(typeof t[e]!="string")throw new Error(`invalid integration OpenAPI schema: ${e} must be string`);return t[e]}function T(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}var er="For Beepflow tasks, call status first and follow the instructions field returned in the status response. Treat client-saved tool outputs as historical logs; verify resource ids with live MCP queries.",Oe=`
21
+ delta.post: ${JSON.stringify(e.post)}`}var st=15e3,ri=2e3,Lt=class{replicatedState;recordStorage;gatewaySocketSession;startPromise;reconnectTimer;registeredResources=new Set(Mn);closed=!1;start(){return this.startPromise?this.startPromise:(this.closed=!1,this.startPromise=this.connectAndHydrate().catch(e=>{throw this.startPromise=void 0,e}),this.startPromise)}async hydrateResource(e,n={all:!0}){this.registerResource(e),await this.start(),await this.hydrateConnectedResource(e,n)}async readResourceItems(e,n={all:!0}){return this.registerResource(e),await this.start(),this.filterVisibleItems(e,n)}async readResourceItem(e,n){this.registerResource(e),await this.start();let r=this.replicatedState?.getVisibleItems(e)[n]??null;return Vn(e,r)}async upsertResourceItem(e,n){if(this.registerResource(e),await this.start(),!this.replicatedState)throw new Error("replicated state not initialized");return this.replicatedState.upsertItem(e,n)}async deleteResourceItem(e,n){if(this.registerResource(e),await this.start(),!this.replicatedState)throw new Error("replicated state not initialized");return this.replicatedState.deleteItem(e,n)}waitForChannelEvent(e,n,r=st){if(!this.gatewaySocketSession)throw new Error("gateway websocket not connected");return this.gatewaySocketSession.waitForChannelEvent(e,o=>n(o),r)}collectChannelEvents(e,n,r=st,o=250){if(!this.gatewaySocketSession)throw new Error("gateway websocket not connected");return this.gatewaySocketSession.collectChannelEvents(e,i=>n(i),r,o)}sendChannelEvent(e,n){if(!this.gatewaySocketSession)throw new Error("gateway websocket not connected");this.gatewaySocketSession.send(e,n)}close(){this.closed=!0,this.reconnectTimer&&clearTimeout(this.reconnectTimer),this.startPromise=void 0,this.gatewaySocketSession?.close(),this.recordStorage?.close(),this.gatewaySocketSession=void 0,this.recordStorage=void 0,this.replicatedState=void 0}registerResource(e){Fn(e),this.registeredResources.add(e),this.replicatedState?.registerResource(e)}async connectAndHydrate(){let e=await X();if(!e)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let n=await Y(e);await mn(n);let r=k(),o=ne(n),i=gn(o.email);this.gatewaySocketSession?.close(),this.recordStorage?.close(),this.recordStorage=new Qe(r.replicatedStateDatabasePath,i),this.gatewaySocketSession=new He(r.backendUrl,n),this.replicatedState=new it(this.recordStorage,this.gatewaySocketSession,ai),this.gatewaySocketSession.onChannel("replicated-state",s=>this.replicatedState?.processSocketEvent(s)),this.gatewaySocketSession.onDisconnected(()=>this.scheduleReconnect());for(let s of this.registeredResources)this.replicatedState.registerResource(s);await this.gatewaySocketSession.connect(st),await this.replicatedState.loadRegisteredResourcesFromStorage(),await this.hydrateRegisteredResources()}async hydrateRegisteredResources(){await Promise.all(Array.from(this.registeredResources,e=>this.hydrateConnectedResource(e,{all:!0})))}async hydrateConnectedResource(e,n){if(!this.replicatedState)throw new Error("replicated state not initialized");let r=this.replicatedState.waitForSnapshot(e,st);await this.replicatedState.hydrate(e,n),await r}filterVisibleItems(e,n){let r=this.replicatedState?.getVisibleItems(e)??{},o={};for(let i in r)oi(i,r[i],n)&&(o[i]=Vn(e,r[i]));return o}scheduleReconnect(){this.closed||this.reconnectTimer||(this.startPromise=void 0,this.reconnectTimer=setTimeout(()=>{this.reconnectTimer=void 0,this.start().catch(()=>this.scheduleReconnect())},ri))}};function oi(t,e,n){return ii(t,e,n.lastUpdatedAtSeen)?!!(n.all||n.keys?.includes(t)||si(e,n.fieldEqualTo)):!1}function Vn(t,e){if(t!=="connections"||!e||typeof e!="object"||Array.isArray(e))return e;let n={...e};return delete n.config,n}function ii(t,e,n){let r=n?.[t];if(r===void 0||!e||typeof e!="object")return!0;let o=e.updatedAt;return typeof o!="number"||o>r}function si(t,e){if(!e||!t||typeof t!="object")return!1;let n=t,r=!1;for(let o in e)if(r=!0,!ni(n[o],e[o]))return!1;return r}var ai={info(t,e){jt("info",t,e)},warn(t,e){jt("warn",t,e)},error(t,e){jt("error",t,e)}};function jt(t,e,n){let r=n===void 0?"":` ${JSON.stringify(n)}`;process.stderr.write(`[replicated-state:${t}] ${e}${r}
22
+ `)}var Ut;function Re(){return Ut||(Ut=new Lt),Ut}import{isDeepStrictEqual as ci}from"node:util";function E(t,e){let n=rt(t);if(!n)throw new Error(`missing schema for resource: ${t}`);let r={failures:[],rootSchema:n.itemSchema};if(ke(n.itemSchema,e,"$",r),r.failures.length===0)return;let o=r.failures.slice(0,5).map(i=>`${i.path} ${i.message}`).join("; ");throw new Error(`item does not match ${t} schema: ${o}`)}function ke(t,e,n,r){if(t===!0)return;if(t===!1)return G(r,n,"is not allowed");if(!wi(t))return;let o=t.$ref;if(typeof o=="string"){ke(yi(o,r.rootSchema),e,n,r);return}pi(t,e,n,r)&&(di(t,e,n,r),ui(t,e,n,r),li(t,e,n,r),mi(t,e,n,r))}function pi(t,e,n,r){if(!Array.isArray(t.anyOf))return!0;for(let o of t.anyOf){let i={failures:[],rootSchema:r.rootSchema};if(ke(o,e,n,i),i.failures.length===0)return!1}return G(r,n,"does not match any allowed schema"),!1}function di(t,e,n,r){let o=t.enum;if(Array.isArray(o)){for(let i of o)if(ci(e,i))return;G(r,n,`must be one of ${o.map(String).join(", ")}`)}}function ui(t,e,n,r){let o=t.type;if(typeof o=="string"&&!zn(e,o)){G(r,n,`must be ${o}`);return}if(Array.isArray(o)){for(let i of o)if(typeof i=="string"&&zn(e,i))return;G(r,n,`must be ${o.map(String).join(" or ")}`)}}function li(t,e,n,r){if(t.type!=="object"||!Ae(e))return;let o=Ae(t.properties)?t.properties:{};fi(t,e,n,r);for(let i of hi(t))(!(i in e)||e[i]===void 0)&&G(r,`${n}.${i}`,"is required");for(let i in e){if(e[i]===void 0){G(r,`${n}.${i}`,"must not be undefined");continue}if(i in o){ke(o[i],e[i],`${n}.${i}`,r);continue}gi(t,e[i],`${n}.${i}`,r)}}function fi(t,e,n,r){let o=0;for(let a in e)Object.prototype.hasOwnProperty.call(e,a)&&o++;let i=t.minProperties;typeof i=="number"&&o<i&&G(r,n,`must have at least ${i} properties`);let s=t.maxProperties;typeof s=="number"&&o>s&&G(r,n,`must have at most ${s} properties`)}function mi(t,e,n,r){if(t.type!=="array"||!Array.isArray(e))return;let o=t.items;if(o!==void 0)for(let i=0;i<e.length;i++)ke(o,e[i],`${n}[${i}]`,r)}function gi(t,e,n,r){let o=t.additionalProperties;if(o===!1){G(r,n,"is not allowed");return}o===void 0||o===!0||ke(o,e,n,r)}function hi(t){return Array.isArray(t.required)?t.required.filter(e=>typeof e=="string"):[]}function yi(t,e){if(!t.startsWith("#/"))return!1;let n=e,r=t.slice(2).split("/").map(bi);for(let o of r){if(!Ae(n)||!(o in n))return!1;n=n[o]}return n}function bi(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function zn(t,e){switch(e){case"array":return Array.isArray(t);case"boolean":return typeof t=="boolean";case"integer":return Number.isInteger(t);case"null":return t===null;case"number":return typeof t=="number"&&Number.isFinite(t);case"object":return Ae(t);case"string":return typeof t=="string";default:return!0}}function wi(t){return Ae(t)}function Ae(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function G(t,e,n){t.failures.push({path:e,message:n})}import Jt from"node:fs/promises";import Ri from"node:os";import Gn from"node:path";var ki=15e3;async function at(t){let e=await Qn({method:"GET",path:t});if(!e.ok)throw await Hn(t,e);return await e.json()}async function Kn(t){let e=await Qn(t),n={status:e.status,statusText:e.statusText,headers:Bi(e.headers)};if(e.status>=300&&e.status<400)return{...n,location:e.headers.get("location")};if(!e.ok)throw await Hn(t.path,e);return t.responseMode==="binary"?await Ai(e,t,n):(e.headers.get("content-type")??"").includes("application/json")?{...n,body:await e.json().catch(()=>null)}:{...n,body:await e.text().catch(()=>"")}}async function Qn(t){let e=await Si(),n=xi(t.path,t.query),r=new Headers({Authorization:`Bearer ${e}`}),o=t.timeoutMs??ki;Ii(r,t.headers);let i={method:t.method,headers:r,redirect:"manual",signal:AbortSignal.timeout(o)};t.requestMode==="multipart"?i.body=await Pi(t):t.requestMode==="form"?(i.body=Ni(t.body),r.set("Content-Type","application/x-www-form-urlencoded")):t.body!==void 0&&t.method!=="GET"&&t.method!=="HEAD"&&(r.set("Content-Type","application/json"),i.body=JSON.stringify(t.body));try{return await fetch(n,i)}catch(s){throw Ti(s)?new Error(`backend endpoint timed out after ${o}ms: ${t.path}`):s}}function Ti(t){return t instanceof DOMException&&(t.name==="TimeoutError"||t.name==="AbortError")}async function Si(){let t=await X();if(!t)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");return await Y(t)}function Ii(t,e){if(e)for(let n in e){let r=e[n];r!=null&&t.set(n,String(r))}}function xi(t,e){if(!t.startsWith("/"))throw new Error(`backend endpoint path must start with /: ${t}`);let n=k(),r=new URL(`${n.backendUrl}${t}`);return vi(r,e),r.toString()}function vi(t,e){if(e)for(let n in e){let r=e[n];if(r!=null){if(Array.isArray(r)){for(let o of r)t.searchParams.append(n,String(o));continue}t.searchParams.set(n,String(r))}}}function Bi(t){let e={};return t.forEach((n,r)=>{e[r]=n}),e}async function Pi(t){let e=new FormData,n=t.body;if(n&&typeof n=="object"&&!Array.isArray(n))for(let o in n){let i=n[o];i!=null&&e.set(o,String(i))}let r=t.files??{};for(let o in r)e.set(o,await Ei(r[o]),r[o].fileName??o);return e}async function Ei(t){if(t.filePath)return new Blob([await Jt.readFile(t.filePath)],{type:t.contentType});if(t.base64)return new Blob([Buffer.from(t.base64,"base64")],{type:t.contentType});throw new Error("multipart file input must include filePath or base64")}function Ni(t){let e=new URLSearchParams;if(!t||typeof t!="object"||Array.isArray(t))return e;for(let n in t){let r=t[n];r!=null&&e.set(n,String(r))}return e}async function Ai(t,e,n){let r=Buffer.from(await t.arrayBuffer()),o=e.outputFilePath??Di(t);return await Jt.mkdir(Gn.dirname(o),{recursive:!0}),await Jt.writeFile(o,r),{...n,filePath:o,sizeBytes:r.byteLength,contentType:t.headers.get("content-type")}}function Di(t){let e=t.headers.get("content-disposition")??"",r=/filename="?([^";]+)"?/i.exec(e)?.[1]?.replace(/[^A-Za-z0-9._-]/g,"_")||`beepflow-download-${Date.now()}.bin`;return Gn.join(Ri.tmpdir(),"beepflow-mcp-downloads",r)}async function Hn(t,e){let n=await e.text().catch(()=>"");return new Error(`${t} failed: ${e.status} ${n}`.trim())}async function Vt(t){return _i(await zt(t))}async function Xn(){return await at("/integrations")}async function Yn(t,e){return await at(`/integrations/blueprint-contexts${Oi(t,e)}`)}async function zt(t){return Ci(await at(`/integrations/${encodeURIComponent(t)}/openapi`))}function Oi(t,e){let n=new URLSearchParams;t&&n.set("integrationType",t),e&&n.set("resourceType",e);let r=n.toString();return r?`?${r}`:""}async function er(t){let n=(await Vt(t.integrationType)).find(o=>o.operationId===t.operationId);if(!n)throw new Error(`unsupported integration endpoint: ${t.operationId}`);Ui(n,t.confirm);let r=Li(n,t.payload);if(n.requestMode==="none"&&r.body!==void 0)throw new Error(`integration endpoint ${n.operationId} has requestBody=null; remove body-only fields from payload`);return await Kn({method:n.method,path:Ki(n,r.path),query:r.query,headers:r.headers,body:r.body,requestMode:n.requestMode,responseMode:n.responseMode,files:r.files,outputFilePath:t.outputFilePath})}function Ci(t){let e=De(t,"paths");for(let n in e){let r=e[n];if(T(r))for(let o in r){let i=r[o];T(i)&&(i.payloadSchema=tr(i))}}return t}function _i(t){let e=De(t,"paths"),n=[];for(let r in e){let o=e[r];if(T(o))for(let i in o){let s=o[i];T(s)&&n.push(Mi(i.toUpperCase(),r,s))}}return n}function Mi(t,e,n){let r=De(n,"x-beepflow");return{operationId:ye(n,"operationId"),integrationType:ye(r,"integrationType"),resourceType:Hi(r,"resourceType"),method:t,path:e,originalPath:ye(r,"originalPath"),summary:ye(n,"summary"),access:ye(r,"access"),sideEffect:ye(r,"sideEffect"),mcpExposure:ye(r,"mcpExposure"),requestMode:or(n),responseMode:qi(n),pathParameters:Qi(e),parameters:rr(n),payloadSchema:tr(n),requestBody:_(n,"requestBody"),responses:De(n,"responses"),runtimeUse:"mcp-only",externalAppUse:"forbidden",externalAppAlternative:"Create/use a blueprint with webhook trigger and call /api/:tabId/trigger."}}function tr(t){let e=or(t),n=Wi(t,e),r={type:"object",additionalProperties:!1,properties:{}},o=r.properties,i=[];for(let s of rr(t))!T(s)||typeof s.name!="string"||!T(s.schema)||(o[s.name]=s.schema,s.required===!0&&i.push(s.name));return $i(r,o,i,n,e),i.length&&(r.required=i),r}function $i(t,e,n,r,o){if(!r)return;let i=_(r,"properties");if(!i){t.additionalProperties=r.additionalProperties??!0;return}for(let a in i)e[a]=Fi(i[a],o);r.additionalProperties!==void 0&&r.additionalProperties!==!1&&(t.additionalProperties=r.additionalProperties);let s=r.required;if(Array.isArray(s))for(let a of s)typeof a=="string"&&n.push(a)}function Fi(t,e){return e!=="multipart"||!T(t)||t.format!=="binary"?t:{type:"object",additionalProperties:!1,description:"Multipart file input. Provide filePath or base64 content.",properties:{filePath:{type:"string",description:"Local file path to read and upload."},base64:{type:"string",description:"Base64-encoded file content."},fileName:{type:"string",description:"File name to send for base64 content."},contentType:{type:"string",description:"MIME type for uploaded content."}}}}function Wi(t,e){let n=_(t,"requestBody");if(!n)return null;let r=_(n,"content");if(!r)return null;let o=nr(e),i=_(r,o);return i?_(i,"schema"):null}function nr(t){switch(t){case"multipart":return"multipart/form-data";case"form":return"application/x-www-form-urlencoded";default:return"application/json"}}function rr(t){let e=t.parameters;if(e==null)return[];if(!Array.isArray(e))throw new Error("invalid integration OpenAPI schema: parameters must be array");return e}function or(t){let e=_(t,"requestBody");if(!e)return"none";let n=_(e,"content");return n?T(n["multipart/form-data"])?"multipart":T(n["application/x-www-form-urlencoded"])?"form":(T(n["application/json"]),"json"):"none"}function qi(t){let e=De(t,"responses");for(let o in e)if(o.startsWith("3")&&T(e[o]))return"redirect";let n=ji(e);if(!n)return"empty";let r=_(n,"content");return r?T(r["application/octet-stream"])?"binary":T(r["text/plain"])?"text":(T(r["application/json"]),"json"):"empty"}function ji(t){if(T(t[200]))return t[200];for(let e in t)if(e.startsWith("2")&&T(t[e]))return t[e];return null}function Ui(t,e){if(!(t.mcpExposure==="safe"&&t.sideEffect!=="destructive")&&e!==!0)throw new Error(`integration endpoint requires confirm=true: ${t.operationId}`)}function Li(t,e){let n={path:{},query:{},headers:{}},r=e??{},o=Gi(t);for(let i of t.parameters){if(!T(i)||typeof i.name!="string"||typeof i.in!="string")continue;let s=r[i.name];s!==void 0&&(i.in==="path"&&(n.path[i.name]=s),i.in==="query"&&(n.query[i.name]=s),i.in==="header"&&(n.headers[i.name]=s))}if(t.requestMode!=="none")Ji(t,r,o,n);else for(let i in r)o.has(i)||(n.body={[i]:r[i]});return n}function Ji(t,e,n,r){let o=zi(t),i=o?_(o,"properties"):null,s={},a={};if(i){for(let c in i)Vi(t,c,e[c],s,a);if(o?.additionalProperties!==void 0&&o.additionalProperties!==!1)for(let c in e)!n.has(c)&&i[c]===void 0&&(s[c]=e[c])}else if(o?.additionalProperties!==!1)for(let c in e)n.has(c)||(s[c]=e[c]);Zn(s)&&(r.body=s),Zn(a)&&(r.files=a)}function Vi(t,e,n,r,o){if(n!==void 0){if(t.requestMode==="multipart"&&T(n)&&(typeof n.filePath=="string"||typeof n.base64=="string")){o[e]=n;return}r[e]=n}}function zi(t){if(!t.requestBody)return null;let e=_(t.requestBody,"content"),n=e?_(e,nr(t.requestMode)):null;return n?_(n,"schema"):null}function Gi(t){let e=new Set;for(let n of t.parameters)T(n)&&typeof n.name=="string"&&e.add(n.name);return e}function Zn(t){for(let e in t)if(t[e]!==void 0)return!0;return!1}function Ki(t,e){let n=t.path;for(let r of t.pathParameters){let o=e?.[r];if(typeof o!="string"&&typeof o!="number")throw new Error(`integration endpoint path parameter required: ${r}`);n=n.replace(`{${r}}`,encodeURIComponent(String(o)))}return n}function Qi(t){let e=[];for(let n of t.matchAll(/\{([^}]+)\}/g))n[1]&&e.push(n[1]);return e}function De(t,e){if(!T(t)||!T(t[e]))throw new Error(`invalid integration OpenAPI schema: ${e} must be object`);return t[e]}function _(t,e){if(!T(t)||t[e]===void 0||t[e]===null)return null;if(!T(t[e]))throw new Error(`invalid integration OpenAPI schema: ${e} must be object`);return t[e]}function ye(t,e){if(typeof t[e]!="string")throw new Error(`invalid integration OpenAPI schema: ${e} must be string`);return t[e]}function Hi(t,e){if(t[e]===void 0||t[e]===null)return null;if(typeof t[e]!="string")throw new Error(`invalid integration OpenAPI schema: ${e} must be string`);return t[e]}function T(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}var ir="For Beepflow tasks, call status first and follow the instructions field returned in the status response. Treat client-saved tool outputs as historical logs; verify resource ids with live MCP queries.",Oe=`
23
23
  Use Beepflow MCP to inspect authenticated workspace resources, blueprint context, live results, integration OpenAPI endpoints, and auth.
24
24
 
25
25
  Global:
@@ -45,4 +45,4 @@ Safety:
45
45
  - Ask before destructive actions unless user intent is explicit.
46
46
  - Pass confirm=true only after explicit confirmation or unmistakable user intent.
47
47
  - When uncertain, inspect schemas and resources first.
48
- `.trim();function p(t,e){let n=A(t)[e];if(typeof n!="string"||!n.trim())throw new Error(`invalid tool arguments: ${e} must be non-empty string`);return n}function b(t,e){let n=A(t)[e];if(n!=null){if(typeof n!="string")throw new Error(`invalid tool arguments: ${e} must be string`);return n}}function ie(t,e){let n=A(t)[e];if(typeof n!="boolean")throw new Error(`invalid tool arguments: ${e} must be boolean`);return n}function at(t,e){let n=A(t)[e];if(n!=null){if(typeof n!="boolean")throw new Error(`invalid tool arguments: ${e} must be boolean`);return n}}function ct(t,e){let n=A(t)[e];if(!ae(n))throw new Error(`invalid tool arguments: ${e} must be object`);return n}function pt(t,e){if(t===void 0)return;let n=A(t)[e];if(n!=null){if(!ae(n))throw new Error(`invalid tool arguments: ${e} must be object`);return n}}function se(t,e){let n=tr(t,e);if(!n)throw new Error(`invalid tool arguments: ${e} must be string array`);return n}function tr(t,e){let n=A(t)[e];if(n!=null){if(!Array.isArray(n)||n.some(r=>typeof r!="string"))throw new Error(`invalid tool arguments: ${e} must be string array`);return n}}function nr(t,e){let n=Vt(t,e);if(n===void 0)throw new Error(`invalid tool arguments: ${e} must be positive integer`);return n}function Vt(t,e){let n=A(t)[e];if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error(`invalid tool arguments: ${e} must be positive integer`);return n}}function rr(t,e){let n=A(t)[e];if(n!=null){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`invalid tool arguments: ${e} must be number`);return n}}function F(t,e,n){let r=p(t,e);if(!n.includes(r))throw new Error(`invalid tool arguments: ${e} must be one of ${n.join(", ")}`);return r}function Te(t,e,n){let r=b(t,e);if(r!==void 0){if(!n.includes(r))throw new Error(`invalid tool arguments: ${e} must be one of ${n.join(", ")}`);return r}}function dt(t){if(t!==void 0)return tr(t,"ids")}function A(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid tool arguments: expected object");return t}function ae(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}var Qi={type:"object",additionalProperties:!0},ut={type:"object",additionalProperties:!1,required:["type","trigger"],properties:{type:Xe,trigger:et,config:Ye}};var Se=["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"];function lt(t){return{type:"object",additionalProperties:!1,properties:{ids:ee(t),fieldEqualTo:{...Qi,description:"Return items whose top-level fields equal these exact values."}}}}function m(t,e=["id"]){return{type:"object",additionalProperties:!1,required:e,properties:{id:{type:"string",description:"Tab/blueprint id."},...t}}}function K(t,e){return m({nodeId:{type:"string",description:"Blueprint node id."},inputName:{type:"string",description:"Operator input name."},...t},e)}function Ie(t,e){return m(t,e)}function ee(t){return{type:"array",items:{type:"string"},description:t}}function M(){return{type:"string",description:"CRDT list index. Defaults to 0.5 where supported."}}function f(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ft(t,e){let n={};return t&&(n.keys=t),e&&(n.fieldEqualTo=e),!t&&!e&&(n.all=!0),n}async function W(t,e,n){return t.readResourceItems("tabs",ft(e,n))}async function or(t,e){let n=await t.readResourceItem("tabs",e);if(!n)throw new Error(`tab not found: ${e}`);return n}function ir(t){return{name:"tabs_query",description:"Query visible tabs and folders. Use ids for exact tabs or fieldEqualTo for exact top-level field matches; with no filters, returns all visible tabs.",inputSchema:lt("Tab ids to read."),call:async e=>f(await W(t,dt(e),pt(e,"fieldEqualTo")))}}var Hi=(t=6)=>{let n="abcdefghijklmnopqrstuvwxyz",o=`1234567890${n}${n.toUpperCase()}`.split(""),i=new Uint8Array(t);return crypto.getRandomValues(i),i.reduce((s,a)=>`${s}${o[a&61]}`,"")},Q=Hi;function gt(t,e){if(e.insertAfterTabId){let o=t[e.insertAfterTabId];return o?Ce(t,o):.5}let n=mt(t).find(o=>o.parent===e.parent);return n?(n.order??1)*.5:(mt(t)[0]?.order??1)*.5}function Ce(t,e){let n=mt(t),r=n.findIndex(i=>i.id===e.id),o=r>=0?n[r+1]:void 0;return e.order*.5+(o?.order??1)*.5}function sr(t,e){let n=mt(t).filter(o=>o.parent===e.parent),r=n.findIndex(o=>o.id===e.id);return((n[r-1]?.order??0)+e.order)*.5}function ar(t,e){let n=0;for(let r in t){let o=t[r];o.parent===e&&o.order>n&&(n=o.order)}return n*.5+.5}function mt(t){let e=[];for(let n in t)e.push(t[n]);return e.sort((n,r)=>n.order-r.order)}function ht(t,e){if(e)return e;for(let n in t)return t[n].parent;throw new Error("parent is required when no existing tab can provide a default parent")}function xe(t,e){if(e.startsWith("spaces:"))return e.split(":")[1]??"";if(e.startsWith("tabs:")){let n=e.split(":")[1],r=n?t[n]?.spaceId:void 0;if(r)return r}throw new Error(`could not find spaceId for parent: ${e}`)}function _e(t,e){let n=t[e];if(!n)throw new Error(`tab not found: ${e}`);return n}async function ve(t,e){return E("tabs",e),t.upsertResourceItem("tabs",e)}function cr(t){return{name:"folder_tab_create",description:"Create a folder tab under a parent such as spaces:<spaceId> or tabs:<folderId>. Computes frontend-compatible order and parent space.",inputSchema:{type:"object",additionalProperties:!1,properties:{parent:{type:"string",description:"Parent id, normally spaces:<spaceId> or tabs:<folderId>. Optional only when an existing tab can provide a default parent."},name:{type:"string",description:"Folder name. Defaults to Untitled folder."},insertAfterTabId:{type:"string",description:"Optional tab id after which to insert in global frontend tab order."}}},call:async e=>f(await Zi(t,{parent:b(e,"parent"),name:b(e,"name"),insertAfterTabId:b(e,"insertAfterTabId")}))}}async function Zi(t,e){let n=await W(t),r=ht(n,e.parent),o=xe(n,r),i={id:Q(),updatedAt:z(),name:e.name??"Untitled folder",order:gt(n,{parent:r,insertAfterTabId:e.insertAfterTabId}),type:"folder",parent:r,spaceId:o};return await ve(t,i),i}function pr(t){return{name:"tab_rename",description:"Rename an existing tab or folder by preserving all other tab fields and upserting only the full updated tab record.",inputSchema:m({name:{type:"string",description:"New non-empty tab name."}},["id","name"]),call:async e=>{let n=p(e,"id"),r=await or(t,n);return r.name=p(e,"name"),await ve(t,r),f(r)}}}function dr(t){return{name:"tab_move",description:"Move or reorder a tab. Supports explicit order, insertBeforeTabId, insertAfterTabId, or appending to a parent while updating parent spaceId like frontend drag/drop.",inputSchema:m({parent:{type:"string",description:"New parent id, normally spaces:<spaceId> or tabs:<folderId>."},order:{type:"number",description:"Explicit order value. Overrides insert and append order computation."},insertBeforeTabId:{type:"string",description:"Move before this sibling tab."},insertAfterTabId:{type:"string",description:"Move after this tab using frontend global ordering."}}),call:async e=>{let n=p(e,"id"),r=await W(t),o=r[n];if(!o)throw new Error(`tab not found: ${n}`);let i=Xi(r,o,e);return o.parent=i.parent,o.spaceId=i.spaceId,o.order=i.order,await ve(t,o),f(o)}}}function Xi(t,e,n){let r=rr(n,"order"),o=b(n,"insertBeforeTabId"),i=b(n,"insertAfterTabId"),s=o?_e(t,o):i?_e(t,i):void 0,a=b(n,"parent")??s?.parent??e.parent,c=s?.spaceId??xe(t,a),d=r??(o?sr(t,_e(t,o)):i?Ce(t,_e(t,i)):ar(t,a));return{parent:a,spaceId:c,order:d}}function ur(t){return{name:"tab_delete",description:"Delete a tab tree recursively. Folder tabs delete children; blueprint tabs delete matching blueprints and blueprint-views before deleting the tab.",inputSchema:m({},["id"]),call:async e=>f(await Yi(t,p(e,"id")))}}async function Yi(t,e){let n=await W(t),r=n[e];if(!r)throw new Error(`tab not found: ${e}`);let o=[],i=[],s=[];return await lr(t,n,r,o,i,s),{deletedTabs:o,deletedBlueprints:i,deletedBlueprintViews:s}}async function lr(t,e,n,r,o,i){let s=`tabs:${n.id}`;for(let a in e){let c=e[a];c.parent===s&&await lr(t,e,c,r,o,i)}n.type==="blueprint"?(await Promise.all([t.deleteResourceItem("blueprints",n.id),t.deleteResourceItem("blueprint-views",n.id),t.deleteResourceItem("tabs",n.id)]),o.push(n.id),i.push(n.id)):await t.deleteResourceItem("tabs",n.id),r.push(n.id)}async function fr(t,e,n){return t.readResourceItems("blueprints",ft(e,n))}function mr(t){return{name:"blueprints_query",description:"Query visible blueprint definitions. Use ids for exact blueprints or fieldEqualTo for exact top-level field matches; with no filters, returns all visible blueprints.",inputSchema:lt("Blueprint ids to read."),call:async e=>f(await fr(t,dt(e),pt(e,"fieldEqualTo")))}}function zt(t){if(!t)throw new Error("blueprint context trigger is required");let e=0;for(let n of["manual","cron","loop","blueprint","webhook","executor"])t[n]!==void 0&&e++;if(e!==1)throw new Error("blueprint context trigger must contain exactly one branch")}function yt(t){let e=t.type,n=t.trigger;if(typeof e!="string"||!e.trim())throw new Error("context.type must be non-empty string");if(!ae(n))throw new Error("context.trigger must be object");zt(n);let r={type:e,trigger:n};return ae(t.config)&&(r.config=t.config),r}function gr(t){return{name:"blueprint_tab_create",description:"Create a blueprint tab plus matching blueprint and blueprint-view records with one shared id. Requires context with exactly one trigger branch. After create, tell user blueprint URL: `${status.frontendUrl}/${encodeURIComponent(tab.id)}`. For external app integrations, use a blueprint with webhook trigger and tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(tab.id)}/trigger`.",inputSchema:{type:"object",additionalProperties:!1,required:["context"],properties:{context:{...ut,description:"Blueprint context with type, trigger, and optional config. Trigger must have exactly one branch."},parent:{type:"string",description:"Parent id, normally spaces:<spaceId> or tabs:<folderId>. Optional only when existing tabs can provide a default."},name:{type:"string",description:"Tab name. Defaults to Untitled."},mode:{type:"string",enum:["test","explore"],description:"Initial mode. Defaults to test."},testRecordsAmount:{type:"integer",minimum:1,description:"Initial number of test records. Defaults to 1."},insertAfterTabId:{type:"string",description:"Optional tab id after which to insert."}}},call:async e=>f(await es(t,{context:yt(ct(e,"context")),parent:b(e,"parent"),name:b(e,"name"),mode:Te(e,"mode",["test","explore"]),testRecordsAmount:Vt(e,"testRecordsAmount"),insertAfterTabId:b(e,"insertAfterTabId")}))}}async function es(t,e){let n=await W(t),r=Q(),o=ht(n,e.parent),i=xe(n,o),s={id:r,updatedAt:z(),name:e.name??"Untitled",order:gt(n,{parent:o,insertAfterTabId:e.insertAfterTabId}),type:"blueprint",parent:o,spaceId:i},a={id:r,updatedAt:z(),mode:e.mode??"test",nodes:{},context:e.context,testRecordsAmount:e.testRecordsAmount??1,desiredState:"inactive"},c={id:r,updatedAt:z(),nodes:{}};return zt(a.context.trigger),E("tabs",s),E("blueprints",a),E("blueprint-views",c),await Promise.all([t.upsertResourceItem("tabs",s),t.upsertResourceItem("blueprints",a),t.upsertResourceItem("blueprint-views",c)]),{tab:s,blueprint:a,blueprintView:c}}async function g(t,e){let[n,r,o]=await Promise.all([t.readResourceItem("tabs",e),t.readResourceItem("blueprints",e),t.readResourceItem("blueprint-views",e)]);if(!n)throw new Error(`tab not found: ${e}`);if(n.type!=="blueprint")throw new Error(`tab is not a blueprint: ${e}`);if(!r)throw new Error(`blueprint not found: ${e}`);if(!o)throw new Error(`blueprint view not found: ${e}`);return ts(r),ns(o),{tab:n,blueprint:r,blueprintView:o}}function ts(t){t.nodes??={}}function ns(t){t.nodes??={}}function hr(t){return{name:"blueprint_tab_duplicate",description:"Duplicate a blueprint tab by cloning tab, blueprint, and blueprint-view with a new shared id. Only top-level ids are remapped; node ids are preserved like frontend tab duplicate. After duplicate, tell user blueprint URL: `${status.frontendUrl}/${encodeURIComponent(tab.id)}`.",inputSchema:m({name:{type:"string",description:"Optional duplicated tab name. Defaults to source name plus *."}}),call:async e=>f(await rs(t,p(e,"id"),b(e,"name")))}}async function rs(t,e,n){let r=await W(t),o=await g(t,e),i=Q(),s=structuredClone(o.tab);s.id=i,s.updatedAt=z(),s.name=n??`${o.tab.name}*`,s.order=Ce(r,o.tab);let a=structuredClone(o.blueprint);a.id=i,a.updatedAt=z(),a.mode=a.mode??"test";let c=structuredClone(o.blueprintView);return c.id=i,c.updatedAt=z(),E("tabs",s),E("blueprints",a),E("blueprint-views",c),await Promise.all([t.upsertResourceItem("tabs",s),t.upsertResourceItem("blueprints",a),t.upsertResourceItem("blueprint-views",c)]),{tab:s,blueprint:a,blueprintView:c}}async function B(t,e){return Gt(e),E("blueprints",e),t.upsertResourceItem("blueprints",e)}function Gt(t){for(let e in t.nodes){let n=t.nodes[e];for(let r in n.inputs){let o=n.inputs[r];for(let i in o.values)os(o.values[i])}}}function os(t){(!Object.prototype.hasOwnProperty.call(t,"literal")||t.literal===void 0)&&(t.literal=null)}function yr(t){return{name:"blueprint_context_update",description:"Replace blueprint context as one unit, including type, config, and exactly one trigger branch. When integrating external apps, set webhook trigger and tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(blueprint.id)}/trigger`.",inputSchema:m({context:{...ut,description:"Full replacement context with type, trigger, and optional config. Trigger must have exactly one branch."}},["id","context"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id"));return n.context=yt(ct(e,"context")),await B(t,n),f(n)}}}async function ce(t,e,n){let r=await X();if(!r)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let o=await Y(r),i=k(),s=await fetch(`${i.backendUrl}/blueprints/${t}/modes/${e}/${n}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`blueprint runtime action failed: ${s.status} ${a}`.trim())}return{ok:!0,status:s.status,blueprintId:t,mode:e,action:n}}function pe(t,e,n,r,o){return{name:e,description:n,inputSchema:m({mode:{type:"string",enum:["test","explore"],description:r?"Target mode.":"Mode to use. Defaults to current blueprint mode."}},r?["id","mode"]:["id"]),call:async i=>{let s=p(i,"id"),c=Te(i,"mode",["test","explore"])??(await g(t,s)).blueprint.mode;return f(await o(s,c))}}}function br(t){return pe(t,"blueprint_mode_set","Switch blueprint mode through backend runtime endpoint to preserve side effects.",!0,async(e,n)=>ce(e,n,"switch-mode"))}function wr(t){return{name:"blueprint_test_records_set",description:"Set blueprint testRecordsAmount for test mode data generation. Uses replicated blueprint upsert; value must be at least 1.",inputSchema:m({amount:{type:"integer",minimum:1,description:"Number of test records."}},["id","amount"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id"));return n.testRecordsAmount=nr(e,"amount"),await B(t,n),f(n)}}}function Rr(t){return pe(t,"blueprint_test_records_shuffle","Regenerate test records through backend /modes/test/shuffle-records endpoint.",!1,async e=>ce(e,"test","shuffle-records"))}function kr(t){return pe(t,"blueprint_runtime_start","Start blueprint runtime for supplied mode or current blueprint mode through backend endpoint. When starting webhook trigger blueprint, tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(id)}/trigger`. Webhook runs only while blueprint is active in explore mode. External apps integrate by calling this blueprint webhook endpoint.",!1,async(e,n)=>ce(e,n,"start"))}function Tr(t){return pe(t,"blueprint_runtime_stop","Stop blueprint runtime for supplied mode or current blueprint mode through backend endpoint.",!1,async(e,n)=>ce(e,n,"stop"))}function Sr(t){return{name:"blueprint_recompute_on_change_set",description:"Set recomputeOnChange to always or manual. Frontend treats undefined as always; this tool stores explicit value for clarity.",inputSchema:m({value:{type:"string",enum:["always","manual"],description:"Recompute behavior."}},["id","value"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id"));return n.recomputeOnChange=F(e,"value",["always","manual"]),await B(t,n),f(n)}}}function Ir(t){return{name:"blueprint_mock_never_set",description:"Set or clear blueprint-level mockNever. enabled=true stores true; enabled=false clears the optional field like frontend toggle.",inputSchema:m({enabled:{type:"boolean",description:"Whether to disable mocking for all nodes."}},["id","enabled"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id"));return ie(e,"enabled")?n.mockNever=!0:delete n.mockNever,await B(t,n),f(n)}}}async function H(t,e){let n=await t.readResourceItems("blueprint-operators"),r={};for(let o in e.nodes){let i=n[e.nodes[o].operatorId];i&&(r[i.id]=i)}return{...n,...r}}function Kt(t){if(Object.keys(t).length===0)return;let e=null,n=null;for(let r in t)isNaN(parseFloat(r))||(n===null||parseFloat(r)<n)&&(e=r,n=parseFloat(r));return n!==null?t[e]:void 0}function xr(t){let e=Object.keys(t).filter(i=>!isNaN(parseFloat(i))).sort((i,s)=>parseFloat(i)-parseFloat(s));if(e.length===0)return"0.5";let n=e[e.length-1],r=parseFloat(n);return((r+(Math.floor(r)+1))/2).toPrecision(15).replace(/0+$/,"").replace(/\.$/,"")}function de(t,e){let n=xr(t);return t[n]=e,n}var vr=new Set(["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"]);function w(t,e){let n=t.nodes[e];if(!n)throw new Error(`blueprint node not found: ${e}`);return n}function $(t,e){let n=t.inputs[e];if(!n)throw new Error(`node input not found: ${t.id}.${e}`);return n.values??={},n}function bt(t,e,n,r){let i=$(w(t,e),n).values[r];if(!i)throw new Error(`input value not found: ${e}.${n}[${r}]`);return i}function Me(t,e){let n=t[e];if(!n)throw new Error(`blueprint operator not found: ${e}`);return n}function Be(t,e){let n=t.inputs.find(r=>r.name===e);if(!n)throw new Error(`operator input not found: ${t.id}.${e}`);return n}function wt(t,e){let n=t.output;if(!n||n.name!==e)throw new Error(`operator output not found: ${t.id}.${e}`);return n}function q(t){delete t.nodeId,delete t.operatorInputId,delete t.nodeInputIndex}function Br(t,e){t.nodeId=e.nodeId,t.operatorInputId=e.operatorInputId,t.nodeInputIndex=e.nodeInputIndex}function Pe(t,e,n,r,o){let i=w(t,n.nodeId),s=w(t,r.nodeId),a=Me(e,i.operatorId),c=Me(e,s.operatorId);wt(a,n.pinName);let d=Be(c,r.pinName),l=$(s,r.pinName),h=n.index??"0.5",y=is(l,d,r.index,o),S=l.values[y];return S.nodeId=i.id,S.operatorInputId=n.pinName,S.nodeInputIndex=h,y}function Pr(t,e){let n=w(t,e.nodeId),r=e.index??"0.5";if(e.pinPosition==="input"){let o=bt(t,n.id,e.pinName,r);q(o);return}for(let o in t.nodes)for(let i in t.nodes[o].inputs)for(let s in t.nodes[o].inputs[i].values){let a=t.nodes[o].inputs[i].values[s];a.nodeId===n.id&&a.operatorInputId===e.pinName&&a.nodeInputIndex===r&&q(a)}}function is(t,e,n,r){if(r)return n?(t.values[n]??={literal:null},n):de(t.values,{literal:null});if(n){if(!(n in t.values))throw new Error(`input value not found: ${e.name}[${n}]`);return n}return e.type.isArray?de(t.values,{literal:null}):"0.5"in t.values?"0.5":(t.values["0.5"]={literal:null},"0.5")}function Er(t){return{name:"blueprint_pins_connect",description:"Connect one output pin to one input pin by writing pointer fields on target input value. Validates nodes and pin names; can create target array element. For newly created operator nodes, prefer passing inputConnections to blueprint_operator_node_add instead of calling this after creation, so layout sees graph edges before assigning coordinates.",inputSchema:m({sourceNodeId:{type:"string"},sourceOutputName:{type:"string"},sourceIndex:M(),targetNodeId:{type:"string"},targetInputName:{type:"string"},targetIndex:M(),createTargetArrayElement:{type:"boolean",description:"Append target input value before connecting."}},["id","sourceNodeId","sourceOutputName","targetNodeId","targetInputName"]),call:async e=>{let n=await g(t,p(e,"id")),r=Pe(n.blueprint,await H(t,n.blueprint),{nodeId:p(e,"sourceNodeId"),pinName:p(e,"sourceOutputName"),index:b(e,"sourceIndex")},{nodeId:p(e,"targetNodeId"),pinName:p(e,"targetInputName"),index:b(e,"targetIndex")},at(e,"createTargetArrayElement")??!1);return await B(t,n.blueprint),f({targetIndex:r,blueprint:n.blueprint})}}}function D(t,e,n,r,o){return{name:t,description:e,inputSchema:n,call:async i=>{let{blueprint:s}=await g(r,p(i,"id"));return o(s,i),await B(r,s),f(s)}}}function Nr(t){return D("blueprint_pin_unlink","Unlink an input pin value or all downstream links from an output pin.",m({nodeId:{type:"string"},pinName:{type:"string"},pinPosition:{type:"string",enum:["input","output"]},index:M()},["id","nodeId","pinName","pinPosition"]),t,(e,n)=>Pr(e,{nodeId:p(n,"nodeId"),pinName:p(n,"pinName"),pinPosition:F(n,"pinPosition",["input","output"]),index:b(n,"index")}))}async function te(t,e){let n=await t.readResourceItem("blueprint-operators",e);if(!n)throw new Error(`blueprint operator not found: ${e}`);if(!Array.isArray(n.inputs))throw new Error(`blueprint operator has invalid inputs: ${e}`);return n}async function Z(t,e,n){Gt(e),E("blueprints",e),E("blueprint-views",n);let[r,o]=await Promise.all([t.upsertResourceItem("blueprints",e),t.upsertResourceItem("blueprint-views",n)]);return{blueprintOk:r,blueprintViewOk:o}}function ss(t,e=Q()){let n={id:e,operatorId:t.id,inputs:{}};for(let r of t.inputs)r.type.isArray?n.inputs[r.name]={isArray:!0,values:{}}:n.inputs[r.name]={values:{"0.5":{literal:null}}};return n}function Ee(t,e,n){let r=ss(n);return t.nodes[r.id]=r,e.nodes[r.id]={id:r.id},r}function Ar(t){return{name:"blueprint_node_input_literal_set",description:"Set a node input literal at a CRDT value index. Defaults index to 0.5. With disconnect=true, clears upstream pointer fields first. For newly created operator nodes, prefer inputLiterals on blueprint_operator_node_add instead of setting literals afterward.",inputSchema:K({literal:{description:"JSON literal value to set."},index:M(),disconnect:{type:"boolean",description:"Clear upstream connection fields when true."}},["id","nodeId","inputName","literal"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id")),r=Qt(n,p(e,"nodeId"),p(e,"inputName"),b(e,"index")??"0.5",A(e).literal,at(e,"disconnect")??!1);return await B(t,n),f({value:r,blueprint:n})}}}function Qt(t,e,n,r,o,i){let s=bt(t,e,n,r);return s.literal=o,i&&q(s),s}function Dr(t){return{name:"blueprint_operator_node_add",description:"Add an operator node using frontend default input creation. Leaves view position unset so frontend can place it after measuring dimensions. When creating connected or configured nodes, set inputConnections and inputLiterals in this same call. Prefer this over blueprint_pins_connect and blueprint_node_input_literal_set immediately after creation because frontend uses connections present at first render to place missing-position nodes correctly.",inputSchema:Ie({operatorId:{type:"string",description:"Registered blueprint operator id."},inputConnections:{type:"array",description:"Input connections to apply before first write. Use for all known input links when creating a node; prefer this over blueprint_pins_connect after creation because frontend layout uses these connections before assigning coordinates.",items:{type:"object",additionalProperties:!1,required:["inputName","sourceNodeId","sourceOutputName","sourceIndex"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},sourceNodeId:{type:"string",description:"Existing source node id."},sourceOutputName:{type:"string",description:"Source output pin name."},sourceIndex:{type:"string",description:"Source output CRDT index."},targetIndex:{type:"string",description:"Target input CRDT index. Defaults to 0.5 for scalar inputs."},createTargetArrayElement:{type:"boolean",description:"Append target input value before connecting."}}}},inputLiterals:{type:"array",description:"Input literals to apply before first write. Use for all known literal inputs when creating a node; prefer this over blueprint_node_input_literal_set immediately after creation. Same behavior as blueprint_node_input_literal_set.",items:{type:"object",additionalProperties:!1,required:["inputName","literal"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},literal:{description:"JSON literal value to set."},index:{type:"string",description:"Target input CRDT index. Defaults to 0.5."},disconnect:{type:"boolean",description:"Clear upstream connection fields when true."}}}}},["id","operatorId"]),call:async e=>{let n=await g(t,p(e,"id")),r=await te(t,p(e,"operatorId")),o=Ee(n.blueprint,n.blueprintView,r);as(n.blueprint,o.id,ds(e));let i=ps(e);return i.length>0&&cs(n.blueprint,await H(t,n.blueprint),o.id,i),await Z(t,n.blueprint,n.blueprintView),f({node:o,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function as(t,e,n){for(let r of n){let o=t.nodes[e].inputs[r.inputName];o?.isArray&&r.index&&(o.values[r.index]??={literal:null});let i=o?.isArray?r.index??de(o.values,{literal:null}):r.index??"0.5";Qt(t,e,r.inputName,i,r.literal,r.disconnect??!1)}}function cs(t,e,n,r){for(let o of r){let i=e[t.nodes[n].operatorId].inputs.find(s=>s.name===o.inputName);Pe(t,e,{nodeId:o.sourceNodeId,pinName:o.sourceOutputName,index:o.sourceIndex},{nodeId:n,pinName:o.inputName,index:o.targetIndex},o.createTargetArrayElement??!!i?.type.isArray)}}function ps(t){let e=A(t).inputConnections;if(e==null)return[];if(!Array.isArray(e))throw new Error("invalid tool arguments: inputConnections must be array");let n=[];for(let r=0;r<e.length;r++){let o=e[r];if(!ae(o))throw new Error(`invalid tool arguments: inputConnections[${r}] must be object`);let i=o.inputName,s=o.sourceNodeId,a=o.sourceOutputName,c=o.sourceIndex,d=o.targetIndex,l=o.createTargetArrayElement;if(typeof i!="string"||!i.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].inputName must be non-empty string`);if(typeof s!="string"||!s.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceNodeId must be non-empty string`);if(typeof a!="string"||!a.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceOutputName must be non-empty string`);if(typeof c!="string"||!c.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceIndex must be non-empty string`);if(d!==void 0&&typeof d!="string")throw new Error(`invalid tool arguments: inputConnections[${r}].targetIndex must be string`);if(l!==void 0&&typeof l!="boolean")throw new Error(`invalid tool arguments: inputConnections[${r}].createTargetArrayElement must be boolean`);n.push({inputName:i,sourceNodeId:s,sourceOutputName:a,sourceIndex:c,targetIndex:d,createTargetArrayElement:l})}return n}function ds(t){let e=A(t).inputLiterals;if(e==null)return[];if(!Array.isArray(e))throw new Error("invalid tool arguments: inputLiterals must be array");let n=[];for(let r=0;r<e.length;r++){let o=e[r];if(!ae(o))throw new Error(`invalid tool arguments: inputLiterals[${r}] must be object`);let i=o.inputName,s=o.literal,a=o.index,c=o.disconnect;if(typeof i!="string"||!i.trim())throw new Error(`invalid tool arguments: inputLiterals[${r}].inputName must be non-empty string`);if(!("literal"in o))throw new Error(`invalid tool arguments: inputLiterals[${r}].literal is required`);if(a!==void 0&&typeof a!="string")throw new Error(`invalid tool arguments: inputLiterals[${r}].index must be string`);if(c!==void 0&&typeof c!="boolean")throw new Error(`invalid tool arguments: inputLiterals[${r}].disconnect must be boolean`);n.push({inputName:i,literal:s,index:a,disconnect:c})}return n}function Or(t){return{name:"blueprint_context_field_node_add",description:"Add a context field getter node using Base/function/blueprint/field-wildcard, setting outputType and Path literal. Apache Kafka context config is initialized from field connection/path when unset.",inputSchema:Ie({connectionId:{type:"string",description:"Context field connection id."},path:{type:"string",description:"Context field path such as topic or collection."},field:{type:"string",description:"Field name to store in Path literal."},type:{type:"string",enum:Se,description:"Field output type."}},["id","connectionId","path","field","type"]),call:async e=>{let n=await g(t,p(e,"id")),r=await te(t,"Base/function/blueprint/field-wildcard"),o=Ee(n.blueprint,n.blueprintView,r);return o.outputType=F(e,"type",Se),o.inputs.Path.values["0.5"]={literal:p(e,"field")},us(n.blueprint.context,p(e,"connectionId"),p(e,"path")),await Z(t,n.blueprint,n.blueprintView),f({node:o,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function us(t,e,n){t.type==="ApacheKafkaTopic"&&(t.config??={},t.config.topicName===void 0&&(t.config.connectionId=e,t.config.topicName=n))}function Cr(t){return{name:"blueprint_node_result_field_node_add",description:"Add a map/get node for a field inferred from an upstream node result. Sets Path literal and optionally connects source output to Target input.",inputSchema:Ie({path:{type:"string",description:"Result field path to store in Path literal."},sourceNodeId:{type:"string",description:"Optional upstream source node id to connect into Target."},sourceOutputName:{type:"string",description:"Optional upstream output name. Defaults to source operator output."}},["id","path"]),call:async e=>{let n=await g(t,p(e,"id")),r=await te(t,"Base/function/map/get"),o=Ee(n.blueprint,n.blueprintView,r);o.inputs.Path.values["0.5"]={literal:p(e,"path")};let i=b(e,"sourceNodeId");return i&&Pe(n.blueprint,await H(t,n.blueprint),{nodeId:i,pinName:b(e,"sourceOutputName")??await ls(t,n.blueprint,i)},{nodeId:o.id,pinName:"Target",index:"0.5"},!1),await Z(t,n.blueprint,n.blueprintView),f({node:o,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}async function ls(t,e,n){let r=e.nodes[n];if(!r)throw new Error(`source node not found: ${n}`);let o=await te(t,r.operatorId);if(!o.output?.name)throw new Error(`source node operator has no output: ${r.operatorId}`);return o.output.name}function _r(t){return{name:"blueprint_node_array_input_add",description:"Append an element to an array input using frontend CRDT list index generation. Returns new index.",inputSchema:K({literal:{description:"Optional initial literal value. Defaults to null."}},["id","nodeId","inputName"]),call:async e=>{let n=await g(t,p(e,"id")),r=n.blueprint.nodes[p(e,"nodeId")];if(!r)throw new Error("node not found");let o=await te(t,r.operatorId),i=A(e),s=Object.prototype.hasOwnProperty.call(i,"literal")?i.literal:null,a=fs(n.blueprint,o,r.id,p(e,"inputName"),s);return await B(t,n.blueprint),f({index:a,blueprint:n.blueprint})}}}function fs(t,e,n,r,o){let i=w(t,n);if(!Be(e,r).type.isArray)throw new Error(`operator input is not an array: ${r}`);let a=$(i,r);return de(a.values,{literal:o===void 0?null:o})}function Mr(t){return D("blueprint_node_array_input_remove","Remove one CRDT-indexed value from a node array input.",K({index:M()},["id","nodeId","inputName","index"]),t,(e,n)=>ms(e,p(n,"nodeId"),p(n,"inputName"),p(n,"index")))}function ms(t,e,n,r){let o=$(w(t,e),n);if(!(r in o.values))throw new Error(`input value not found: ${e}.${n}[${r}]`);delete o.values[r]}function $r(t){return D("blueprint_node_array_input_move","Move array input values by swapping two CRDT entries. Provide indexA/indexB or index plus direction up/down.",K({indexA:M(),indexB:M(),index:M(),direction:{type:"string",enum:["up","down"],description:"Adjacent move direction when indexA/indexB are omitted."}},["id","nodeId","inputName"]),t,(e,n)=>{let r=p(n,"inputName"),o=e.nodes[p(n,"nodeId")];if(!o)throw new Error("node not found");let i=b(n,"indexA")??p(n,"index"),s=b(n,"indexB")??hs(o.inputs[r]?.values??{},i,F(n,"direction",["up","down"]));gs(e,o.id,r,i,s)})}function gs(t,e,n,r,o){let i=$(w(t,e),n);if(!(r in i.values))throw new Error(`input value not found: ${e}.${n}[${r}]`);if(!(o in i.values))throw new Error(`input value not found: ${e}.${n}[${o}]`);let s=i.values[r];i.values[r]=i.values[o],i.values[o]=s}function hs(t,e,n){let r=[];for(let s in t)Number.isNaN(parseFloat(s))||r.push(s);r.sort((s,a)=>parseFloat(s)-parseFloat(a));let o=r.indexOf(e),i=n==="up"?r[o-1]:r[o+1];if(!i)throw new Error(`no adjacent input value ${n} from index ${e}`);return i}function Fr(t){return D("blueprint_node_input_zipping_set","Set or clear forceZipping on a node input. enabled=false clears the optional field like frontend.",K({enabled:{type:"boolean",description:"Whether to force zipping."}},["id","nodeId","inputName","enabled"]),t,(e,n)=>ys(e,p(n,"nodeId"),p(n,"inputName"),ie(n,"enabled")))}function ys(t,e,n,r){let o=$(w(t,e),n);r?o.forceZipping=!0:delete o.forceZipping}function Wr(t,e,n,r,o,i){if(i!==void 0&&!vr.has(i))throw new Error(`unsupported type: ${i}`);let s=w(t,n),a=Me(e,s.operatorId);r==="output"?bs(t,e,s,a,o,i):Rs(t,e,s,a,o,i)}function Zt(t,e){return t.outputType??e.output?.type.type}function bs(t,e,n,r,o,i){let s=wt(r,o);i===void 0||i===s.type.type?delete n.outputType:n.outputType=i;let a=i??s.type.type;for(let c in t.nodes)ws(t.nodes[c],e,n,o,a)}function ws(t,e,n,r,o){let i=e[t.operatorId];if(i)for(let s in t.inputs){let a=i.inputs.find(c=>c.name===s);if(a)for(let c in t.inputs[s].values){let d=t.inputs[s].values[c];d.nodeId!==n.id||d.operatorInputId!==r||(Ts(o,t.inputs[s].type??a.type.type,a.type)?t.inputs[s].type=o:q(d))}}}function Rs(t,e,n,r,o,i){let s=Be(r,o),a=$(n,o);i===void 0||i===s.type.type?delete a.type:a.type=i;let c=i??s.type.type;for(let d in a.values){let l=a.values[d];if(!l.nodeId||!l.operatorInputId)continue;let h=t.nodes[l.nodeId],y=h?e[h.operatorId]:void 0;if(!h||!y?.output)continue;let S=Zt(h,y);Ss(S,c)||q(l)}ks(n,r,s.type,i)}function ks(t,e,n,r){let o=Ht(n);if(o){for(let i of e.inputs)Ht(i.type)===o&&(r?t.inputs[i.name].type=r:delete t.inputs[i.name].type);e.output&&Ht(e.output.type)===o&&(r?t.outputType=r:delete t.outputType)}}function Ts(t,e,n){return Rt(e)?!n.allowedTypes||n.allowedTypes.length===0?!0:n.allowedTypes.some(r=>$e(t)?t.includes(r.type):r.type===t):$e(t)?t.includes(e):t===e}function Ss(t,e){return!t||!e?!1:t==="list of wildcard"||e==="list of wildcard"?$e(t)&&$e(e):!Rt(t)&&!Rt(e)?$e(t)?t.includes(e):t===e:!0}function $e(t){return t?.startsWith("list of ")??!1}function Rt(t){return t==="wildcard"||t==="list of wildcard"}function Ht(t){if(t&&Rt(t.type))return t.linkType??"_"}function qr(t,e){let n=new Set(e);for(let r of n)Is(t,r);for(let r in t.nodes){let o=t.nodes[r];for(let i in o.inputs)for(let s in o.inputs[i].values){let a=o.inputs[i].values[s];(n.has(o.id)||a.nodeId&&n.has(a.nodeId))&&q(a)}}}function jr(t,e,n){let r={};for(let o of n){let i=t.nodes[o],s=i?e[i.operatorId]:void 0,a=s?.inputs[0];if(!i||!s?.output||!a)continue;let c=Zt(i,s),d=i.inputs[a.name]?.type??a.type.type;if(c!==d)continue;let l=Kt(i.inputs[a.name]?.values??{});l?.nodeId&&(r[i.id]=structuredClone(l))}return r}function Ur(t,e,n){for(let r in t.inputs)for(let o in t.inputs[r].values){let i=t.inputs[r].values[o];i.nodeId&&(e[i.nodeId]?i.nodeId=e[i.nodeId]:n.has(i.nodeId)||q(i))}}function Lr(t,e){e?Br(t,e):q(t)}function Is(t,e){if(!t.nodes[e])throw new Error(`blueprint node not found: ${e}`)}function Jr(t){return D("blueprint_node_connections_remove","Remove selected nodes input links and downstream links pointing to selected nodes.",m({nodeIds:ee("Node ids whose connections should be removed.")},["id","nodeIds"]),t,(e,n)=>qr(e,se(n,"nodeIds")))}function Vr(t){return{name:"blueprint_node_type_set",description:"Set or clear an input/output resolved type. Omitting type or setting base type clears override; incompatible existing links are disconnected.",inputSchema:m({nodeId:{type:"string"},xputType:{type:"string",enum:["input","output"]},pinName:{type:"string"},type:{type:"string",enum:Se,description:"Resolved type override. Omit to reset to operator base type."}},["id","nodeId","xputType","pinName"]),call:async e=>{let n=await g(t,p(e,"id"));return Wr(n.blueprint,await H(t,n.blueprint),p(e,"nodeId"),F(e,"xputType",["input","output"]),p(e,"pinName"),Te(e,"type",Se)),await B(t,n.blueprint),f(n.blueprint)}}}function zr(t){return D("blueprint_nodes_disabled_set","Set or clear disabled on selected nodes. disabled=false clears optional field like frontend.",m({nodeIds:ee("Node ids to update."),disabled:{type:"boolean",description:"Whether nodes should be disabled."}},["id","nodeIds","disabled"]),t,(e,n)=>xs(e,se(n,"nodeIds"),ie(n,"disabled")))}function xs(t,e,n){for(let r of e){let o=w(t,r);n?o.disabled=!0:delete o.disabled}}function Gr(t){return D("blueprint_node_mock_never_set","Set or clear node-level mockNever. enabled=false clears optional field like frontend.",m({nodeId:{type:"string"},enabled:{type:"boolean"}},["id","nodeId","enabled"]),t,(e,n)=>vs(e,p(n,"nodeId"),ie(n,"enabled")))}function vs(t,e,n){let r=w(t,e);n?r.mockNever=!0:delete r.mockNever}function Kr(t){return D("blueprint_node_skip_behavior_set","Set On Skip behavior. behavior=skip clears stored value because frontend default skip is undefined; behavior=null stores string null.",m({nodeId:{type:"string"},behavior:{type:"string",enum:["skip","null"]}},["id","nodeId","behavior"]),t,(e,n)=>Bs(e,p(n,"nodeId"),F(n,"behavior",["skip","null"])))}function Bs(t,e,n){let r=w(t,e);n==="skip"?delete r.skipBehavior:r.skipBehavior="null"}function Qr(t){return{name:"blueprint_nodes_delete",description:"Delete blueprint nodes and view nodes. Mirrors frontend rewire behavior for deleted nodes whose first input type matches output type.",inputSchema:m({nodeIds:ee("Node ids to delete.")},["id","nodeIds"]),call:async e=>{let n=await g(t,p(e,"id"));return Ps(n.blueprint,n.blueprintView,await H(t,n.blueprint),se(e,"nodeIds")),await Z(t,n.blueprint,n.blueprintView),f({blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function Ps(t,e,n,r){let o=new Set(r);for(let s of o)w(t,s);let i=jr(t,n,o);for(let s in t.nodes)for(let a in t.nodes[s].inputs)for(let c in t.nodes[s].inputs[a].values){let d=t.nodes[s].inputs[a].values[c];!d.nodeId||!o.has(d.nodeId)||Lr(d,i[d.nodeId])}for(let s of o)delete t.nodes[s],delete e.nodes[s]}function Hr(t){return{name:"blueprint_nodes_duplicate",description:"Duplicate selected nodes and view nodes. Remaps internal copied-node references, drops missing-node references, and leaves new node positions for the frontend layout pass.",inputSchema:m({nodeIds:ee("Node ids to duplicate.")},["id","nodeIds"]),call:async e=>{let n=await g(t,p(e,"id")),r=Es(n.blueprint,n.blueprintView,se(e,"nodeIds"));return await Z(t,n.blueprint,n.blueprintView),f({nodeIds:r,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function Es(t,e,n){let r=new Set(n);for(let a of r)w(t,a);let o={},i=n.map(a=>structuredClone(t.nodes[a])),s=new Set;for(let a in t.nodes)s.add(a);for(let a of i){let c=Q();o[a.id]=c,a.id=c}for(let a of i)Ur(a,o,s);for(let a of i)t.nodes[a.id]=a;for(let a of n){let c=structuredClone(e.nodes[a]??{id:a}),d=o[a];c.id=d,Ns(c),e.nodes[d]=c}return n.map(a=>o[a])}function Ns(t){if(!t.style)return;let e={...t.style};delete e.x,delete e.y;for(let n in e){t.style=e;return}delete t.style}function Zr(t){return[ir(t),mr(t),cr(t),pr(t),dr(t),ur(t),gr(t),hr(t),yr(t),br(t),wr(t),Rr(t),kr(t),Tr(t),Sr(t),Ir(t),Dr(t),Or(t),Cr(t),Ar(t),_r(t),Mr(t),$r(t),Fr(t),Er(t),Nr(t),Jr(t),Vr(t),zr(t),Gr(t),Kr(t),Qr(t),Hr(t)]}var We={type:"object",additionalProperties:!0},qe={type:"object",additionalProperties:!1,properties:{}},eo=["kafka-topic:offset-extents","rabbitmq-stream:offset-extents","base-event-collection:offset-extents","shopify-webhook:offset-extents"],Ds=["ticket-message-created","ticket-message-failed"];function to(t=Re()){return[...Os(t),...Cs(t),..._s(t),...Zr(t),...Ms(t),...$s(t),...Ws(t)]}function Os(t){return[{name:"resources_list",description:"Discover Beepflow resources supported by this MCP server, including writable flags and item schema URIs.",inputSchema:qe,call:async()=>R({resources:he,note:"tabs, blueprints, and blueprint-views are dedicated resources; use tabs_query, blueprints_query, and blueprint intent tools instead of generic resource_* tools."})},{name:"resource_schema_get",description:"Read JSON Schema and mutation notes for one Beepflow resource item. Use before constructing an upsert item unless modifying an item read from the same resource.",inputSchema:{type:"object",additionalProperties:!1,required:["resource"],properties:{resource:{type:"string",enum:Ne,description:"Resource whose item JSON Schema and mutation notes should be read."}}},call:async e=>{let n=At(v(e,"resource"));return R(nt(n))}},{name:"resource_query",description:"Query a Beepflow resource with all, keys, or fieldEqualTo snapshot filters. Returns an item map. Use before editing existing resource items.",inputSchema:{type:"object",additionalProperties:!1,required:["resource"],properties:{resource:{type:"string",enum:Ne,description:"Resource collection to query."},all:{type:"boolean",description:"Return whole resource collection."},keys:{type:"array",items:{type:"string"},description:"Return items with these ids."},fieldEqualTo:{...We,description:"Return items whose fields equal these exact values."}}},call:async e=>{let n=At(v(e,"resource")),r=ma(e),o=await t.readResourceItems(n,r);return R(o)}},{name:"resource_upsert",description:"Create or update one writable Beepflow resource item. Mandatory: before calling resource_upsert, first call resource_schema_get for the same resource and ensure item matches that resource schema. Send full item state, not JSON patches; preserve unchanged fields.",inputSchema:{type:"object",additionalProperties:!1,required:["resource","item"],properties:{resource:{type:"string",enum:Ne,description:"Writable resource collection to create or update."},item:{...We,description:"Full item state with non-empty id; not a JSON patch."}}},call:async e=>{let n=Dt(v(e,"resource")),r=Xt(e,"item"),o=r.id;if(typeof o!="string"||!o)throw new Error("item.id must be non-empty string");E(n,r);let i=await t.upsertResourceItem(n,r);return R({ok:i})}},{name:"resource_delete",description:"Delete one writable Beepflow resource item by key. Destructive; use only when user intent is explicit.",inputSchema:{type:"object",additionalProperties:!1,required:["resource","key"],properties:{resource:{type:"string",enum:Ne,description:"Writable resource collection to delete from."},key:{type:"string",description:"Item id to delete."}}},call:async e=>{let n=Dt(v(e,"resource")),r=v(e,"key"),o=await t.deleteResourceItem(n,r);return R({ok:o})}}]}function Cs(t){return[{name:"status",description:"Mandatory first call before any Beepflow task. Call status at least once whenever user wants to inspect, edit, debug, or operate Beepflow, so agent has latest user status and MCP instructions. Returns MCP instructions, frontendUrl, backendUrl, current authenticated user location, current tab id, tab, blueprint, blueprint view, used operator definitions, and context fields when on a blueprint tab.",inputSchema:qe,call:async()=>Us(t)}]}function _s(t){return[{name:"results_read",description:"Read current blueprint result events for a result id such as tabId-test or tabId-explore. Blueprint result ids are tabId-test and tabId-explore.",inputSchema:Ta(),call:async e=>ca(t,e)},{name:"results_delete_state",description:"Stop and delete persisted result state for a result id. State-changing; use only when user intent is explicit.",inputSchema:Sa(),call:async e=>ua(t,e)},{name:"results_set_offsets",description:"Set current stream offsets for a result id. State-changing; use only when user intent is explicit.",inputSchema:Ia(),call:async e=>la(t,e)},{name:"stream_offset_extents_read",description:"Read stream partition offset extents from supported frontend live channels for runtime diagnostics.",inputSchema:xa(),call:async e=>fa(t,e)}]}function Ms(t){return[{name:"blueprint_operators_search",description:"Search blueprint operators with the same vector endpoint used by the editor menu. Use to find valid operator ids plus input/output metadata before editing blueprint nodes.",inputSchema:wa(),call:async e=>qs(t,e)},{name:"blueprint_context_fields_search",description:"Search contextual fields available to a blueprint using the editor menu field matching rules. Use to find fields available from blueprint context schemas.",inputSchema:Ra(),call:async e=>js(t,e)}]}function $s(t){return[{name:"integrations_list",description:"List integration types available from the backend integration API. Use before listing endpoints for an integration type.",inputSchema:qe,call:async()=>R(await Gn())},{name:"integration_blueprint_contexts_list",description:"List backend-defined blueprint context resource types, including executionKind, config fields, and type/config templates. If a resource type is absent, do not use it for blueprint context. Use before blueprint_tab_create or blueprint_context_update when choosing context.type, context.trigger, and context.config. executionKind=managed means choose trigger { executor: { enabled: true } } because integration runtime owns stream/event/poll lifecycle. executionKind=finite means choose trigger from user intent: manual for ad hoc/sample/start-once execution, cron for scheduled refresh, loop for fixed-delay repeated polling, blueprint for upstream blueprint invocation, and webhook only for generic GET/POST /:tabId/trigger HTTP calls, not integration webhooks.",inputSchema:{type:"object",additionalProperties:!1,properties:{integrationType:{type:"string",description:"Optional integration type from integrations_list; omit to return all blueprint context resource definitions including ManualTick."},resourceType:{type:"string",description:"Optional integration resource type to return one matching blueprint context definition."}}},call:async e=>R(await Kn(je(e,"integrationType"),je(e,"resourceType")))},{name:"integration_endpoints_list",description:"List backend integration endpoints for one integration type from workspace OpenAPI metadata, including access, side effect, request, response, confirmation metadata, parameters, requestBody, and payloadSchema for integration_endpoint_call. If payloadSchema includes connectionId, use integration_connections_list before integration_endpoint_call. MCP-only; external apps must integrate through a blueprint with webhook trigger.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type from integrations_list."}}},call:async e=>R(await Lt(v(e,"integrationType")))},{name:"integration_connections_list",description:"List redacted workspace connections for one integration type. Use this to find connectionId before integration_endpoint_call when endpoint payloadSchema declares connectionId. Use status only to disambiguate by current space when multiple matching connections exist. External apps must integrate through a blueprint with webhook trigger.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type whose connections should be listed."},spaceId:{type:"string",description:"Optional space id to restrict connection matches."}}},call:async e=>Fs(t,e)},{name:"integration_endpoint_schema_get",description:"MCP-only; not for external app data sources. Read OpenAPI 3.1 schema for one integration type. Use before integration_endpoint_call when full request/response schema details are needed. External apps must call blueprint webhook endpoints.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type whose OpenAPI schema should be read."}}},call:async e=>R(await Jt(v(e,"integrationType")))},{name:"integration_endpoint_call",description:"Call one allowlisted backend integration endpoint by integrationType and operationId. First call integration_endpoints_list or integration_endpoint_schema_get, then pass one payload object matching the exposed payloadSchema. For endpoints with connectionId in payloadSchema, first call integration_connections_list. Can cause external reads or writes, read local files for multipart uploads, and write binary downloads to disk. Mutating or destructive endpoints require confirm=true. Supports JSON, form, multipart files, request headers, redirects, and binary downloads. MCP-only; not an external app runtime integration path. External apps must call blueprint webhook endpoints.",inputSchema:ka(),call:async e=>R(await Qn(ba(e)))}]}async function Fs(t,e){let n={type:v(e,"integrationType")},r=je(e,"spaceId");return r&&(n.spaceId=r),R(await t.readResourceItems("connections",{fieldEqualTo:n}))}function Ws(t){return[{name:"auth_email_request_code",description:"Request email login code via Beepflow auth service.",inputSchema:{type:"object",additionalProperties:!1,required:["email"],properties:{email:{type:"string"}}},call:async e=>{let n=v(e,"email");return await pn(n),ha(`code sent to ${n}`)}},{name:"auth_email_verify_code",description:"Verify email login code and persist JWT for backend. Modifies stored credentials.",inputSchema:{type:"object",additionalProperties:!1,required:["email","code"],properties:{email:{type:"string"},code:{type:"string"}}},call:async e=>{let n=await dn(v(e,"email"),v(e,"code"));return t.close(),R(n)}},{name:"auth_google_sign_in",description:"Open Google OAuth login, wait for completion, and persist JWT for backend. Modifies stored credentials.",inputSchema:qe,call:async()=>{let e=await un();return e.status==="authenticated"&&t.close(),R(e)}},{name:"auth_sign_out",description:"Delete stored backend JWT. Modifies stored credentials.",inputSchema:qe,call:async()=>(t.close(),R(await an()))}]}async function qs(t,e){let n=v(e,"query"),r=Ue(e,"limit")??25,o=Yt(e,"includeDeprecated")??!1,[i,s]=await Promise.all([Gs(n,r),t.readResourceItems("blueprint-operators")]),a=[];for(let c of i){let d=s[c.operatorId];d?.hidden!==!0&&(!o&&d?.isDeprecated===!0||a.push(Ks(c,d)))}return R({results:a})}async function js(t,e){let n=v(e,"blueprintId"),r=v(e,"query"),o=Ue(e,"limit")??25,i=je(e,"connectionId"),[s,a,c]=await Promise.all([t.readResourceItem("blueprints",n),t.readResourceItems("schemas"),t.readResourceItems("connections")]);if(!s)return R({results:[]});let d=no(s,a,c,i),l=Zs(d,r,o);return R({results:l})}async function Us(t){let e=await Vs(),n=k(),r=await t.readResourceItem("user-locations",e),o=zs(r);if(!o)return R({instructions:Oe,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:e,tabId:null,location:r,tab:null,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]});let i=await t.readResourceItem("tabs",o);if(i?.type!=="blueprint")return R({instructions:Oe,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:e,tabId:o,location:r,tab:i,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]});let[s,a]=await Promise.all([t.readResourceItem("blueprints",o),t.readResourceItem("blueprint-views",o)]);if(!s)return R({instructions:Oe,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:e,tabId:o,location:r,tab:i,blueprint:null,blueprintView:a,blueprintOperators:{},contextFields:[]});let[c,d,l]=await Promise.all([Ls(t,s),t.readResourceItems("schemas"),t.readResourceItems("connections")]),h=no(s,d,l,void 0);return R({instructions:Oe,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:e,tabId:o,location:r,tab:i,blueprint:s,blueprintView:a,blueprintOperators:c,contextFields:h})}async function Ls(t,e){let n=Js(e),r=await t.readResourceItems("blueprint-operators"),o={};for(let i in n)o[i]=r[i]??null;return o}function Js(t){let e=t.nodes,n={};if(!J(e))return n;for(let r in e){let o=e[r];if(!J(o))continue;let i=o.operatorId;typeof i=="string"&&i.trim()&&(n[i]=!0)}return n}async function Vs(){let t=await X();if(!t)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let e=await Y(t),n=ne(e).email;if(!n)throw new Error("current jwt does not include email");return n}function zs(t){let e=t?.blueprint;if(!J(e))return;let n=e.id;return typeof n=="string"&&n.trim()?n:void 0}async function Gs(t,e){let n=await X();if(!n)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let r=await Y(n),o=k(),i=await fetch(`${o.backendUrl}/blueprint/operators/search`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({query:t,limit:e})});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`blueprint/operators/search failed: ${i.status} ${c}`.trim())}let s=await i.json().catch(()=>{});if(!Array.isArray(s))throw new Error("blueprint/operators/search returned invalid payload");let a=[];for(let c of s){if(!J(c))continue;let d=c.operatorId,l=c.score;typeof d!="string"||typeof l!="number"||a.push({operatorId:d,score:l})}return a}function Ks(t,e){return{kind:"operator",id:t.operatorId,name:Fe(e,"name"),categoryPath:Yr(e,"categoryPath"),aliases:Yr(e,"aliases"),doc:Fe(e,"doc"),inputs:sa(e),output:aa(e),score:t.score}}function no(t,e,n,r){let o=Qs(t.context,e),i=[];for(let s of o){if(!s.connectionId||r&&s.connectionId!==r)continue;let a=n[s.connectionId],c=ra(s.path);for(let d in s.schema)i.push({kind:"contextField",connectionId:s.connectionId,connectionLabel:a?.label??"???",path:c,field:d,type:s.schema[d]??"wildcard",score:0})}return i}function Qs(t,e){if(!t?.type)return[];let n=Hs(t);if(n){let i=e[n];return i?[i]:[]}let r=L(t.config,"connectionId"),o=[];for(let i in e){let s=e[i];if(s)switch(!0){case!!r:s.connectionId===r&&o.push(s);break;case s.type===t.type:o.push(s);break}}return o}function Hs(t){let e=t.config,n=L(e,"connectionId");if(n)switch(t.type){case"ApacheKafkaTopic":return j(n,{topicName:L(e,"topicName")});case"ShopifyWebhook":return j(n,{topicName:oa(e)});case"RabbitMQStream":case"MQTTTopic":return j(n,{streamPattern:L(e,"streamPattern")});case"QdrantCollection":case"BaseVectorCollection":case"BaseLookupCollection":case"BaseEventCollection":return j(n,{collectionName:L(e,"collectionName")});case"AerospikeSet":return j(n,{namespace:L(e,"namespace"),setName:L(e,"setName")});case"KaggleFile":return j(n,{datasetRef:L(e,"datasetRef"),fileName:L(e,"filePath")});case"GoogleDriveFile":return j(n,{fileId:L(e,"fileId"),parser:L(e,"parser")});case"GmailMessage":return j(n,{resource:"message"});case"GmailThread":return j(n,{resource:"thread"});case"GmailEvent":return j(n,{resource:"event"});case"GorgiasEvent":return j(n,{resource:"event",variant:ia(e)?"message":"ticket"});case"GorgiasTicket":return j(n,{resource:"ticket"})}}function Zs(t,e,n){let r=[];return t.forEach((o,i)=>{let s=Ys(e,Xs(o));s!==void 0&&r.push({field:{...o,score:s},index:i})}),r.sort((o,i)=>i.field.score-o.field.score||o.index-i.index).slice(0,n).map(o=>o.field)}function Xs(t){return[t.connectionLabel,t.path,t.field,t.type].join(" ")}function Ys(t,e){let n=Xr(t);if(n.length===0)return;let r=e.toLowerCase(),o=Xr(e),i=0;for(let s of n){let a=ea(s,o),c=Math.max(a,r.includes(s)?.82:0);if(c<=0)return;i+=c}return Number((i/n.length).toFixed(4))}function ea(t,e){let n=0;for(let r of e)switch(!0){case r===t:n=Math.max(n,1);break;case r.startsWith(t):n=Math.max(n,.92);break;case r.includes(t):n=Math.max(n,.82);break;case(t.length>=3&&r.length>=3):n=Math.max(n,ta(t,r));break}return n}function ta(t,e){let n=Math.max(t.length,e.length);if(n===0)return 0;let r=1-na(t,e)/n;return r>=.72?r*.7:0}function na(t,e){let n=Array.from({length:e.length+1},(o,i)=>i),r=Array.from({length:e.length+1},()=>0);for(let o=1;o<=t.length;o+=1){r[0]=o;for(let i=1;i<=e.length;i+=1){let s=t[o-1]===e[i-1]?0:1;r[i]=Math.min(n[i]+1,r[i-1]+1,n[i-1]+s)}for(let i=0;i<n.length;i+=1)n[i]=r[i]??0}return n[e.length]??0}function Xr(t){return t.toLowerCase().split(/[^a-z0-9]+/).map(e=>e.trim()).filter(Boolean)}function j(t,e){let n="";for(let r in e){let o=e[r];if(!o)return;n+=`${r} = ${o} `}if(n=n.trim(),!!n)return As("md5").update(`${t} ${n}`).digest("hex")}function ra(t){if(!t)return"";let e=[];for(let n in t)e.push(t[n]??"");return e.filter(Boolean).join("/")}function oa(t){let e=t?.webhookTopics;if(J(e)){for(let n in e)if(e[n]===!0)return n}}function ia(t){let e=t?.webhookTriggers;if(!J(e))return!1;for(let n in e)if(e[n]===!0&&Ds.includes(n))return!0;return!1}function L(t,e){let n=t?.[e];return typeof n=="string"&&n.trim()?n:void 0}function Fe(t,e){let n=t?.[e];return typeof n=="string"?n:void 0}function Yr(t,e){let n=t?.[e];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function sa(t){return Array.isArray(t?.inputs)?t.inputs.map(e=>ro(e)).filter(e=>e.name):[]}function aa(t){let e=t?.output;if(!J(e))return;let n=ro(e);return n.name?n:void 0}function ro(t){let e=J(t)?t:void 0,n=J(e?.type)?e.type:void 0;return{name:Fe(e,"name")??"",type:Fe(n,"type")??"",doc:Fe(e,"doc")}}async function ca(t,e){let n=v(e,"resultId"),r=Ue(e,"timeoutMs")??15e3,o=Ue(e,"quietMs")??250;await pa(t,n);let i=`${n}:events`,s=`results:${i}`;await t.start();let a=t.collectChannelEvents(s,c=>c.key===i,r,o);t.sendChannelEvent("results",{resource:"results",key:i,action:"subscribe-key"});try{return R(ga(await a))}finally{t.sendChannelEvent("results",{resource:"results",key:i,action:"unsubscribe-key"})}}async function pa(t,e){let n=da(e);if(!n)throw new Error(`invalid result id: ${e}; expected blueprintId-test or blueprintId-explore`);let[r,o]=await Promise.all([t.readResourceItem("tabs",n.blueprintId),t.readResourceItem("blueprints",n.blueprintId)]);if(!r)throw new Error(`tab not found for result: ${n.blueprintId}`);if(r.type!=="blueprint")throw new Error(`tab is not a blueprint: ${n.blueprintId}`);if(!o)throw new Error(`blueprint not found for result: ${n.blueprintId}`);if(o.mode!==n.mode)throw new Error(`blueprint mode mismatch for result: requested ${n.mode}, blueprint is ${o.mode}`)}function da(t){for(let e of["test","explore"]){let n=`-${e}`;if(t.endsWith(n)&&t.length>n.length)return{blueprintId:t.slice(0,-n.length),mode:e}}}async function ua(t,e){let n=v(e,"resultId");return await t.start(),t.sendChannelEvent("results",{resource:"results",key:n,action:"delete-state"}),R({ok:!0})}async function la(t,e){let n=v(e,"resultId"),r=Xt(e,"offsets");return await t.start(),t.sendChannelEvent("results",{resource:"results",key:n,action:"set-offsets",value:r}),R({ok:!0})}async function fa(t,e){let n=v(e,"channel");if(!eo.includes(n))throw new Error(`unsupported offset extent channel: ${n}`);let r=Xt(e,"key"),o=Ue(e,"timeoutMs")??15e3;await t.start();let i=t.waitForChannelEvent(n,s=>JSON.stringify(s.key)===JSON.stringify(r),o);t.sendChannelEvent(n,{resource:n,key:r,action:"on"});try{return R(await i)}finally{t.sendChannelEvent(n,{resource:n,key:r,action:"off"})}}function ma(t){let e=ya(t,"keys"),n=oo(t,"fieldEqualTo"),r=Yt(t,"all")??(!e&&!n),o={};return r&&(o.all=!0),e&&(o.keys=e),n&&(o.fieldEqualTo=n),o}function ga(t){let e={},n;for(let r of t){let o=r.value;switch(o?.kind){case"blueprint":n=o.value;break;case"node":{let i=o.nodeId;typeof i=="string"&&(e[i]=o.value);break}case"reset":n=void 0;for(let i in e)delete e[i];break}}return{public:n,publicByNode:e,events:t}}function R(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ha(t){return{content:[{type:"text",text:t}]}}function v(t,e){let n=ue(t)[e];if(typeof n!="string"||!n.trim())throw new Error(`invalid tool arguments: ${e} must be non-empty string`);return n}function je(t,e){if(t===void 0)return;let n=ue(t)[e];if(n!=null){if(typeof n!="string")throw new Error(`invalid tool arguments: ${e} must be string`);return n}}function Xt(t,e){let n=ue(t)[e];if(!J(n))throw new Error(`invalid tool arguments: ${e} must be object`);return n}function oo(t,e){let n=ue(t)[e];if(n!=null){if(!J(n))throw new Error(`invalid tool arguments: ${e} must be object`);return n}}function ya(t,e){let n=ue(t)[e];if(n!=null){if(!Array.isArray(n)||n.some(r=>typeof r!="string"))throw new Error(`invalid tool arguments: ${e} must be string array`);return n}}function Yt(t,e){let n=ue(t)[e];if(n!=null){if(typeof n!="boolean")throw new Error(`invalid tool arguments: ${e} must be boolean`);return n}}function Ue(t,e){let n=ue(t)[e];if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error(`invalid tool arguments: ${e} must be positive integer`);return n}}function ba(t){let e=ue(t);for(let n of["path","query","headers","body","files"])if(e[n]!==void 0)throw new Error(`invalid tool arguments: use payload instead of ${n}`);return{integrationType:v(t,"integrationType"),operationId:v(t,"operationId"),payload:oo(t,"payload"),outputFilePath:je(t,"outputFilePath"),confirm:Yt(t,"confirm")}}function ue(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid tool arguments: expected object");return t}function J(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function wa(){return{type:"object",additionalProperties:!1,required:["query"],properties:{query:{type:"string",description:"Operator name, alias, category, or behavior to search for."},limit:{type:"integer",minimum:1,description:"Maximum number of operator matches to return."},includeDeprecated:{type:"boolean",description:"Include deprecated operators in results when true."}}}}function Ra(){return{type:"object",additionalProperties:!1,required:["blueprintId","query"],properties:{blueprintId:{type:"string",description:"Blueprint id whose context schemas should be searched."},query:{type:"string",description:"Field name, path, connection label, or type to search for."},limit:{type:"integer",minimum:1,description:"Maximum number of context fields to return."},connectionId:{type:"string",description:"Optional connection id to restrict context field matches."}}}}function ka(){return{type:"object",additionalProperties:!1,required:["integrationType","operationId"],properties:{integrationType:{type:"string",description:"Integration type from integrations_list. MCP-only; not for external app data sources."},operationId:{type:"string",description:"Operation id from integration_endpoints_list or integration_endpoint_schema_get. MCP-only; not for external app data sources."},payload:{...We,description:"Single payload object matching payloadSchema from integration_endpoints_list or integration_endpoint_schema_get."},outputFilePath:{type:"string",description:"Local path where binary response downloads should be written."},confirm:{type:"boolean",description:"Required true for mutating or destructive endpoints after explicit user intent."}}}}function Ta(){return{type:"object",additionalProperties:!1,required:["resultId"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."},timeoutMs:{type:"integer",minimum:1,description:"Maximum wait in milliseconds."},quietMs:{type:"integer",minimum:1,description:"Quiet period before returning collected events."}}}}function Sa(){return{type:"object",additionalProperties:!1,required:["resultId"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."}}}}function Ia(){return{type:"object",additionalProperties:!1,required:["resultId","offsets"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."},offsets:{...We,description:"Stream offsets to set for current result state."}}}}function xa(){return{type:"object",additionalProperties:!1,required:["channel","key"],properties:{channel:{type:"string",enum:eo,description:"Offset extent live channel to read."},key:{...We,description:"Stream partition key to read extents for."},timeoutMs:{type:"integer",minimum:1,description:"Maximum wait in milliseconds."}}}}var Le="application/json";function io(t=Re()){return[{uri:"beepflow://resources",name:"Beepflow workspace resource registry",description:"Resource registry supported by this MCP server, including item schema URIs.",mimeType:Le,read:async()=>kt("beepflow://resources",he)},{uri:"beepflow://resource-schemas",name:"Beepflow workspace resource schema registry",description:"JSON Schema registry for resource items supported by this MCP server.",mimeType:Le,read:async()=>kt("beepflow://resource-schemas",tt)},...tt.map(e=>({uri:e.uri,name:`Beepflow ${e.resource} item schema`,description:`JSON Schema for ${e.resource} resource items.`,mimeType:Le,read:async()=>kt(e.uri,e)})),...he.map(e=>({uri:`beepflow://resources/${e.name}`,name:`Beepflow ${e.name}`,description:e.description,mimeType:Le,read:async()=>{let n=await t.readResourceItems(e.name);return kt(`beepflow://resources/${e.name}`,n)}}))]}function kt(t,e){return{contents:[{uri:t,mimeType:Le,text:JSON.stringify(e,null,2)}]}}var Tt=Re(),{server:va,closeServer:Ba}=tn({serverName:"mcp",serverVersion:"0.1.0",instructions:er,tools:to(Tt),resources:io(Tt),onInitialized:()=>{Tt.start().catch(()=>{})}});process.on("SIGINT",()=>so("SIGINT"));process.on("SIGTERM",()=>so("SIGTERM"));va.start();function so(t){Tt.close(),Ba(t)}
48
+ `.trim();function p(t,e){let n=A(t)[e];if(typeof n!="string"||!n.trim())throw new Error(`invalid tool arguments: ${e} must be non-empty string`);return n}function b(t,e){let n=A(t)[e];if(n!=null){if(typeof n!="string")throw new Error(`invalid tool arguments: ${e} must be string`);return n}}function ie(t,e){let n=A(t)[e];if(typeof n!="boolean")throw new Error(`invalid tool arguments: ${e} must be boolean`);return n}function ct(t,e){let n=A(t)[e];if(n!=null){if(typeof n!="boolean")throw new Error(`invalid tool arguments: ${e} must be boolean`);return n}}function pt(t,e){let n=A(t)[e];if(!ae(n))throw new Error(`invalid tool arguments: ${e} must be object`);return n}function dt(t,e){if(t===void 0)return;let n=A(t)[e];if(n!=null){if(!ae(n))throw new Error(`invalid tool arguments: ${e} must be object`);return n}}function se(t,e){let n=sr(t,e);if(!n)throw new Error(`invalid tool arguments: ${e} must be string array`);return n}function sr(t,e){let n=A(t)[e];if(n!=null){if(!Array.isArray(n)||n.some(r=>typeof r!="string"))throw new Error(`invalid tool arguments: ${e} must be string array`);return n}}function ar(t,e){let n=Gt(t,e);if(n===void 0)throw new Error(`invalid tool arguments: ${e} must be positive integer`);return n}function Gt(t,e){let n=A(t)[e];if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error(`invalid tool arguments: ${e} must be positive integer`);return n}}function cr(t,e){let n=A(t)[e];if(n!=null){if(typeof n!="number"||!Number.isFinite(n))throw new Error(`invalid tool arguments: ${e} must be number`);return n}}function F(t,e,n){let r=p(t,e);if(!n.includes(r))throw new Error(`invalid tool arguments: ${e} must be one of ${n.join(", ")}`);return r}function Te(t,e,n){let r=b(t,e);if(r!==void 0){if(!n.includes(r))throw new Error(`invalid tool arguments: ${e} must be one of ${n.join(", ")}`);return r}}function ut(t){if(t!==void 0)return sr(t,"ids")}function A(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid tool arguments: expected object");return t}function ae(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}var Zi={type:"object",additionalProperties:!0},lt={type:"object",additionalProperties:!1,required:["type","trigger"],properties:{type:Ye,trigger:Xe,config:et}};var Se=["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"];function ft(t){return{type:"object",additionalProperties:!1,properties:{ids:ee(t),fieldEqualTo:{...Zi,description:"Return items whose top-level fields equal these exact values."}}}}function m(t,e=["id"]){return{type:"object",additionalProperties:!1,required:e,properties:{id:{type:"string",description:"Tab/blueprint id."},...t}}}function K(t,e){return m({nodeId:{type:"string",description:"Blueprint node id."},inputName:{type:"string",description:"Operator input name."},...t},e)}function Ie(t,e){return m(t,e)}function ee(t){return{type:"array",items:{type:"string"},description:t}}function M(){return{type:"string",description:"CRDT list index. Defaults to 0.5 where supported."}}function f(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function mt(t,e){let n={};return t&&(n.keys=t),e&&(n.fieldEqualTo=e),!t&&!e&&(n.all=!0),n}async function W(t,e,n){return t.readResourceItems("tabs",mt(e,n))}async function pr(t,e){let n=await t.readResourceItem("tabs",e);if(!n)throw new Error(`tab not found: ${e}`);return n}function dr(t){return{name:"tabs_query",description:"Query visible tabs and folders. Use ids for exact tabs or fieldEqualTo for exact top-level field matches; with no filters, returns all visible tabs.",inputSchema:ft("Tab ids to read."),call:async e=>f(await W(t,ut(e),dt(e,"fieldEqualTo")))}}var Xi=(t=6)=>{let n="abcdefghijklmnopqrstuvwxyz",o=`1234567890${n}${n.toUpperCase()}`.split(""),i=new Uint8Array(t);return crypto.getRandomValues(i),i.reduce((s,a)=>`${s}${o[a&61]}`,"")},Q=Xi;function ht(t,e){if(e.insertAfterTabId){let o=t[e.insertAfterTabId];return o?Ce(t,o):.5}let n=gt(t).find(o=>o.parent===e.parent);return n?(n.order??1)*.5:(gt(t)[0]?.order??1)*.5}function Ce(t,e){let n=gt(t),r=n.findIndex(i=>i.id===e.id),o=r>=0?n[r+1]:void 0;return e.order*.5+(o?.order??1)*.5}function ur(t,e){let n=gt(t).filter(o=>o.parent===e.parent),r=n.findIndex(o=>o.id===e.id);return((n[r-1]?.order??0)+e.order)*.5}function lr(t,e){let n=0;for(let r in t){let o=t[r];o.parent===e&&o.order>n&&(n=o.order)}return n*.5+.5}function gt(t){let e=[];for(let n in t)e.push(t[n]);return e.sort((n,r)=>n.order-r.order)}function yt(t,e){if(e)return e;for(let n in t)return t[n].parent;throw new Error("parent is required when no existing tab can provide a default parent")}function xe(t,e){if(e.startsWith("spaces:"))return e.split(":")[1]??"";if(e.startsWith("tabs:")){let n=e.split(":")[1],r=n?t[n]?.spaceId:void 0;if(r)return r}throw new Error(`could not find spaceId for parent: ${e}`)}function _e(t,e){let n=t[e];if(!n)throw new Error(`tab not found: ${e}`);return n}async function ve(t,e){return E("tabs",e),t.upsertResourceItem("tabs",e)}function fr(t){return{name:"folder_tab_create",description:"Create a folder tab under a parent such as spaces:<spaceId> or tabs:<folderId>. Computes frontend-compatible order and parent space.",inputSchema:{type:"object",additionalProperties:!1,properties:{parent:{type:"string",description:"Parent id, normally spaces:<spaceId> or tabs:<folderId>. Optional only when an existing tab can provide a default parent."},name:{type:"string",description:"Folder name. Defaults to Untitled folder."},insertAfterTabId:{type:"string",description:"Optional tab id after which to insert in global frontend tab order."}}},call:async e=>f(await Yi(t,{parent:b(e,"parent"),name:b(e,"name"),insertAfterTabId:b(e,"insertAfterTabId")}))}}async function Yi(t,e){let n=await W(t),r=yt(n,e.parent),o=xe(n,r),i={id:Q(),updatedAt:z(),name:e.name??"Untitled folder",order:ht(n,{parent:r,insertAfterTabId:e.insertAfterTabId}),type:"folder",parent:r,spaceId:o};return await ve(t,i),i}function mr(t){return{name:"tab_rename",description:"Rename an existing tab or folder by preserving all other tab fields and upserting only the full updated tab record.",inputSchema:m({name:{type:"string",description:"New non-empty tab name."}},["id","name"]),call:async e=>{let n=p(e,"id"),r=await pr(t,n);return r.name=p(e,"name"),await ve(t,r),f(r)}}}function gr(t){return{name:"tab_move",description:"Move or reorder a tab. Supports explicit order, insertBeforeTabId, insertAfterTabId, or appending to a parent while updating parent spaceId like frontend drag/drop.",inputSchema:m({parent:{type:"string",description:"New parent id, normally spaces:<spaceId> or tabs:<folderId>."},order:{type:"number",description:"Explicit order value. Overrides insert and append order computation."},insertBeforeTabId:{type:"string",description:"Move before this sibling tab."},insertAfterTabId:{type:"string",description:"Move after this tab using frontend global ordering."}}),call:async e=>{let n=p(e,"id"),r=await W(t),o=r[n];if(!o)throw new Error(`tab not found: ${n}`);let i=es(r,o,e);return o.parent=i.parent,o.spaceId=i.spaceId,o.order=i.order,await ve(t,o),f(o)}}}function es(t,e,n){let r=cr(n,"order"),o=b(n,"insertBeforeTabId"),i=b(n,"insertAfterTabId"),s=o?_e(t,o):i?_e(t,i):void 0,a=b(n,"parent")??s?.parent??e.parent,c=s?.spaceId??xe(t,a),d=r??(o?ur(t,_e(t,o)):i?Ce(t,_e(t,i)):lr(t,a));return{parent:a,spaceId:c,order:d}}function hr(t){return{name:"tab_delete",description:"Delete a tab tree recursively. Folder tabs delete children; blueprint tabs delete matching blueprints and blueprint-views before deleting the tab.",inputSchema:m({},["id"]),call:async e=>f(await ts(t,p(e,"id")))}}async function ts(t,e){let n=await W(t),r=n[e];if(!r)throw new Error(`tab not found: ${e}`);let o=[],i=[],s=[];return await yr(t,n,r,o,i,s),{deletedTabs:o,deletedBlueprints:i,deletedBlueprintViews:s}}async function yr(t,e,n,r,o,i){let s=`tabs:${n.id}`;for(let a in e){let c=e[a];c.parent===s&&await yr(t,e,c,r,o,i)}n.type==="blueprint"?(await Promise.all([t.deleteResourceItem("blueprints",n.id),t.deleteResourceItem("blueprint-views",n.id),t.deleteResourceItem("tabs",n.id)]),o.push(n.id),i.push(n.id)):await t.deleteResourceItem("tabs",n.id),r.push(n.id)}async function br(t,e,n){return t.readResourceItems("blueprints",mt(e,n))}function wr(t){return{name:"blueprints_query",description:"Query visible blueprint definitions. Use ids for exact blueprints or fieldEqualTo for exact top-level field matches; with no filters, returns all visible blueprints.",inputSchema:ft("Blueprint ids to read."),call:async e=>f(await br(t,ut(e),dt(e,"fieldEqualTo")))}}function Kt(t){if(!t)throw new Error("blueprint context trigger is required");let e=0;for(let n of["manual","cron","loop","blueprint","webhook","executor"])t[n]!==void 0&&e++;if(e!==1)throw new Error("blueprint context trigger must contain exactly one branch")}function bt(t){let e=t.type,n=t.trigger;if(typeof e!="string"||!e.trim())throw new Error("context.type must be non-empty string");if(!ae(n))throw new Error("context.trigger must be object");Kt(n);let r={type:e,trigger:n};return ae(t.config)&&(r.config=t.config),r}function Rr(t){return{name:"blueprint_tab_create",description:"Create a blueprint tab plus matching blueprint and blueprint-view records with one shared id. Requires context with exactly one trigger branch. After create, tell user blueprint URL: `${status.frontendUrl}/${encodeURIComponent(tab.id)}`. For external app integrations, use a blueprint with webhook trigger and tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(tab.id)}/trigger`.",inputSchema:{type:"object",additionalProperties:!1,required:["context"],properties:{context:{...lt,description:"Blueprint context with type, trigger, and optional config. Trigger must have exactly one branch."},parent:{type:"string",description:"Parent id, normally spaces:<spaceId> or tabs:<folderId>. Optional only when existing tabs can provide a default."},name:{type:"string",description:"Tab name. Defaults to Untitled."},mode:{type:"string",enum:["test","explore"],description:"Initial mode. Defaults to test."},testRecordsAmount:{type:"integer",minimum:1,description:"Initial number of test records. Defaults to 1."},insertAfterTabId:{type:"string",description:"Optional tab id after which to insert."}}},call:async e=>f(await ns(t,{context:bt(pt(e,"context")),parent:b(e,"parent"),name:b(e,"name"),mode:Te(e,"mode",["test","explore"]),testRecordsAmount:Gt(e,"testRecordsAmount"),insertAfterTabId:b(e,"insertAfterTabId")}))}}async function ns(t,e){let n=await W(t),r=Q(),o=yt(n,e.parent),i=xe(n,o),s={id:r,updatedAt:z(),name:e.name??"Untitled",order:ht(n,{parent:o,insertAfterTabId:e.insertAfterTabId}),type:"blueprint",parent:o,spaceId:i},a={id:r,updatedAt:z(),mode:e.mode??"test",nodes:{},context:e.context,testRecordsAmount:e.testRecordsAmount??1,desiredState:"inactive"},c={id:r,updatedAt:z(),nodes:{}};return Kt(a.context.trigger),E("tabs",s),E("blueprints",a),E("blueprint-views",c),await Promise.all([t.upsertResourceItem("tabs",s),t.upsertResourceItem("blueprints",a),t.upsertResourceItem("blueprint-views",c)]),{tab:s,blueprint:a,blueprintView:c}}async function g(t,e){let[n,r,o]=await Promise.all([t.readResourceItem("tabs",e),t.readResourceItem("blueprints",e),t.readResourceItem("blueprint-views",e)]);if(!n)throw new Error(`tab not found: ${e}`);if(n.type!=="blueprint")throw new Error(`tab is not a blueprint: ${e}`);if(!r)throw new Error(`blueprint not found: ${e}`);if(!o)throw new Error(`blueprint view not found: ${e}`);return rs(r),os(o),{tab:n,blueprint:r,blueprintView:o}}function rs(t){t.nodes??={}}function os(t){t.nodes??={}}function kr(t){return{name:"blueprint_tab_duplicate",description:"Duplicate a blueprint tab by cloning tab, blueprint, and blueprint-view with a new shared id. Only top-level ids are remapped; node ids are preserved like frontend tab duplicate. After duplicate, tell user blueprint URL: `${status.frontendUrl}/${encodeURIComponent(tab.id)}`.",inputSchema:m({name:{type:"string",description:"Optional duplicated tab name. Defaults to source name plus *."}}),call:async e=>f(await is(t,p(e,"id"),b(e,"name")))}}async function is(t,e,n){let r=await W(t),o=await g(t,e),i=Q(),s=structuredClone(o.tab);s.id=i,s.updatedAt=z(),s.name=n??`${o.tab.name}*`,s.order=Ce(r,o.tab);let a=structuredClone(o.blueprint);a.id=i,a.updatedAt=z(),a.mode=a.mode??"test";let c=structuredClone(o.blueprintView);return c.id=i,c.updatedAt=z(),E("tabs",s),E("blueprints",a),E("blueprint-views",c),await Promise.all([t.upsertResourceItem("tabs",s),t.upsertResourceItem("blueprints",a),t.upsertResourceItem("blueprint-views",c)]),{tab:s,blueprint:a,blueprintView:c}}async function B(t,e){return Qt(e),E("blueprints",e),t.upsertResourceItem("blueprints",e)}function Qt(t){for(let e in t.nodes){let n=t.nodes[e];for(let r in n.inputs){let o=n.inputs[r];for(let i in o.values)ss(o.values[i])}}}function ss(t){(!Object.prototype.hasOwnProperty.call(t,"literal")||t.literal===void 0)&&(t.literal=null)}function Tr(t){return{name:"blueprint_context_update",description:"Replace blueprint context as one unit, including type, config, and exactly one trigger branch. When integrating external apps, set webhook trigger and tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(blueprint.id)}/trigger`.",inputSchema:m({context:{...lt,description:"Full replacement context with type, trigger, and optional config. Trigger must have exactly one branch."}},["id","context"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id"));return n.context=bt(pt(e,"context")),await B(t,n),f(n)}}}async function ce(t,e,n){let r=await X();if(!r)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let o=await Y(r),i=k(),s=await fetch(`${i.backendUrl}/blueprints/${t}/modes/${e}/${n}`,{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"}});if(!s.ok){let a=await s.text().catch(()=>"");throw new Error(`blueprint runtime action failed: ${s.status} ${a}`.trim())}return{ok:!0,status:s.status,blueprintId:t,mode:e,action:n}}function pe(t,e,n,r,o){return{name:e,description:n,inputSchema:m({mode:{type:"string",enum:["test","explore"],description:r?"Target mode.":"Mode to use. Defaults to current blueprint mode."}},r?["id","mode"]:["id"]),call:async i=>{let s=p(i,"id"),c=Te(i,"mode",["test","explore"])??(await g(t,s)).blueprint.mode;return f(await o(s,c))}}}function Sr(t){return pe(t,"blueprint_mode_set","Switch blueprint mode through backend runtime endpoint to preserve side effects.",!0,async(e,n)=>ce(e,n,"switch-mode"))}function Ir(t){return{name:"blueprint_test_records_set",description:"Set blueprint testRecordsAmount for test mode data generation. Uses replicated blueprint upsert; value must be at least 1.",inputSchema:m({amount:{type:"integer",minimum:1,description:"Number of test records."}},["id","amount"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id"));return n.testRecordsAmount=ar(e,"amount"),await B(t,n),f(n)}}}function xr(t){return pe(t,"blueprint_test_records_shuffle","Regenerate test records through backend /modes/test/shuffle-records endpoint.",!1,async e=>ce(e,"test","shuffle-records"))}function vr(t){return pe(t,"blueprint_runtime_start","Start blueprint runtime for supplied mode or current blueprint mode through backend endpoint. When starting webhook trigger blueprint, tell user webhook URL: `${status.backendUrl}/${encodeURIComponent(id)}/trigger`. Webhook runs only while blueprint is active in explore mode. External apps integrate by calling this blueprint webhook endpoint.",!1,async(e,n)=>ce(e,n,"start"))}function Br(t){return pe(t,"blueprint_runtime_stop","Stop blueprint runtime for supplied mode or current blueprint mode through backend endpoint.",!1,async(e,n)=>ce(e,n,"stop"))}function Pr(t){return{name:"blueprint_recompute_on_change_set",description:"Set recomputeOnChange to always or manual. Frontend treats undefined as always; this tool stores explicit value for clarity.",inputSchema:m({value:{type:"string",enum:["always","manual"],description:"Recompute behavior."}},["id","value"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id"));return n.recomputeOnChange=F(e,"value",["always","manual"]),await B(t,n),f(n)}}}function Er(t){return{name:"blueprint_mock_never_set",description:"Set or clear blueprint-level mockNever. enabled=true stores true; enabled=false clears the optional field like frontend toggle.",inputSchema:m({enabled:{type:"boolean",description:"Whether to disable mocking for all nodes."}},["id","enabled"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id"));return ie(e,"enabled")?n.mockNever=!0:delete n.mockNever,await B(t,n),f(n)}}}async function H(t,e){let n=await t.readResourceItems("blueprint-operators"),r={};for(let o in e.nodes){let i=n[e.nodes[o].operatorId];i&&(r[i.id]=i)}return{...n,...r}}function Ht(t){if(Object.keys(t).length===0)return;let e=null,n=null;for(let r in t)isNaN(parseFloat(r))||(n===null||parseFloat(r)<n)&&(e=r,n=parseFloat(r));return n!==null?t[e]:void 0}function Nr(t){let e=Object.keys(t).filter(i=>!isNaN(parseFloat(i))).sort((i,s)=>parseFloat(i)-parseFloat(s));if(e.length===0)return"0.5";let n=e[e.length-1],r=parseFloat(n);return((r+(Math.floor(r)+1))/2).toPrecision(15).replace(/0+$/,"").replace(/\.$/,"")}function de(t,e){let n=Nr(t);return t[n]=e,n}var Ar=new Set(["boolean","string","number","datetime","map","binary","wildcard","list of boolean","list of string","list of number","list of datetime","list of map","list of binary","list of wildcard"]);function w(t,e){let n=t.nodes[e];if(!n)throw new Error(`blueprint node not found: ${e}`);return n}function $(t,e){let n=t.inputs[e];if(!n)throw new Error(`node input not found: ${t.id}.${e}`);return n.values??={},n}function wt(t,e,n,r){let i=$(w(t,e),n).values[r];if(!i)throw new Error(`input value not found: ${e}.${n}[${r}]`);return i}function Me(t,e){let n=t[e];if(!n)throw new Error(`blueprint operator not found: ${e}`);return n}function Be(t,e){let n=t.inputs.find(r=>r.name===e);if(!n)throw new Error(`operator input not found: ${t.id}.${e}`);return n}function Rt(t,e){let n=t.output;if(!n||n.name!==e)throw new Error(`operator output not found: ${t.id}.${e}`);return n}function q(t){delete t.nodeId,delete t.operatorInputId,delete t.nodeInputIndex}function Dr(t,e){t.nodeId=e.nodeId,t.operatorInputId=e.operatorInputId,t.nodeInputIndex=e.nodeInputIndex}function Pe(t,e,n,r,o){let i=w(t,n.nodeId),s=w(t,r.nodeId),a=Me(e,i.operatorId),c=Me(e,s.operatorId);Rt(a,n.pinName);let d=Be(c,r.pinName),l=$(s,r.pinName),h=n.index??"0.5",y=as(l,d,r.index,o),S=l.values[y];return S.nodeId=i.id,S.operatorInputId=n.pinName,S.nodeInputIndex=h,y}function Or(t,e){let n=w(t,e.nodeId),r=e.index??"0.5";if(e.pinPosition==="input"){let o=wt(t,n.id,e.pinName,r);q(o);return}for(let o in t.nodes)for(let i in t.nodes[o].inputs)for(let s in t.nodes[o].inputs[i].values){let a=t.nodes[o].inputs[i].values[s];a.nodeId===n.id&&a.operatorInputId===e.pinName&&a.nodeInputIndex===r&&q(a)}}function as(t,e,n,r){if(r)return n?(t.values[n]??={literal:null},n):de(t.values,{literal:null});if(n){if(!(n in t.values))throw new Error(`input value not found: ${e.name}[${n}]`);return n}return e.type.isArray?de(t.values,{literal:null}):"0.5"in t.values?"0.5":(t.values["0.5"]={literal:null},"0.5")}function Cr(t){return{name:"blueprint_pins_connect",description:"Connect one output pin to one input pin by writing pointer fields on target input value. Validates nodes and pin names; can create target array element. For newly created operator nodes, prefer passing inputConnections to blueprint_operator_node_add instead of calling this after creation, so layout sees graph edges before assigning coordinates.",inputSchema:m({sourceNodeId:{type:"string"},sourceOutputName:{type:"string"},sourceIndex:M(),targetNodeId:{type:"string"},targetInputName:{type:"string"},targetIndex:M(),createTargetArrayElement:{type:"boolean",description:"Append target input value before connecting."}},["id","sourceNodeId","sourceOutputName","targetNodeId","targetInputName"]),call:async e=>{let n=await g(t,p(e,"id")),r=Pe(n.blueprint,await H(t,n.blueprint),{nodeId:p(e,"sourceNodeId"),pinName:p(e,"sourceOutputName"),index:b(e,"sourceIndex")},{nodeId:p(e,"targetNodeId"),pinName:p(e,"targetInputName"),index:b(e,"targetIndex")},ct(e,"createTargetArrayElement")??!1);return await B(t,n.blueprint),f({targetIndex:r,blueprint:n.blueprint})}}}function D(t,e,n,r,o){return{name:t,description:e,inputSchema:n,call:async i=>{let{blueprint:s}=await g(r,p(i,"id"));return o(s,i),await B(r,s),f(s)}}}function _r(t){return D("blueprint_pin_unlink","Unlink an input pin value or all downstream links from an output pin.",m({nodeId:{type:"string"},pinName:{type:"string"},pinPosition:{type:"string",enum:["input","output"]},index:M()},["id","nodeId","pinName","pinPosition"]),t,(e,n)=>Or(e,{nodeId:p(n,"nodeId"),pinName:p(n,"pinName"),pinPosition:F(n,"pinPosition",["input","output"]),index:b(n,"index")}))}async function te(t,e){let n=await t.readResourceItem("blueprint-operators",e);if(!n)throw new Error(`blueprint operator not found: ${e}`);if(!Array.isArray(n.inputs))throw new Error(`blueprint operator has invalid inputs: ${e}`);return n}async function Z(t,e,n){Qt(e),E("blueprints",e),E("blueprint-views",n);let[r,o]=await Promise.all([t.upsertResourceItem("blueprints",e),t.upsertResourceItem("blueprint-views",n)]);return{blueprintOk:r,blueprintViewOk:o}}function cs(t,e=Q()){let n={id:e,operatorId:t.id,inputs:{}};for(let r of t.inputs)r.type.isArray?n.inputs[r.name]={isArray:!0,values:{}}:n.inputs[r.name]={values:{"0.5":{literal:null}}};return n}function Ee(t,e,n){let r=cs(n);return t.nodes[r.id]=r,e.nodes[r.id]={id:r.id},r}function Mr(t){return{name:"blueprint_node_input_literal_set",description:"Set a node input literal at a CRDT value index. Defaults index to 0.5. With disconnect=true, clears upstream pointer fields first. For newly created operator nodes, prefer inputLiterals on blueprint_operator_node_add instead of setting literals afterward.",inputSchema:K({literal:{description:"JSON literal value to set."},index:M(),disconnect:{type:"boolean",description:"Clear upstream connection fields when true."}},["id","nodeId","inputName","literal"]),call:async e=>{let{blueprint:n}=await g(t,p(e,"id")),r=Zt(n,p(e,"nodeId"),p(e,"inputName"),b(e,"index")??"0.5",A(e).literal,ct(e,"disconnect")??!1);return await B(t,n),f({value:r,blueprint:n})}}}function Zt(t,e,n,r,o,i){let s=wt(t,e,n,r);return s.literal=o,i&&q(s),s}function $r(t){return{name:"blueprint_operator_node_add",description:"Add an operator node using frontend default input creation. Leaves view position unset so frontend can place it after measuring dimensions. When creating connected or configured nodes, set inputConnections and inputLiterals in this same call. Prefer this over blueprint_pins_connect and blueprint_node_input_literal_set immediately after creation because frontend uses connections present at first render to place missing-position nodes correctly.",inputSchema:Ie({operatorId:{type:"string",description:"Registered blueprint operator id."},inputConnections:{type:"array",description:"Input connections to apply before first write. Use for all known input links when creating a node; prefer this over blueprint_pins_connect after creation because frontend layout uses these connections before assigning coordinates.",items:{type:"object",additionalProperties:!1,required:["inputName","sourceNodeId","sourceOutputName","sourceIndex"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},sourceNodeId:{type:"string",description:"Existing source node id."},sourceOutputName:{type:"string",description:"Source output pin name."},sourceIndex:{type:"string",description:"Source output CRDT index."},targetIndex:{type:"string",description:"Target input CRDT index. Defaults to 0.5 for scalar inputs."},createTargetArrayElement:{type:"boolean",description:"Append target input value before connecting."}}}},inputLiterals:{type:"array",description:"Input literals to apply before first write. Use for all known literal inputs when creating a node; prefer this over blueprint_node_input_literal_set immediately after creation. Same behavior as blueprint_node_input_literal_set.",items:{type:"object",additionalProperties:!1,required:["inputName","literal"],properties:{inputName:{type:"string",description:"Input pin name on the new node."},literal:{description:"JSON literal value to set."},index:{type:"string",description:"Target input CRDT index. Defaults to 0.5."},disconnect:{type:"boolean",description:"Clear upstream connection fields when true."}}}}},["id","operatorId"]),call:async e=>{let n=await g(t,p(e,"id")),r=await te(t,p(e,"operatorId")),o=Ee(n.blueprint,n.blueprintView,r);ps(n.blueprint,o.id,ls(e));let i=us(e);return i.length>0&&ds(n.blueprint,await H(t,n.blueprint),o.id,i),await Z(t,n.blueprint,n.blueprintView),f({node:o,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function ps(t,e,n){for(let r of n){let o=t.nodes[e].inputs[r.inputName];o?.isArray&&r.index&&(o.values[r.index]??={literal:null});let i=o?.isArray?r.index??de(o.values,{literal:null}):r.index??"0.5";Zt(t,e,r.inputName,i,r.literal,r.disconnect??!1)}}function ds(t,e,n,r){for(let o of r){let i=e[t.nodes[n].operatorId].inputs.find(s=>s.name===o.inputName);Pe(t,e,{nodeId:o.sourceNodeId,pinName:o.sourceOutputName,index:o.sourceIndex},{nodeId:n,pinName:o.inputName,index:o.targetIndex},o.createTargetArrayElement??!!i?.type.isArray)}}function us(t){let e=A(t).inputConnections;if(e==null)return[];if(!Array.isArray(e))throw new Error("invalid tool arguments: inputConnections must be array");let n=[];for(let r=0;r<e.length;r++){let o=e[r];if(!ae(o))throw new Error(`invalid tool arguments: inputConnections[${r}] must be object`);let i=o.inputName,s=o.sourceNodeId,a=o.sourceOutputName,c=o.sourceIndex,d=o.targetIndex,l=o.createTargetArrayElement;if(typeof i!="string"||!i.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].inputName must be non-empty string`);if(typeof s!="string"||!s.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceNodeId must be non-empty string`);if(typeof a!="string"||!a.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceOutputName must be non-empty string`);if(typeof c!="string"||!c.trim())throw new Error(`invalid tool arguments: inputConnections[${r}].sourceIndex must be non-empty string`);if(d!==void 0&&typeof d!="string")throw new Error(`invalid tool arguments: inputConnections[${r}].targetIndex must be string`);if(l!==void 0&&typeof l!="boolean")throw new Error(`invalid tool arguments: inputConnections[${r}].createTargetArrayElement must be boolean`);n.push({inputName:i,sourceNodeId:s,sourceOutputName:a,sourceIndex:c,targetIndex:d,createTargetArrayElement:l})}return n}function ls(t){let e=A(t).inputLiterals;if(e==null)return[];if(!Array.isArray(e))throw new Error("invalid tool arguments: inputLiterals must be array");let n=[];for(let r=0;r<e.length;r++){let o=e[r];if(!ae(o))throw new Error(`invalid tool arguments: inputLiterals[${r}] must be object`);let i=o.inputName,s=o.literal,a=o.index,c=o.disconnect;if(typeof i!="string"||!i.trim())throw new Error(`invalid tool arguments: inputLiterals[${r}].inputName must be non-empty string`);if(!("literal"in o))throw new Error(`invalid tool arguments: inputLiterals[${r}].literal is required`);if(a!==void 0&&typeof a!="string")throw new Error(`invalid tool arguments: inputLiterals[${r}].index must be string`);if(c!==void 0&&typeof c!="boolean")throw new Error(`invalid tool arguments: inputLiterals[${r}].disconnect must be boolean`);n.push({inputName:i,literal:s,index:a,disconnect:c})}return n}function Fr(t){return{name:"blueprint_context_field_node_add",description:"Add a context field getter node using Base/function/blueprint/field-wildcard, setting outputType and Path literal. Apache Kafka context config is initialized from field connection/path when unset.",inputSchema:Ie({connectionId:{type:"string",description:"Context field connection id."},path:{type:"string",description:"Context field path such as topic or collection."},field:{type:"string",description:"Field name to store in Path literal."},type:{type:"string",enum:Se,description:"Field output type."}},["id","connectionId","path","field","type"]),call:async e=>{let n=await g(t,p(e,"id")),r=await te(t,"Base/function/blueprint/field-wildcard"),o=Ee(n.blueprint,n.blueprintView,r);return o.outputType=F(e,"type",Se),o.inputs.Path.values["0.5"]={literal:p(e,"field")},fs(n.blueprint.context,p(e,"connectionId"),p(e,"path")),await Z(t,n.blueprint,n.blueprintView),f({node:o,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function fs(t,e,n){t.type==="ApacheKafkaTopic"&&(t.config??={},t.config.topicName===void 0&&(t.config.connectionId=e,t.config.topicName=n))}function Wr(t){return{name:"blueprint_node_result_field_node_add",description:"Add a map/get node for a field inferred from an upstream node result. Sets Path literal and optionally connects source output to Target input.",inputSchema:Ie({path:{type:"string",description:"Result field path to store in Path literal."},sourceNodeId:{type:"string",description:"Optional upstream source node id to connect into Target."},sourceOutputName:{type:"string",description:"Optional upstream output name. Defaults to source operator output."}},["id","path"]),call:async e=>{let n=await g(t,p(e,"id")),r=await te(t,"Base/function/map/get"),o=Ee(n.blueprint,n.blueprintView,r);o.inputs.Path.values["0.5"]={literal:p(e,"path")};let i=b(e,"sourceNodeId");return i&&Pe(n.blueprint,await H(t,n.blueprint),{nodeId:i,pinName:b(e,"sourceOutputName")??await ms(t,n.blueprint,i)},{nodeId:o.id,pinName:"Target",index:"0.5"},!1),await Z(t,n.blueprint,n.blueprintView),f({node:o,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}async function ms(t,e,n){let r=e.nodes[n];if(!r)throw new Error(`source node not found: ${n}`);let o=await te(t,r.operatorId);if(!o.output?.name)throw new Error(`source node operator has no output: ${r.operatorId}`);return o.output.name}function qr(t){return{name:"blueprint_node_array_input_add",description:"Append an element to an array input using frontend CRDT list index generation. Returns new index.",inputSchema:K({literal:{description:"Optional initial literal value. Defaults to null."}},["id","nodeId","inputName"]),call:async e=>{let n=await g(t,p(e,"id")),r=n.blueprint.nodes[p(e,"nodeId")];if(!r)throw new Error("node not found");let o=await te(t,r.operatorId),i=A(e),s=Object.prototype.hasOwnProperty.call(i,"literal")?i.literal:null,a=gs(n.blueprint,o,r.id,p(e,"inputName"),s);return await B(t,n.blueprint),f({index:a,blueprint:n.blueprint})}}}function gs(t,e,n,r,o){let i=w(t,n);if(!Be(e,r).type.isArray)throw new Error(`operator input is not an array: ${r}`);let a=$(i,r);return de(a.values,{literal:o===void 0?null:o})}function jr(t){return D("blueprint_node_array_input_remove","Remove one CRDT-indexed value from a node array input.",K({index:M()},["id","nodeId","inputName","index"]),t,(e,n)=>hs(e,p(n,"nodeId"),p(n,"inputName"),p(n,"index")))}function hs(t,e,n,r){let o=$(w(t,e),n);if(!(r in o.values))throw new Error(`input value not found: ${e}.${n}[${r}]`);delete o.values[r]}function Ur(t){return D("blueprint_node_array_input_move","Move array input values by swapping two CRDT entries. Provide indexA/indexB or index plus direction up/down.",K({indexA:M(),indexB:M(),index:M(),direction:{type:"string",enum:["up","down"],description:"Adjacent move direction when indexA/indexB are omitted."}},["id","nodeId","inputName"]),t,(e,n)=>{let r=p(n,"inputName"),o=e.nodes[p(n,"nodeId")];if(!o)throw new Error("node not found");let i=b(n,"indexA")??p(n,"index"),s=b(n,"indexB")??bs(o.inputs[r]?.values??{},i,F(n,"direction",["up","down"]));ys(e,o.id,r,i,s)})}function ys(t,e,n,r,o){let i=$(w(t,e),n);if(!(r in i.values))throw new Error(`input value not found: ${e}.${n}[${r}]`);if(!(o in i.values))throw new Error(`input value not found: ${e}.${n}[${o}]`);let s=i.values[r];i.values[r]=i.values[o],i.values[o]=s}function bs(t,e,n){let r=[];for(let s in t)Number.isNaN(parseFloat(s))||r.push(s);r.sort((s,a)=>parseFloat(s)-parseFloat(a));let o=r.indexOf(e),i=n==="up"?r[o-1]:r[o+1];if(!i)throw new Error(`no adjacent input value ${n} from index ${e}`);return i}function Lr(t){return D("blueprint_node_input_zipping_set","Set or clear forceZipping on a node input. enabled=false clears the optional field like frontend.",K({enabled:{type:"boolean",description:"Whether to force zipping."}},["id","nodeId","inputName","enabled"]),t,(e,n)=>ws(e,p(n,"nodeId"),p(n,"inputName"),ie(n,"enabled")))}function ws(t,e,n,r){let o=$(w(t,e),n);r?o.forceZipping=!0:delete o.forceZipping}function Jr(t,e,n,r,o,i){if(i!==void 0&&!Ar.has(i))throw new Error(`unsupported type: ${i}`);let s=w(t,n),a=Me(e,s.operatorId);r==="output"?Rs(t,e,s,a,o,i):Ts(t,e,s,a,o,i)}function Yt(t,e){return t.outputType??e.output?.type.type}function Rs(t,e,n,r,o,i){let s=Rt(r,o);i===void 0||i===s.type.type?delete n.outputType:n.outputType=i;let a=i??s.type.type;for(let c in t.nodes)ks(t.nodes[c],e,n,o,a)}function ks(t,e,n,r,o){let i=e[t.operatorId];if(i)for(let s in t.inputs){let a=i.inputs.find(c=>c.name===s);if(a)for(let c in t.inputs[s].values){let d=t.inputs[s].values[c];d.nodeId!==n.id||d.operatorInputId!==r||(Is(o,t.inputs[s].type??a.type.type,a.type)?t.inputs[s].type=o:q(d))}}}function Ts(t,e,n,r,o,i){let s=Be(r,o),a=$(n,o);i===void 0||i===s.type.type?delete a.type:a.type=i;let c=i??s.type.type;for(let d in a.values){let l=a.values[d];if(!l.nodeId||!l.operatorInputId)continue;let h=t.nodes[l.nodeId],y=h?e[h.operatorId]:void 0;if(!h||!y?.output)continue;let S=Yt(h,y);xs(S,c)||q(l)}Ss(n,r,s.type,i)}function Ss(t,e,n,r){let o=Xt(n);if(o){for(let i of e.inputs)Xt(i.type)===o&&(r?t.inputs[i.name].type=r:delete t.inputs[i.name].type);e.output&&Xt(e.output.type)===o&&(r?t.outputType=r:delete t.outputType)}}function Is(t,e,n){return kt(e)?!n.allowedTypes||n.allowedTypes.length===0?!0:n.allowedTypes.some(r=>$e(t)?t.includes(r.type):r.type===t):$e(t)?t.includes(e):t===e}function xs(t,e){return!t||!e?!1:t==="list of wildcard"||e==="list of wildcard"?$e(t)&&$e(e):!kt(t)&&!kt(e)?$e(t)?t.includes(e):t===e:!0}function $e(t){return t?.startsWith("list of ")??!1}function kt(t){return t==="wildcard"||t==="list of wildcard"}function Xt(t){if(t&&kt(t.type))return t.linkType??"_"}function Vr(t,e){let n=new Set(e);for(let r of n)vs(t,r);for(let r in t.nodes){let o=t.nodes[r];for(let i in o.inputs)for(let s in o.inputs[i].values){let a=o.inputs[i].values[s];(n.has(o.id)||a.nodeId&&n.has(a.nodeId))&&q(a)}}}function zr(t,e,n){let r={};for(let o of n){let i=t.nodes[o],s=i?e[i.operatorId]:void 0,a=s?.inputs[0];if(!i||!s?.output||!a)continue;let c=Yt(i,s),d=i.inputs[a.name]?.type??a.type.type;if(c!==d)continue;let l=Ht(i.inputs[a.name]?.values??{});l?.nodeId&&(r[i.id]=structuredClone(l))}return r}function Gr(t,e,n){for(let r in t.inputs)for(let o in t.inputs[r].values){let i=t.inputs[r].values[o];i.nodeId&&(e[i.nodeId]?i.nodeId=e[i.nodeId]:n.has(i.nodeId)||q(i))}}function Kr(t,e){e?Dr(t,e):q(t)}function vs(t,e){if(!t.nodes[e])throw new Error(`blueprint node not found: ${e}`)}function Qr(t){return D("blueprint_node_connections_remove","Remove selected nodes input links and downstream links pointing to selected nodes.",m({nodeIds:ee("Node ids whose connections should be removed.")},["id","nodeIds"]),t,(e,n)=>Vr(e,se(n,"nodeIds")))}function Hr(t){return{name:"blueprint_node_type_set",description:"Set or clear an input/output resolved type. Omitting type or setting base type clears override; incompatible existing links are disconnected.",inputSchema:m({nodeId:{type:"string"},xputType:{type:"string",enum:["input","output"]},pinName:{type:"string"},type:{type:"string",enum:Se,description:"Resolved type override. Omit to reset to operator base type."}},["id","nodeId","xputType","pinName"]),call:async e=>{let n=await g(t,p(e,"id"));return Jr(n.blueprint,await H(t,n.blueprint),p(e,"nodeId"),F(e,"xputType",["input","output"]),p(e,"pinName"),Te(e,"type",Se)),await B(t,n.blueprint),f(n.blueprint)}}}function Zr(t){return D("blueprint_nodes_disabled_set","Set or clear disabled on selected nodes. disabled=false clears optional field like frontend.",m({nodeIds:ee("Node ids to update."),disabled:{type:"boolean",description:"Whether nodes should be disabled."}},["id","nodeIds","disabled"]),t,(e,n)=>Bs(e,se(n,"nodeIds"),ie(n,"disabled")))}function Bs(t,e,n){for(let r of e){let o=w(t,r);n?o.disabled=!0:delete o.disabled}}function Xr(t){return D("blueprint_node_mock_never_set","Set or clear node-level mockNever. enabled=false clears optional field like frontend.",m({nodeId:{type:"string"},enabled:{type:"boolean"}},["id","nodeId","enabled"]),t,(e,n)=>Ps(e,p(n,"nodeId"),ie(n,"enabled")))}function Ps(t,e,n){let r=w(t,e);n?r.mockNever=!0:delete r.mockNever}function Yr(t){return D("blueprint_node_skip_behavior_set","Set On Skip behavior. behavior=skip clears stored value because frontend default skip is undefined; behavior=null stores string null.",m({nodeId:{type:"string"},behavior:{type:"string",enum:["skip","null"]}},["id","nodeId","behavior"]),t,(e,n)=>Es(e,p(n,"nodeId"),F(n,"behavior",["skip","null"])))}function Es(t,e,n){let r=w(t,e);n==="skip"?delete r.skipBehavior:r.skipBehavior="null"}function eo(t){return{name:"blueprint_nodes_delete",description:"Delete blueprint nodes and view nodes. Mirrors frontend rewire behavior for deleted nodes whose first input type matches output type.",inputSchema:m({nodeIds:ee("Node ids to delete.")},["id","nodeIds"]),call:async e=>{let n=await g(t,p(e,"id"));return Ns(n.blueprint,n.blueprintView,await H(t,n.blueprint),se(e,"nodeIds")),await Z(t,n.blueprint,n.blueprintView),f({blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function Ns(t,e,n,r){let o=new Set(r);for(let s of o)w(t,s);let i=zr(t,n,o);for(let s in t.nodes)for(let a in t.nodes[s].inputs)for(let c in t.nodes[s].inputs[a].values){let d=t.nodes[s].inputs[a].values[c];!d.nodeId||!o.has(d.nodeId)||Kr(d,i[d.nodeId])}for(let s of o)delete t.nodes[s],delete e.nodes[s]}function to(t){return{name:"blueprint_nodes_duplicate",description:"Duplicate selected nodes and view nodes. Remaps internal copied-node references, drops missing-node references, and leaves new node positions for the frontend layout pass.",inputSchema:m({nodeIds:ee("Node ids to duplicate.")},["id","nodeIds"]),call:async e=>{let n=await g(t,p(e,"id")),r=As(n.blueprint,n.blueprintView,se(e,"nodeIds"));return await Z(t,n.blueprint,n.blueprintView),f({nodeIds:r,blueprint:n.blueprint,blueprintView:n.blueprintView})}}}function As(t,e,n){let r=new Set(n);for(let a of r)w(t,a);let o={},i=n.map(a=>structuredClone(t.nodes[a])),s=new Set;for(let a in t.nodes)s.add(a);for(let a of i){let c=Q();o[a.id]=c,a.id=c}for(let a of i)Gr(a,o,s);for(let a of i)t.nodes[a.id]=a;for(let a of n){let c=structuredClone(e.nodes[a]??{id:a}),d=o[a];c.id=d,Ds(c),e.nodes[d]=c}return n.map(a=>o[a])}function Ds(t){if(!t.style)return;let e={...t.style};delete e.x,delete e.y;for(let n in e){t.style=e;return}delete t.style}function no(t){return[dr(t),wr(t),fr(t),mr(t),gr(t),hr(t),Rr(t),kr(t),Tr(t),Sr(t),Ir(t),xr(t),vr(t),Br(t),Pr(t),Er(t),$r(t),Fr(t),Wr(t),Mr(t),qr(t),jr(t),Ur(t),Lr(t),Cr(t),_r(t),Qr(t),Hr(t),Zr(t),Xr(t),Yr(t),eo(t),to(t)]}var We={type:"object",additionalProperties:!0},qe={type:"object",additionalProperties:!1,properties:{}},io=["kafka-topic:offset-extents","rabbitmq-stream:offset-extents","base-event-collection:offset-extents","shopify-webhook:offset-extents"],Cs=["ticket-message-created","ticket-message-failed"];function so(t=Re()){return[..._s(t),...Ms(t),...$s(t),...no(t),...Fs(t),...Ws(t),...js(t)]}function _s(t){return[{name:"resources_list",description:"Discover Beepflow resources supported by this MCP server, including writable flags and item schema URIs.",inputSchema:qe,call:async()=>R({resources:he,note:"tabs, blueprints, and blueprint-views are dedicated resources; use tabs_query, blueprints_query, and blueprint intent tools instead of generic resource_* tools."})},{name:"resource_schema_get",description:"Read JSON Schema and mutation notes for one Beepflow resource item. Use before constructing an upsert item unless modifying an item read from the same resource.",inputSchema:{type:"object",additionalProperties:!1,required:["resource"],properties:{resource:{type:"string",enum:Ne,description:"Resource whose item JSON Schema and mutation notes should be read."}}},call:async e=>{let n=Ot(v(e,"resource"));return R(rt(n))}},{name:"resource_query",description:"Query a Beepflow resource with all, keys, or fieldEqualTo snapshot filters. Returns an item map. Use before editing existing resource items.",inputSchema:{type:"object",additionalProperties:!1,required:["resource"],properties:{resource:{type:"string",enum:Ne,description:"Resource collection to query."},all:{type:"boolean",description:"Return whole resource collection."},keys:{type:"array",items:{type:"string"},description:"Return items with these ids."},fieldEqualTo:{...We,description:"Return items whose fields equal these exact values."}}},call:async e=>{let n=Ot(v(e,"resource")),r=ha(e),o=await t.readResourceItems(n,r);return R(o)}},{name:"resource_upsert",description:"Create or update one writable Beepflow resource item. Mandatory: before calling resource_upsert, first call resource_schema_get for the same resource and ensure item matches that resource schema. Send full item state, not JSON patches; preserve unchanged fields.",inputSchema:{type:"object",additionalProperties:!1,required:["resource","item"],properties:{resource:{type:"string",enum:Ne,description:"Writable resource collection to create or update."},item:{...We,description:"Full item state with non-empty id; not a JSON patch."}}},call:async e=>{let n=Ct(v(e,"resource")),r=en(e,"item"),o=r.id;if(typeof o!="string"||!o)throw new Error("item.id must be non-empty string");E(n,r);let i=await t.upsertResourceItem(n,r);return R({ok:i})}},{name:"resource_delete",description:"Delete one writable Beepflow resource item by key. Destructive; use only when user intent is explicit.",inputSchema:{type:"object",additionalProperties:!1,required:["resource","key"],properties:{resource:{type:"string",enum:Ne,description:"Writable resource collection to delete from."},key:{type:"string",description:"Item id to delete."}}},call:async e=>{let n=Ct(v(e,"resource")),r=v(e,"key"),o=await t.deleteResourceItem(n,r);return R({ok:o})}}]}function Ms(t){return[{name:"status",description:"Mandatory first call before any Beepflow task. Call status at least once whenever user wants to inspect, edit, debug, or operate Beepflow, so agent has latest user status and MCP instructions. Returns MCP instructions, frontendUrl, backendUrl, current authenticated user location, current tab id, tab, blueprint, blueprint view, used operator definitions, and context fields when on a blueprint tab.",inputSchema:qe,call:async()=>Js(t)}]}function $s(t){return[{name:"results_read",description:"Read current blueprint result events for a result id such as tabId-test or tabId-explore. Blueprint result ids are tabId-test and tabId-explore.",inputSchema:Ia(),call:async e=>da(t,e)},{name:"results_delete_state",description:"Stop and delete persisted result state for a result id. State-changing; use only when user intent is explicit.",inputSchema:xa(),call:async e=>fa(t,e)},{name:"results_set_offsets",description:"Set current stream offsets for a result id. State-changing; use only when user intent is explicit.",inputSchema:va(),call:async e=>ma(t,e)},{name:"stream_offset_extents_read",description:"Read stream partition offset extents from supported frontend live channels for runtime diagnostics.",inputSchema:Ba(),call:async e=>ga(t,e)}]}function Fs(t){return[{name:"blueprint_operators_search",description:"Search blueprint operators with the same vector endpoint used by the editor menu. Use to find valid operator ids plus input/output metadata before editing blueprint nodes.",inputSchema:ka(),call:async e=>Us(t,e)},{name:"blueprint_context_fields_search",description:"Search contextual fields available to a blueprint using the editor menu field matching rules. Use to find fields available from blueprint context schemas.",inputSchema:Ta(),call:async e=>Ls(t,e)}]}function Ws(t){return[{name:"integrations_list",description:"List integration types available from the backend integration API. Use before listing endpoints for an integration type.",inputSchema:qe,call:async()=>R(await Xn())},{name:"integration_blueprint_contexts_list",description:"List backend-defined blueprint context resource types, including executionKind, config fields, and type/config templates. If a resource type is absent, do not use it for blueprint context. Use before blueprint_tab_create or blueprint_context_update when choosing context.type, context.trigger, and context.config. executionKind=managed means choose trigger { executor: { enabled: true } } because integration runtime owns stream/event/poll lifecycle. executionKind=finite means choose trigger from user intent: manual for ad hoc/sample/start-once execution, cron for scheduled refresh, loop for fixed-delay repeated polling, blueprint for upstream blueprint invocation, and webhook only for generic GET/POST /:tabId/trigger HTTP calls, not integration webhooks.",inputSchema:{type:"object",additionalProperties:!1,properties:{integrationType:{type:"string",description:"Optional integration type from integrations_list; omit to return all blueprint context resource definitions including ManualTick."},resourceType:{type:"string",description:"Optional integration resource type to return one matching blueprint context definition."}}},call:async e=>R(await Yn(je(e,"integrationType"),je(e,"resourceType")))},{name:"integration_endpoints_list",description:"List backend integration endpoints for one integration type from workspace OpenAPI metadata, including access, side effect, request, response, confirmation metadata, parameters, requestBody, and payloadSchema for integration_endpoint_call. If payloadSchema includes connectionId, use integration_connections_list before integration_endpoint_call. MCP-only; external apps must integrate through a blueprint with webhook trigger.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type from integrations_list."}}},call:async e=>R(await Vt(v(e,"integrationType")))},{name:"integration_connections_list",description:"List redacted workspace connections for one integration type. Use this to find connectionId before integration_endpoint_call when endpoint payloadSchema declares connectionId. Use status only to disambiguate by current space when multiple matching connections exist. External apps must integrate through a blueprint with webhook trigger.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type whose connections should be listed."},spaceId:{type:"string",description:"Optional space id to restrict connection matches."}}},call:async e=>qs(t,e)},{name:"integration_endpoint_schema_get",description:"MCP-only; not for external app data sources. Read OpenAPI 3.1 schema for one integration type. Use before integration_endpoint_call when full request/response schema details are needed. External apps must call blueprint webhook endpoints.",inputSchema:{type:"object",additionalProperties:!1,required:["integrationType"],properties:{integrationType:{type:"string",description:"Integration type whose OpenAPI schema should be read."}}},call:async e=>R(await zt(v(e,"integrationType")))},{name:"integration_endpoint_call",description:"Call one allowlisted backend integration endpoint by integrationType and operationId. First call integration_endpoints_list or integration_endpoint_schema_get, then pass one payload object matching the exposed payloadSchema. For endpoints with connectionId in payloadSchema, first call integration_connections_list. Can cause external reads or writes, read local files for multipart uploads, and write binary downloads to disk. Mutating or destructive endpoints require confirm=true. Supports JSON, form, multipart files, request headers, redirects, and binary downloads. MCP-only; not an external app runtime integration path. External apps must call blueprint webhook endpoints.",inputSchema:Sa(),call:async e=>R(await er(Ra(e)))}]}async function qs(t,e){let n={type:v(e,"integrationType")},r=je(e,"spaceId");return r&&(n.spaceId=r),R(await t.readResourceItems("connections",{fieldEqualTo:n}))}function js(t){return[{name:"auth_email_request_code",description:"Request email login code via Beepflow auth service.",inputSchema:{type:"object",additionalProperties:!1,required:["email"],properties:{email:{type:"string"}}},call:async e=>{let n=v(e,"email");return await un(n),ba(`code sent to ${n}`)}},{name:"auth_email_verify_code",description:"Verify email login code and persist JWT for backend. Modifies stored credentials.",inputSchema:{type:"object",additionalProperties:!1,required:["email","code"],properties:{email:{type:"string"},code:{type:"string"}}},call:async e=>{let n=await ln(v(e,"email"),v(e,"code"));return t.close(),R(n)}},{name:"auth_google_sign_in",description:"Open Google OAuth login, wait for completion, and persist JWT for backend. Modifies stored credentials.",inputSchema:qe,call:async()=>{let e=await fn();return e.status==="authenticated"&&t.close(),R(e)}},{name:"auth_sign_out",description:"Delete stored backend JWT. Modifies stored credentials.",inputSchema:qe,call:async()=>(t.close(),R(await pn()))}]}async function Us(t,e){let n=v(e,"query"),r=Ue(e,"limit")??25,o=tn(e,"includeDeprecated")??!1,[i,s]=await Promise.all([Qs(n,r),t.readResourceItems("blueprint-operators")]),a=[];for(let c of i){let d=s[c.operatorId];d?.hidden!==!0&&(!o&&d?.isDeprecated===!0||a.push(Hs(c,d)))}return R({results:a})}async function Ls(t,e){let n=v(e,"blueprintId"),r=v(e,"query"),o=Ue(e,"limit")??25,i=je(e,"connectionId"),[s,a,c]=await Promise.all([t.readResourceItem("blueprints",n),t.readResourceItems("schemas"),t.readResourceItems("connections")]);if(!s)return R({results:[]});let d=ao(s,a,c,i),l=Ys(d,r,o);return R({results:l})}async function Js(t){let e=await Gs(),n=k(),r=await t.readResourceItem("user-locations",e),o=Ks(r);if(!o)return R({instructions:Oe,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:e,tabId:null,location:r,tab:null,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]});let i=await t.readResourceItem("tabs",o);if(i?.type!=="blueprint")return R({instructions:Oe,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:e,tabId:o,location:r,tab:i,blueprint:null,blueprintView:null,blueprintOperators:{},contextFields:[]});let[s,a]=await Promise.all([t.readResourceItem("blueprints",o),t.readResourceItem("blueprint-views",o)]);if(!s)return R({instructions:Oe,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:e,tabId:o,location:r,tab:i,blueprint:null,blueprintView:a,blueprintOperators:{},contextFields:[]});let[c,d,l]=await Promise.all([Vs(t,s),t.readResourceItems("schemas"),t.readResourceItems("connections")]),h=ao(s,d,l,void 0);return R({instructions:Oe,frontendUrl:n.frontendUrl,backendUrl:n.backendUrl,email:e,tabId:o,location:r,tab:i,blueprint:s,blueprintView:a,blueprintOperators:c,contextFields:h})}async function Vs(t,e){let n=zs(e),r=await t.readResourceItems("blueprint-operators"),o={};for(let i in n)o[i]=r[i]??null;return o}function zs(t){let e=t.nodes,n={};if(!J(e))return n;for(let r in e){let o=e[r];if(!J(o))continue;let i=o.operatorId;typeof i=="string"&&i.trim()&&(n[i]=!0)}return n}async function Gs(){let t=await X();if(!t)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let e=await Y(t),n=ne(e).email;if(!n)throw new Error("current jwt does not include email");return n}function Ks(t){let e=t?.blueprint;if(!J(e))return;let n=e.id;return typeof n=="string"&&n.trim()?n:void 0}async function Qs(t,e){let n=await X();if(!n)throw new Error("missing jwt: set BEEPFLOW_JWT or run auth tool to persist token");let r=await Y(n),o=k(),i=await fetch(`${o.backendUrl}/blueprint/operators/search`,{method:"POST",headers:{Authorization:`Bearer ${r}`,"Content-Type":"application/json"},body:JSON.stringify({query:t,limit:e})});if(!i.ok){let c=await i.text().catch(()=>"");throw new Error(`blueprint/operators/search failed: ${i.status} ${c}`.trim())}let s=await i.json().catch(()=>{});if(!Array.isArray(s))throw new Error("blueprint/operators/search returned invalid payload");let a=[];for(let c of s){if(!J(c))continue;let d=c.operatorId,l=c.score;typeof d!="string"||typeof l!="number"||a.push({operatorId:d,score:l})}return a}function Hs(t,e){return{kind:"operator",id:t.operatorId,name:Fe(e,"name"),categoryPath:oo(e,"categoryPath"),aliases:oo(e,"aliases"),doc:Fe(e,"doc"),inputs:ca(e),output:pa(e),score:t.score}}function ao(t,e,n,r){let o=Zs(t.context,e),i=[];for(let s of o){if(!s.connectionId||r&&s.connectionId!==r)continue;let a=n[s.connectionId],c=ia(s.path);for(let d in s.schema)i.push({kind:"contextField",connectionId:s.connectionId,connectionLabel:a?.label??"???",path:c,field:d,type:s.schema[d]??"wildcard",score:0})}return i}function Zs(t,e){if(!t?.type)return[];let n=Xs(t);if(n){let i=e[n];return i?[i]:[]}let r=L(t.config,"connectionId"),o=[];for(let i in e){let s=e[i];if(s)switch(!0){case!!r:s.connectionId===r&&o.push(s);break;case s.type===t.type:o.push(s);break}}return o}function Xs(t){let e=t.config,n=L(e,"connectionId");if(n)switch(t.type){case"ApacheKafkaTopic":return j(n,{topicName:L(e,"topicName")});case"ShopifyWebhook":return j(n,{topicName:sa(e)});case"RabbitMQStream":case"MQTTTopic":return j(n,{streamPattern:L(e,"streamPattern")});case"QdrantCollection":case"BaseVectorCollection":case"BaseLookupCollection":case"BaseEventCollection":return j(n,{collectionName:L(e,"collectionName")});case"AerospikeSet":return j(n,{namespace:L(e,"namespace"),setName:L(e,"setName")});case"KaggleFile":return j(n,{datasetRef:L(e,"datasetRef"),fileName:L(e,"filePath")});case"GoogleDriveFile":return j(n,{fileId:L(e,"fileId"),parser:L(e,"parser")});case"GmailMessage":return j(n,{resource:"message"});case"GmailThread":return j(n,{resource:"thread"});case"GmailEvent":return j(n,{resource:"event"});case"GorgiasEvent":return j(n,{resource:"event",variant:aa(e)?"message":"ticket"});case"GorgiasTicket":return j(n,{resource:"ticket"})}}function Ys(t,e,n){let r=[];return t.forEach((o,i)=>{let s=ta(e,ea(o));s!==void 0&&r.push({field:{...o,score:s},index:i})}),r.sort((o,i)=>i.field.score-o.field.score||o.index-i.index).slice(0,n).map(o=>o.field)}function ea(t){return[t.connectionLabel,t.path,t.field,t.type].join(" ")}function ta(t,e){let n=ro(t);if(n.length===0)return;let r=e.toLowerCase(),o=ro(e),i=0;for(let s of n){let a=na(s,o),c=Math.max(a,r.includes(s)?.82:0);if(c<=0)return;i+=c}return Number((i/n.length).toFixed(4))}function na(t,e){let n=0;for(let r of e)switch(!0){case r===t:n=Math.max(n,1);break;case r.startsWith(t):n=Math.max(n,.92);break;case r.includes(t):n=Math.max(n,.82);break;case(t.length>=3&&r.length>=3):n=Math.max(n,ra(t,r));break}return n}function ra(t,e){let n=Math.max(t.length,e.length);if(n===0)return 0;let r=1-oa(t,e)/n;return r>=.72?r*.7:0}function oa(t,e){let n=Array.from({length:e.length+1},(o,i)=>i),r=Array.from({length:e.length+1},()=>0);for(let o=1;o<=t.length;o+=1){r[0]=o;for(let i=1;i<=e.length;i+=1){let s=t[o-1]===e[i-1]?0:1;r[i]=Math.min(n[i]+1,r[i-1]+1,n[i-1]+s)}for(let i=0;i<n.length;i+=1)n[i]=r[i]??0}return n[e.length]??0}function ro(t){return t.toLowerCase().split(/[^a-z0-9]+/).map(e=>e.trim()).filter(Boolean)}function j(t,e){let n="";for(let r in e){let o=e[r];if(!o)return;n+=`${r} = ${o} `}if(n=n.trim(),!!n)return Os("md5").update(`${t} ${n}`).digest("hex")}function ia(t){if(!t)return"";let e=[];for(let n in t)e.push(t[n]??"");return e.filter(Boolean).join("/")}function sa(t){let e=t?.webhookTopics;if(J(e)){for(let n in e)if(e[n]===!0)return n}}function aa(t){let e=t?.webhookTriggers;if(!J(e))return!1;for(let n in e)if(e[n]===!0&&Cs.includes(n))return!0;return!1}function L(t,e){let n=t?.[e];return typeof n=="string"&&n.trim()?n:void 0}function Fe(t,e){let n=t?.[e];return typeof n=="string"?n:void 0}function oo(t,e){let n=t?.[e];return Array.isArray(n)?n.filter(r=>typeof r=="string"):[]}function ca(t){return Array.isArray(t?.inputs)?t.inputs.map(e=>co(e)).filter(e=>e.name):[]}function pa(t){let e=t?.output;if(!J(e))return;let n=co(e);return n.name?n:void 0}function co(t){let e=J(t)?t:void 0,n=J(e?.type)?e.type:void 0;return{name:Fe(e,"name")??"",type:Fe(n,"type")??"",doc:Fe(e,"doc")}}async function da(t,e){let n=v(e,"resultId"),r=Ue(e,"timeoutMs")??15e3,o=Ue(e,"quietMs")??250;await ua(t,n);let i=`${n}:events`,s=`results:${i}`;await t.start();let a=t.collectChannelEvents(s,c=>c.key===i,r,o);t.sendChannelEvent("results",{resource:"results",key:i,action:"subscribe-key"});try{return R(ya(await a))}finally{t.sendChannelEvent("results",{resource:"results",key:i,action:"unsubscribe-key"})}}async function ua(t,e){let n=la(e);if(!n)throw new Error(`invalid result id: ${e}; expected blueprintId-test or blueprintId-explore`);let[r,o]=await Promise.all([t.readResourceItem("tabs",n.blueprintId),t.readResourceItem("blueprints",n.blueprintId)]);if(!r)throw new Error(`tab not found for result: ${n.blueprintId}`);if(r.type!=="blueprint")throw new Error(`tab is not a blueprint: ${n.blueprintId}`);if(!o)throw new Error(`blueprint not found for result: ${n.blueprintId}`);if(o.mode!==n.mode)throw new Error(`blueprint mode mismatch for result: requested ${n.mode}, blueprint is ${o.mode}`)}function la(t){for(let e of["test","explore"]){let n=`-${e}`;if(t.endsWith(n)&&t.length>n.length)return{blueprintId:t.slice(0,-n.length),mode:e}}}async function fa(t,e){let n=v(e,"resultId");return await t.start(),t.sendChannelEvent("results",{resource:"results",key:n,action:"delete-state"}),R({ok:!0})}async function ma(t,e){let n=v(e,"resultId"),r=en(e,"offsets");return await t.start(),t.sendChannelEvent("results",{resource:"results",key:n,action:"set-offsets",value:r}),R({ok:!0})}async function ga(t,e){let n=v(e,"channel");if(!io.includes(n))throw new Error(`unsupported offset extent channel: ${n}`);let r=en(e,"key"),o=Ue(e,"timeoutMs")??15e3;await t.start();let i=t.waitForChannelEvent(n,s=>JSON.stringify(s.key)===JSON.stringify(r),o);t.sendChannelEvent(n,{resource:n,key:r,action:"on"});try{return R(await i)}finally{t.sendChannelEvent(n,{resource:n,key:r,action:"off"})}}function ha(t){let e=wa(t,"keys"),n=po(t,"fieldEqualTo"),r=tn(t,"all")??(!e&&!n),o={};return r&&(o.all=!0),e&&(o.keys=e),n&&(o.fieldEqualTo=n),o}function ya(t){let e={},n;for(let r of t){let o=r.value;switch(o?.kind){case"blueprint":n=o.value;break;case"node":{let i=o.nodeId;typeof i=="string"&&(e[i]=o.value);break}case"reset":n=void 0;for(let i in e)delete e[i];break}}return{public:n,publicByNode:e,events:t}}function R(t){return{content:[{type:"text",text:JSON.stringify(t,null,2)}]}}function ba(t){return{content:[{type:"text",text:t}]}}function v(t,e){let n=ue(t)[e];if(typeof n!="string"||!n.trim())throw new Error(`invalid tool arguments: ${e} must be non-empty string`);return n}function je(t,e){if(t===void 0)return;let n=ue(t)[e];if(n!=null){if(typeof n!="string")throw new Error(`invalid tool arguments: ${e} must be string`);return n}}function en(t,e){let n=ue(t)[e];if(!J(n))throw new Error(`invalid tool arguments: ${e} must be object`);return n}function po(t,e){let n=ue(t)[e];if(n!=null){if(!J(n))throw new Error(`invalid tool arguments: ${e} must be object`);return n}}function wa(t,e){let n=ue(t)[e];if(n!=null){if(!Array.isArray(n)||n.some(r=>typeof r!="string"))throw new Error(`invalid tool arguments: ${e} must be string array`);return n}}function tn(t,e){let n=ue(t)[e];if(n!=null){if(typeof n!="boolean")throw new Error(`invalid tool arguments: ${e} must be boolean`);return n}}function Ue(t,e){let n=ue(t)[e];if(n!=null){if(typeof n!="number"||!Number.isInteger(n)||n<=0)throw new Error(`invalid tool arguments: ${e} must be positive integer`);return n}}function Ra(t){let e=ue(t);for(let n of["path","query","headers","body","files"])if(e[n]!==void 0)throw new Error(`invalid tool arguments: use payload instead of ${n}`);return{integrationType:v(t,"integrationType"),operationId:v(t,"operationId"),payload:po(t,"payload"),outputFilePath:je(t,"outputFilePath"),confirm:tn(t,"confirm")}}function ue(t){if(!t||typeof t!="object"||Array.isArray(t))throw new Error("invalid tool arguments: expected object");return t}function J(t){return!!t&&typeof t=="object"&&!Array.isArray(t)}function ka(){return{type:"object",additionalProperties:!1,required:["query"],properties:{query:{type:"string",description:"Operator name, alias, category, or behavior to search for."},limit:{type:"integer",minimum:1,description:"Maximum number of operator matches to return."},includeDeprecated:{type:"boolean",description:"Include deprecated operators in results when true."}}}}function Ta(){return{type:"object",additionalProperties:!1,required:["blueprintId","query"],properties:{blueprintId:{type:"string",description:"Blueprint id whose context schemas should be searched."},query:{type:"string",description:"Field name, path, connection label, or type to search for."},limit:{type:"integer",minimum:1,description:"Maximum number of context fields to return."},connectionId:{type:"string",description:"Optional connection id to restrict context field matches."}}}}function Sa(){return{type:"object",additionalProperties:!1,required:["integrationType","operationId"],properties:{integrationType:{type:"string",description:"Integration type from integrations_list. MCP-only; not for external app data sources."},operationId:{type:"string",description:"Operation id from integration_endpoints_list or integration_endpoint_schema_get. MCP-only; not for external app data sources."},payload:{...We,description:"Single payload object matching payloadSchema from integration_endpoints_list or integration_endpoint_schema_get."},outputFilePath:{type:"string",description:"Local path where binary response downloads should be written."},confirm:{type:"boolean",description:"Required true for mutating or destructive endpoints after explicit user intent."}}}}function Ia(){return{type:"object",additionalProperties:!1,required:["resultId"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."},timeoutMs:{type:"integer",minimum:1,description:"Maximum wait in milliseconds."},quietMs:{type:"integer",minimum:1,description:"Quiet period before returning collected events."}}}}function xa(){return{type:"object",additionalProperties:!1,required:["resultId"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."}}}}function va(){return{type:"object",additionalProperties:!1,required:["resultId","offsets"],properties:{resultId:{type:"string",description:"Blueprint result id, normally tabId-test or tabId-explore."},offsets:{...We,description:"Stream offsets to set for current result state."}}}}function Ba(){return{type:"object",additionalProperties:!1,required:["channel","key"],properties:{channel:{type:"string",enum:io,description:"Offset extent live channel to read."},key:{...We,description:"Stream partition key to read extents for."},timeoutMs:{type:"integer",minimum:1,description:"Maximum wait in milliseconds."}}}}var Le="application/json";function uo(t=Re()){return[{uri:"beepflow://resources",name:"Beepflow workspace resource registry",description:"Resource registry supported by this MCP server, including item schema URIs.",mimeType:Le,read:async()=>Tt("beepflow://resources",he)},{uri:"beepflow://resource-schemas",name:"Beepflow workspace resource schema registry",description:"JSON Schema registry for resource items supported by this MCP server.",mimeType:Le,read:async()=>Tt("beepflow://resource-schemas",nt)},...nt.map(e=>({uri:e.uri,name:`Beepflow ${e.resource} item schema`,description:`JSON Schema for ${e.resource} resource items.`,mimeType:Le,read:async()=>Tt(e.uri,e)})),...he.map(e=>({uri:`beepflow://resources/${e.name}`,name:`Beepflow ${e.name}`,description:e.description,mimeType:Le,read:async()=>{let n=await t.readResourceItems(e.name);return Tt(`beepflow://resources/${e.name}`,n)}}))]}function Tt(t,e){return{contents:[{uri:t,mimeType:Le,text:JSON.stringify(e,null,2)}]}}var St=Re(),{server:Pa,closeServer:Ea}=rn({serverName:"mcp",serverVersion:"0.1.0",instructions:ir,tools:so(St),resources:uo(St),onInitialized:()=>{St.start().catch(()=>{})}});process.on("SIGINT",()=>lo("SIGINT"));process.on("SIGTERM",()=>lo("SIGTERM"));Pa.start();function lo(t){St.close(),Ea(t)}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@beepflow/mcp",
3
- "version": "2026.5.2",
3
+ "version": "2026.5.3",
4
4
  "type": "module",
5
5
  "engines": {
6
6
  "node": ">=24.6.0"