@flexkit/studio 0.0.35 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (164) hide show
  1. package/README.md +81 -0
  2. package/dist/astro.d.ts +3 -5
  3. package/dist/astro.js +3 -8
  4. package/dist/chat-page-NWMI4XOE.js +2 -0
  5. package/dist/chat-page-NWMI4XOE.js.map +1 -0
  6. package/dist/chunk-2DXR5NJV.js +2 -0
  7. package/dist/chunk-2DXR5NJV.js.map +1 -0
  8. package/dist/chunk-3CPWATOI.js +2 -0
  9. package/dist/chunk-3CPWATOI.js.map +1 -0
  10. package/dist/chunk-5DHOBLAE.js +2 -0
  11. package/dist/chunk-5DHOBLAE.js.map +1 -0
  12. package/dist/chunk-6LYEDKFY.js +7 -0
  13. package/dist/chunk-6LYEDKFY.js.map +1 -0
  14. package/dist/chunk-7PDYCDX6.js +2 -0
  15. package/dist/chunk-7PDYCDX6.js.map +1 -0
  16. package/dist/chunk-7SK5YPHT.js +2 -0
  17. package/dist/chunk-7SK5YPHT.js.map +1 -0
  18. package/dist/chunk-AKQ6ELDX.js +2 -0
  19. package/dist/chunk-AKQ6ELDX.js.map +1 -0
  20. package/dist/{chunk-POQX5GIA.js → chunk-C2BPRGGQ.js} +47 -172
  21. package/dist/chunk-CSUHZFEP.js +2 -0
  22. package/dist/chunk-CSUHZFEP.js.map +1 -0
  23. package/dist/chunk-G4PYYHI3.js +2 -0
  24. package/dist/chunk-G4PYYHI3.js.map +1 -0
  25. package/dist/chunk-GZIMMYLK.js +2 -0
  26. package/dist/chunk-GZIMMYLK.js.map +1 -0
  27. package/dist/chunk-HROHAMPM.js +3 -0
  28. package/dist/chunk-HROHAMPM.js.map +1 -0
  29. package/dist/chunk-NNA4MLFC.js +3 -0
  30. package/dist/chunk-NNA4MLFC.js.map +1 -0
  31. package/dist/chunk-NSYO57O3.js +5 -0
  32. package/dist/chunk-NSYO57O3.js.map +1 -0
  33. package/dist/chunk-ODORXGGY.js +2 -0
  34. package/dist/chunk-ODORXGGY.js.map +1 -0
  35. package/dist/chunk-OUSEULBR.js +384 -0
  36. package/dist/chunk-OUSEULBR.js.map +1 -0
  37. package/dist/chunk-P6BZ4QP7.js +2 -0
  38. package/dist/chunk-P6BZ4QP7.js.map +1 -0
  39. package/dist/chunk-QQUNCDUB.js +2 -0
  40. package/dist/chunk-QQUNCDUB.js.map +1 -0
  41. package/dist/chunk-SZEGGBOC.js +2 -0
  42. package/dist/chunk-SZEGGBOC.js.map +1 -0
  43. package/dist/chunk-W2EBZZAY.js +3 -0
  44. package/dist/chunk-W2EBZZAY.js.map +1 -0
  45. package/dist/chunk-YINI2YKQ.js +4 -0
  46. package/dist/chunk-YINI2YKQ.js.map +1 -0
  47. package/dist/{core-handler-C3xC98bN.d.ts → core-handler-XAVVKLhV.d.ts} +0 -3
  48. package/dist/edit-entity-PVT34FD7.js +2 -0
  49. package/dist/edit-entity-PVT34FD7.js.map +1 -0
  50. package/dist/index.css +1403 -1
  51. package/dist/index.d.ts +433 -33
  52. package/dist/index.js +12 -395
  53. package/dist/index.js.map +1 -1
  54. package/dist/list-SQCN7HA3.js +2 -0
  55. package/dist/list-SQCN7HA3.js.map +1 -0
  56. package/dist/nextjs.d.ts +61 -56
  57. package/dist/nextjs.js +3 -8
  58. package/dist/pages-OIAPASPF.js +3 -0
  59. package/dist/pages-OIAPASPF.js.map +1 -0
  60. package/dist/plugin-pages-AHOA6YJE.js +2 -0
  61. package/dist/plugin-pages-AHOA6YJE.js.map +1 -0
  62. package/dist/project-selector-72VM6SUI.js +2 -0
  63. package/dist/project-selector-72VM6SUI.js.map +1 -0
  64. package/dist/root-4FGNRGCD.js +23 -0
  65. package/dist/root-4FGNRGCD.js.map +1 -0
  66. package/dist/root-5ZW536V7.js +2 -0
  67. package/dist/root-5ZW536V7.js.map +1 -0
  68. package/dist/root-IIILTOJI.js +31 -0
  69. package/dist/root-IIILTOJI.js.map +1 -0
  70. package/dist/root-QPQQ3DFJ.js +2 -0
  71. package/dist/root-QPQQ3DFJ.js.map +1 -0
  72. package/dist/search-2K2BU4UU.js +2 -0
  73. package/dist/{search-XKG5A7XM.js.map → search-2K2BU4UU.js.map} +1 -1
  74. package/dist/skills-pages-PSBRTFGK.js +2 -0
  75. package/dist/skills-pages-PSBRTFGK.js.map +1 -0
  76. package/dist/tanstack-start.d.ts +4 -6
  77. package/dist/tanstack-start.js +5 -12
  78. package/dist/ui.d.ts +12 -9
  79. package/dist/ui.js +1 -6
  80. package/dist/ui.js.map +1 -1
  81. package/dist/user-nav-QZFCICK3.js +2 -0
  82. package/dist/{user-nav-LSEOOH4E.js.map → user-nav-QZFCICK3.js.map} +1 -1
  83. package/package.json +30 -12
  84. package/dist/asset-3XMRPTA5.js +0 -2
  85. package/dist/asset-3XMRPTA5.js.map +0 -1
  86. package/dist/boolean-MTD44LXP.js +0 -2
  87. package/dist/boolean-MTD44LXP.js.map +0 -1
  88. package/dist/chunk-3VOTTOJT.js +0 -2
  89. package/dist/chunk-3VOTTOJT.js.map +0 -1
  90. package/dist/chunk-5I7Q5ODB.js +0 -2
  91. package/dist/chunk-5I7Q5ODB.js.map +0 -1
  92. package/dist/chunk-6NRQMG26.js +0 -2
  93. package/dist/chunk-6NRQMG26.js.map +0 -1
  94. package/dist/chunk-6V73336R.js +0 -623
  95. package/dist/chunk-7BOX7HHO.js +0 -2
  96. package/dist/chunk-7BOX7HHO.js.map +0 -1
  97. package/dist/chunk-7JFLGBWE.js +0 -2
  98. package/dist/chunk-7JFLGBWE.js.map +0 -1
  99. package/dist/chunk-AICNS7KW.js +0 -2
  100. package/dist/chunk-AICNS7KW.js.map +0 -1
  101. package/dist/chunk-CCXRYZ5I.js +0 -2
  102. package/dist/chunk-CCXRYZ5I.js.map +0 -1
  103. package/dist/chunk-D4XLXU2H.js +0 -2
  104. package/dist/chunk-D4XLXU2H.js.map +0 -1
  105. package/dist/chunk-FLT6RWXH.js +0 -2
  106. package/dist/chunk-FLT6RWXH.js.map +0 -1
  107. package/dist/chunk-GBM7VKFS.js +0 -2
  108. package/dist/chunk-GBM7VKFS.js.map +0 -1
  109. package/dist/chunk-HMMBYXYA.js +0 -2
  110. package/dist/chunk-HMMBYXYA.js.map +0 -1
  111. package/dist/chunk-IRY4KWB5.js +0 -2
  112. package/dist/chunk-IRY4KWB5.js.map +0 -1
  113. package/dist/chunk-JH4MVD36.js +0 -2
  114. package/dist/chunk-JH4MVD36.js.map +0 -1
  115. package/dist/chunk-JKHUO27E.js +0 -2
  116. package/dist/chunk-JKHUO27E.js.map +0 -1
  117. package/dist/chunk-LIV5RBWJ.js +0 -2
  118. package/dist/chunk-LIV5RBWJ.js.map +0 -1
  119. package/dist/chunk-PENRGDNC.js +0 -2
  120. package/dist/chunk-PENRGDNC.js.map +0 -1
  121. package/dist/chunk-QOX3QNMM.js +0 -2
  122. package/dist/chunk-QOX3QNMM.js.map +0 -1
  123. package/dist/chunk-QVBNGGOE.js +0 -2
  124. package/dist/chunk-QVBNGGOE.js.map +0 -1
  125. package/dist/chunk-S6MOM5G3.js +0 -2
  126. package/dist/chunk-S6MOM5G3.js.map +0 -1
  127. package/dist/chunk-UGRS4FEI.js +0 -2
  128. package/dist/chunk-UGRS4FEI.js.map +0 -1
  129. package/dist/chunk-USNXQOMJ.js +0 -2
  130. package/dist/chunk-USNXQOMJ.js.map +0 -1
  131. package/dist/chunk-UWMJBBTY.js +0 -2
  132. package/dist/chunk-UWMJBBTY.js.map +0 -1
  133. package/dist/chunk-W3Z33ETA.js +0 -2
  134. package/dist/chunk-W3Z33ETA.js.map +0 -1
  135. package/dist/chunk-WDRCARCP.js +0 -3
  136. package/dist/chunk-WDRCARCP.js.map +0 -1
  137. package/dist/chunk-WIUPQHZ5.js +0 -2
  138. package/dist/chunk-WIUPQHZ5.js.map +0 -1
  139. package/dist/chunk-WJ4ORIXF.js +0 -2
  140. package/dist/chunk-WJ4ORIXF.js.map +0 -1
  141. package/dist/chunk-YSLN4XT6.js +0 -2
  142. package/dist/chunk-YSLN4XT6.js.map +0 -1
  143. package/dist/datetime-C55QQQJK.js +0 -2
  144. package/dist/datetime-C55QQQJK.js.map +0 -1
  145. package/dist/editor-NZLXIOE7.js +0 -2
  146. package/dist/editor-NZLXIOE7.js.map +0 -1
  147. package/dist/project-selector-GQ24PVO6.js +0 -2
  148. package/dist/project-selector-GQ24PVO6.js.map +0 -1
  149. package/dist/search-XKG5A7XM.js +0 -2
  150. package/dist/select-SO3DICYX.js +0 -2
  151. package/dist/select-SO3DICYX.js.map +0 -1
  152. package/dist/switch-SU3OIXL6.js +0 -2
  153. package/dist/switch-SU3OIXL6.js.map +0 -1
  154. package/dist/text-FZSI6W5I.js +0 -2
  155. package/dist/text-FZSI6W5I.js.map +0 -1
  156. package/dist/text-QXGOD2KW.js +0 -2
  157. package/dist/text-QXGOD2KW.js.map +0 -1
  158. package/dist/textarea-INLURFNU.js +0 -2
  159. package/dist/textarea-INLURFNU.js.map +0 -1
  160. package/dist/tools.d.ts +0 -78
  161. package/dist/tools.js +0 -60
  162. package/dist/types-U28Ppixq.d.ts +0 -56
  163. package/dist/types.d-CPIuPrvL.d.ts +0 -458
  164. package/dist/user-nav-LSEOOH4E.js +0 -2
@@ -0,0 +1,2 @@
1
+ import'./index.css';import {q as q$1,o,r}from'./chunk-OUSEULBR.js';import {f}from'./chunk-W2EBZZAY.js';import {e}from'./chunk-NNA4MLFC.js';import {useCallback}from'react';import {toast}from'sonner';import {useApolloClient}from'@apollo/client/react';function E(i){let{currentProjectSchema:t}=f();return useCallback(a=>{t&&q$1(o(i,t),a);},[i,t])}var g=["image/jpeg","image/png","image/webp","image/vnd.microsoft.icon","image/bmp","image/gif","image/tiff","image/svg+xml","image/avif","image/heic","image/heif","image/heic-sequence","image/heif-sequence","image/apng","audio/aac","audio/mpeg","audio/wav","audio/webm","audio/midi","audio/x-midi","audio/ogg","video/x-msvideo","video/mp4","video/mpeg","video/webm","video/quicktime","video/ogg","video/mp2t","video/3gpp","video/3gpp2","application/x-7z-compressed","application/zip","application/vnd.amazon.ebook","application/octet-stream","application/epub+zip","application/pdf","application/msword","application/vnd.openxmlformats-officedocument.wordprocessingml.document","application/vnd.ms-fontobject","application/gzip","application/x-gzip","application/java-archive","application/json","application/ld+json","text/javascript","application/vnd.oasis.opendocument.presentation","application/vnd.oasis.opendocument.spreadsheet","application/vnd.oasis.opendocument.text","application/ogg","application/vnd.ms-powerpoint","application/vnd.openxmlformats-officedocument.presentationml.presentation","application/vnd.rar","application/x-tar","application/vnd.visio","application/xhtml+xml","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet","application/xml"];function F(i,t){if(!i.type)return true;let a=t?t.split(",").map(e=>e.trim()).filter(Boolean):g;return a.length===0?true:a.some(e=>e.endsWith("/*")?i.type.startsWith(e.slice(0,-1)):i.type===e)}async function x(i,t){let a=new URLSearchParams({filename:i.name}),e$1=await fetch(`${e(t).assets}?${a.toString()}`,{method:"POST",headers:{"Content-Type":i.type||"application/octet-stream"},body:i});if(!e$1.ok)throw new Error(`Upload failed for ${i.name}`);let n=await e$1.json(),o={_id:n._id,path:n.path??"",originalFilename:n.originalFilename??i.name,size:n.size??i.size,mimeType:n.mimeType??i.type,lqip:n.lqip??"",width:n.width??0,height:n.height??0};return {pathname:o.path,lqip:o.lqip||void 0,originalFilename:o.originalFilename,size:o.size,mimeType:o.mimeType,width:o.width||void 0,height:o.height||void 0,_id:o._id,asset:o}}async function h(i,t){let{projectId:a,accept:e,maxBytes:n=4*1024*1024,onUploadStart:o}=t,l=[];for(let p of Array.from(i)){if(p.size>n){toast.error(`File size too big (max ${(n/(1024*1024)).toFixed(0)}MB): ${p.name}`);continue}if(!F(p,e)){toast.error(`Unsupported file type: ${p.name}`);continue}l.push(p);}if(l.length===0)return [];o?.();try{let p=await Promise.all(l.map(async f=>x(f,a)));return p.length>0&&toast.success(`Uploaded ${p.length} file${p.length>1?"s":""}`),p}catch(p){return console.error(p),toast.error("Upload failed. Please try again."),[]}}async function b(i){let{accept:t,multiple:a=true}=i,e=document.createElement("input");e.type="file",e.accept=t??g.join(","),e.multiple=a,e.style.display="none",document.body.appendChild(e);try{let n=await new Promise(o=>{e.addEventListener("change",()=>o(e.files),{once:!0}),e.addEventListener("cancel",()=>o(null),{once:!0}),e.click();});return !n||n.length===0?[]:h(n,i)}finally{document.body.removeChild(e);}}function q(){let i=useApolloClient();return useCallback(async t=>{let a=t.files?await h(t.files,t):await b(t);return a.length>0&&await r(i,"GetAssets").catch(e=>{console.error("Error refreshing asset lists after upload:",e);}),a},[i])}export{E as a,x as b,q as c};//# sourceMappingURL=chunk-GZIMMYLK.js.map
2
+ //# sourceMappingURL=chunk-GZIMMYLK.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/graphql-client/use-patch-entity-list.ts","../src/core/upload.ts"],"names":["usePatchEntityList","entityNameOrPlural","schema","useConfig","useCallback","patches","scheduleEntityListPatch","getEntityListQueryName","ACCEPTED_MIME_TYPES","isAcceptedMimeType","file","accept","allowed","pattern","uploadAssetFile","projectId","params","response","apiPaths","data","asset","uploadSelectedFiles","files","options","maxBytes","onUploadStart","validFiles","toast","uploads","error","openFileDialogAndUpload","multiple","input","resolve","useUploadAssets","apolloClient","useApolloClient","scheduleEntityListRefetch"],"mappings":"yPAYO,SAASA,EAAmBC,CAAAA,CAAqE,CACtG,GAAM,CAAE,oBAAA,CAAsBC,CAAO,CAAA,CAAIC,CAAAA,GAEzC,OAAOC,WAAAA,CACJC,CAAAA,EAAkC,CAC5BH,CAAAA,EAILI,GAAAA,CAAwBC,CAAAA,CAAuBN,CAAAA,CAAoBC,CAAM,CAAA,CAAGG,CAAO,EACrF,CAAA,CACA,CAACJ,CAAAA,CAAoBC,CAAM,CAC7B,CACF,CClBO,IAAMM,CAAAA,CAAsB,CACjC,YAAA,CACA,YACA,YAAA,CACA,0BAAA,CACA,WAAA,CACA,WAAA,CACA,YAAA,CACA,eAAA,CACA,YAAA,CACA,YAAA,CACA,aACA,qBAAA,CAC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,WAAAA,CACL,MAAOmB,CAAAA,EAA4C,CACjD,IAAMK,EAAUL,CAAAA,CAAQ,KAAA,CACpB,MAAMF,CAAAA,CAAoBE,CAAAA,CAAQ,KAAA,CAAOA,CAAO,CAAA,CAChD,MAAMO,CAAAA,CAAwBP,CAAO,CAAA,CAEzC,OAAIK,CAAAA,CAAQ,MAAA,CAAS,CAAA,EAEnB,MAAMS,EAA0BF,CAAAA,CAAc,WAAW,CAAA,CAAE,KAAA,CAAON,CAAAA,EAAmB,CACnF,OAAA,CAAQ,KAAA,CAAM,6CAA8CA,CAAK,EACnE,CAAC,CAAA,CAGID,CACT,CAAA,CACA,CAACO,CAAY,CACf,CACF","file":"chunk-GZIMMYLK.js","sourcesContent":["import { useCallback } from 'react';\nimport { useConfig } from '../core/config/config-context';\nimport {\n getEntityListQueryName,\n scheduleEntityListPatch,\n type EntityListRowPatch,\n} from './refetch-entity-lists';\n\n/**\n * Patch active list rows for an entity without a soft-refetch.\n * Prefer this after mutations that only change row fields (e.g. tag connect/disconnect).\n */\nexport function usePatchEntityList(entityNameOrPlural: string): (patches: EntityListRowPatch[]) => void {\n const { currentProjectSchema: schema } = useConfig();\n\n return useCallback(\n (patches: EntityListRowPatch[]) => {\n if (!schema) {\n return;\n }\n\n scheduleEntityListPatch(getEntityListQueryName(entityNameOrPlural, schema), patches);\n },\n [entityNameOrPlural, schema]\n );\n}\n","import { useCallback } from 'react';\nimport { toast } from 'sonner';\nimport { useApolloClient } from '@apollo/client/react';\nimport { apiPaths } from './api-paths';\nimport { scheduleEntityListRefetch } from '../graphql-client/refetch-entity-lists';\nimport type { OrderedAssetValue } from '../graphql-client/types';\n\nexport const ACCEPTED_MIME_TYPES = [\n 'image/jpeg',\n 'image/png',\n 'image/webp',\n 'image/vnd.microsoft.icon',\n 'image/bmp',\n 'image/gif',\n 'image/tiff',\n 'image/svg+xml',\n 'image/avif',\n 'image/heic',\n 'image/heif',\n 'image/heic-sequence',\n 'image/heif-sequence',\n 'image/apng',\n 'audio/aac',\n 'audio/mpeg',\n 'audio/wav',\n 'audio/webm',\n 'audio/midi',\n 'audio/x-midi',\n 'audio/ogg',\n 'video/x-msvideo',\n 'video/mp4',\n 'video/mpeg',\n 'video/webm',\n 'video/quicktime',\n 'video/ogg',\n 'video/mp2t',\n 'video/3gpp',\n 'video/3gpp2',\n 'application/x-7z-compressed',\n 'application/zip',\n 'application/vnd.amazon.ebook',\n 'application/octet-stream',\n 'application/epub+zip',\n 'application/pdf',\n 'application/msword',\n 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',\n 'application/vnd.ms-fontobject',\n 'application/gzip',\n 'application/x-gzip',\n 'application/java-archive',\n 'application/json',\n 'application/ld+json',\n 'text/javascript',\n 'application/vnd.oasis.opendocument.presentation',\n 'application/vnd.oasis.opendocument.spreadsheet',\n 'application/vnd.oasis.opendocument.text',\n 'application/ogg',\n 'application/vnd.ms-powerpoint',\n 'application/vnd.openxmlformats-officedocument.presentationml.presentation',\n 'application/vnd.rar',\n 'application/x-tar',\n 'application/vnd.visio',\n 'application/xhtml+xml',\n 'application/vnd.ms-excel',\n 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n 'application/xml',\n];\n\nexport type UploadedFileResult = {\n pathname: string;\n lqip?: string;\n size: number;\n mimeType: string;\n originalFilename: string;\n width?: number;\n height?: number;\n};\n\nexport type UploadedAssetResult = UploadedFileResult & {\n asset: OrderedAssetValue;\n _id: string;\n};\n\ntype AssetUploadResponse = {\n _id: string;\n path: string | null;\n mimeType: string | null;\n originalFilename: string | null;\n size: number | null;\n width: number | null;\n height: number | null;\n lqip: string | null;\n sha256: string | null;\n deduped: boolean;\n};\n\nexport type OpenFileDialogAndUploadOptions = {\n projectId: string | undefined;\n accept?: string;\n files?: File[] | FileList;\n multiple?: boolean;\n maxBytes?: number;\n onUploadStart?: () => void;\n};\n\nfunction isAcceptedMimeType(file: File, accept?: string): boolean {\n if (!file.type) {\n return true;\n }\n\n const allowed = accept\n ? accept\n .split(',')\n .map((pattern) => pattern.trim())\n .filter(Boolean)\n : ACCEPTED_MIME_TYPES;\n\n if (allowed.length === 0) {\n return true;\n }\n\n return allowed.some((pattern) => {\n if (pattern.endsWith('/*')) {\n return file.type.startsWith(pattern.slice(0, -1));\n }\n\n return file.type === pattern;\n });\n}\n\n/**\n * Uploads a single file to the one-shot /assets endpoint, which stores the\n * blob and creates the _asset node in a single request.\n */\nexport async function uploadAssetFile(file: File, projectId: string | undefined): Promise<UploadedAssetResult> {\n const params = new URLSearchParams({ filename: file.name });\n const response = await fetch(`${apiPaths(projectId).assets}?${params.toString()}`, {\n method: 'POST',\n headers: { 'Content-Type': file.type || 'application/octet-stream' },\n body: file,\n });\n\n if (!response.ok) {\n throw new Error(`Upload failed for ${file.name}`);\n }\n\n const data = (await response.json()) as AssetUploadResponse;\n const asset: OrderedAssetValue = {\n _id: data._id,\n path: data.path ?? '',\n originalFilename: data.originalFilename ?? file.name,\n size: data.size ?? file.size,\n mimeType: data.mimeType ?? file.type,\n lqip: data.lqip ?? '',\n width: data.width ?? 0,\n height: data.height ?? 0,\n };\n\n return {\n pathname: asset.path,\n lqip: asset.lqip || undefined,\n originalFilename: asset.originalFilename,\n size: asset.size,\n mimeType: asset.mimeType,\n width: asset.width || undefined,\n height: asset.height || undefined,\n _id: asset._id,\n asset,\n };\n}\n\nasync function uploadSelectedFiles(\n files: File[] | FileList,\n options: OpenFileDialogAndUploadOptions\n): Promise<UploadedAssetResult[]> {\n const { projectId, accept, maxBytes = 4 * 1024 * 1024, onUploadStart } = options;\n const validFiles: File[] = [];\n\n for (const file of Array.from(files)) {\n if (file.size > maxBytes) {\n toast.error(`File size too big (max ${(maxBytes / (1024 * 1024)).toFixed(0)}MB): ${file.name}`);\n\n continue;\n }\n\n if (!isAcceptedMimeType(file, accept)) {\n toast.error(`Unsupported file type: ${file.name}`);\n\n continue;\n }\n\n validFiles.push(file);\n }\n\n if (validFiles.length === 0) {\n return [];\n }\n\n onUploadStart?.();\n\n try {\n const uploads = await Promise.all(validFiles.map(async (file) => uploadAssetFile(file, projectId)));\n\n if (uploads.length > 0) {\n toast.success(`Uploaded ${uploads.length} file${uploads.length > 1 ? 's' : ''}`);\n }\n\n return uploads;\n } catch (error) {\n console.error(error);\n toast.error('Upload failed. Please try again.');\n\n return [];\n }\n}\n\n/**\n * Opens a native file picker and uploads selected files to the Flexkit assets\n * endpoint, which also creates an asset node in the database.\n * Returns a list of uploaded file results. Skips files that exceed maxBytes.\n */\nasync function openFileDialogAndUpload(options: OpenFileDialogAndUploadOptions): Promise<UploadedAssetResult[]> {\n const { accept, multiple = true } = options;\n const input = document.createElement('input');\n input.type = 'file';\n input.accept = accept ?? ACCEPTED_MIME_TYPES.join(',');\n input.multiple = multiple;\n input.style.display = 'none';\n document.body.appendChild(input);\n\n try {\n const files = await new Promise<FileList | null>((resolve) => {\n input.addEventListener('change', () => resolve(input.files), { once: true });\n input.addEventListener('cancel', () => resolve(null), { once: true });\n input.click();\n });\n\n if (!files || files.length === 0) {\n return [];\n }\n\n return uploadSelectedFiles(files, options);\n } finally {\n document.body.removeChild(input);\n }\n}\n\nexport function useUploadAssets(): (options: OpenFileDialogAndUploadOptions) => Promise<UploadedAssetResult[]> {\n const apolloClient = useApolloClient();\n\n return useCallback(\n async (options: OpenFileDialogAndUploadOptions) => {\n const uploads = options.files\n ? await uploadSelectedFiles(options.files, options)\n : await openFileDialogAndUpload(options);\n\n if (uploads.length > 0) {\n // Upload is outside Apollo; soft-refresh mounted asset lists via useEntityQuery.\n await scheduleEntityListRefetch(apolloClient, 'GetAssets').catch((error: unknown) => {\n console.error('Error refreshing asset lists after upload:', error);\n });\n }\n\n return uploads;\n },\n [apolloClient]\n );\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import'./index.css';import {put}from'@vercel/blob/client';function I(o,n){let a=n.trim();return a?o.trim()?/\s$/.test(o)||/^[.,!?;:]/.test(a)?`${o}${a}`:`${o} ${a}`:o.length===0?a:`${o}${a}`:o}async function h(o){if(typeof window>"u")throw new Error("Dictation is only available in the browser.");let n=window.AudioContext??window.webkitAudioContext;if(!n)throw new Error("This browser cannot decode recorded audio.");let a=await o.arrayBuffer(),u=new n;try{let e=await u.decodeAudioData(a.slice(0)),r=C(e),t=$(r,e.sampleRate,24e3),i=y(t),l=t.length/24e3;if(l<.25)throw new Error("No speech was captured. Try again.");if(l>60)throw new Error(`Dictation is limited to ${String(60)} seconds.`);return {durationSeconds:l,pcm:new Blob([i],{type:"audio/pcm"})}}finally{await u.close();}}function C(o){let{length:n,numberOfChannels:a}=o;if(a===1)return o.getChannelData(0).slice();let u=new Float32Array(n);for(let e=0;e<n;e+=1){let r=0;for(let t=0;t<a;t+=1)r+=o.getChannelData(t)[e]??0;u[e]=r/a;}return u}function $(o,n,a){if(n===a)return o;let u=n/a,e=Math.max(1,Math.round(o.length/u)),r=new Float32Array(e);for(let t=0;t<e;t+=1){let i=t*u,l=Math.floor(i),s=Math.min(l+1,o.length-1),c=i-l,d=o[l]??0,g=o[s]??0;r[t]=d+(g-d)*c;}return r}function y(o){let n=new ArrayBuffer(o.length*2),a=new DataView(n);for(let u=0;u<o.length;u+=1){let e=Math.max(-1,Math.min(1,o[u]??0));a.setInt16(u*2,e<0?e*32768:e*32767,true);}return n}var m=class extends Error{code;status;constructor(n,a,u=null){super(a),this.name="AgentUploadError",this.code=u,this.status=n;}};function f(){if(typeof window>"u")return "flexkit.io";let{hostname:o}=window.location;return o==="localhost"||o==="127.0.0.1"||o==="flexkit.test"||o.endsWith(".flexkit.test")?"flexkit.test":"flexkit.io"}function w(){return `https://${f()}`}function R(o,n){return `https://${o}.api.${f()}/automations/webhook/${encodeURIComponent(n)}`}function _(o){let n=`/api/flexkit/${o}`,a=`${n}/automations`,u=`${n}/skills`,e=`${n}/agent/chats`;async function r(t,i){let l=await fetch(t,{credentials:"include",headers:{"Content-Type":"application/json",...i?.headers??{}},...i}),s=await l.json();if(!l.ok){let c=s&&typeof s=="object"&&"error"in s?String(s.error):"Request failed";throw new Error(c)}return s}return {connectPlugins:t=>r(`${n}/plugins/connect`,{method:"POST",body:JSON.stringify(t)}),pluginOAuthStatus:t=>r(`${n}/plugins/oauth-transactions/${encodeURIComponent(t)}`),updatePluginConnection:(t,i)=>r(`${n}/plugin-connections/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(i)}),disconnectPlugin:t=>r(`${n}/plugin-connections/${encodeURIComponent(t)}`,{method:"DELETE"}),installPlugin:t=>r(`${n}/plugins/${encodeURIComponent(t)}/installation`,{method:"PUT",body:JSON.stringify({})}),setPluginPolicy:(t,i)=>r(`${n}/plugins/${encodeURIComponent(t)}/policy`,{method:"PATCH",body:JSON.stringify(i)}),refreshPluginTools:t=>r(`${n}/plugin-connections/${encodeURIComponent(t)}/tools/refresh`,{method:"POST"}),cancelRun:async t=>r(`${a}/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"}),createAgentChat:async t=>r(e,{body:JSON.stringify({modelId:t?.modelId??null}),method:"POST"}),deleteAgentChat:async t=>r(`${e}/${encodeURIComponent(t)}`,{method:"DELETE"}),getAgentChatStreamUrl:(t,i)=>`${e}/${encodeURIComponent(t)}/stream?workflowRunId=${encodeURIComponent(i)}`,renameAgentChat:async(t,i)=>r(`${e}/${encodeURIComponent(t)}`,{body:JSON.stringify({title:i}),method:"PATCH"}),sendAgentChatMessage:async(t,i)=>r(`${e}/${encodeURIComponent(t)}/messages`,{body:JSON.stringify(i),method:"POST"}),stopAgentChat:async t=>r(`${e}/${encodeURIComponent(t)}/stop`,{method:"POST"}),transcribeAgentAudio:async(t,i)=>{let{durationSeconds:l,pcm:s}=await h(t),c=new FormData;c.append("file",s,"audio.pcm"),c.append("durationSeconds",String(l));let d=await fetch(`${n}/agent/transcribe`,{body:c,credentials:"include",method:"POST",signal:i}),g=await d.json();if(!d.ok){let A=g&&typeof g=="object"&&g.error?String(g.error):"Request failed";throw new Error(A)}if(!g.text?.trim())throw new Error("No speech was recognized. Try again.");return {text:g.text}},uploadAgentChatAttachment:async(t,i)=>{let l=await fetch(`${n}/agent/uploads`,{body:JSON.stringify({filename:t.name,mediaType:t.type||null,sizeBytes:t.size}),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST",signal:i}),s=await l.json();if(!l.ok||!s.pathname||!s.token||!s.mediaType)throw new m(l.status,s.error?String(s.error):"The file could not be uploaded.",s.code??null);let c=await put(s.pathname,t,{abortSignal:i,access:"public",contentType:s.mediaType,token:s.token});return {filename:t.name,mediaType:s.mediaType,sizeBytes:t.size,url:c.url}},decideApproval:async(t,i)=>{let l=await fetch(`${a}/approvals/${encodeURIComponent(t)}/decide`,{body:JSON.stringify(i),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST"}),s=await l.json();if(!l.ok&&typeof s.success!="boolean")throw new Error(s.error?String(s.error):"Request failed");return s},createAutomation:async t=>r(a,{body:JSON.stringify(t),method:"POST"}),createSkill:async t=>r(u,{body:JSON.stringify(t),method:"POST"}),deleteAutomation:async t=>r(`${a}/${encodeURIComponent(t)}`,{method:"DELETE"}),deleteSkill:async t=>r(`${u}/${encodeURIComponent(t)}`,{method:"DELETE"}),getArtifactUrl:(t,i)=>{let l=i?.download?"?download=1":"";return `${a}/artifacts/${encodeURIComponent(t)}/content${l}`},getRunArtifacts:async t=>r(`${a}/runs/${encodeURIComponent(t)}/artifacts`).then(i=>i.artifacts),getStreamUrl:t=>`${a}/runs/${encodeURIComponent(t)}/stream`,getTranscriptUrl:t=>`${a}/runs/${encodeURIComponent(t)}/transcript`,listChannels:async(t,i)=>{let l=i?`${n}/plugin-connections/${encodeURIComponent(i)}/channels`:`${n}/plugins/${t}/channels`,s=await fetch(l,{credentials:"include",headers:{"Content-Type":"application/json"}}),c=await s.json();if(s.ok)return {channels:c.channels??[],errorMessage:c.errorMessage,success:c.success??true};if(c.success===false)return {channels:c.channels??[],errorMessage:c.errorMessage??`Failed to load ${t==="slack"?"Slack":"Teams"} channels.`,success:false};let d=c.error?String(c.error):"Request failed";throw new Error(d)},runAutomation:async t=>r(`${a}/${encodeURIComponent(t)}/runs`,{method:"POST"}),updateAutomation:async(t,i)=>r(`${a}/${encodeURIComponent(t)}`,{body:JSON.stringify(i),method:"PATCH"}),updateSkill:async(t,i)=>r(`${u}/${encodeURIComponent(t)}`,{body:JSON.stringify(i),method:"PATCH"})}}var p=class extends Error{status;constructor(n,a="Request failed"){super(a),this.name="FetcherError",this.status=n;}},k=async o=>{let n=await fetch(o,{credentials:"include"});if(!n.ok)throw new p(n.status);return await n.json()};function U(o){let n=`/api/flexkit/${o}/automations`,a=`/api/flexkit/${o}/skills`,u=`/api/flexkit/${o}/agent/chats`;return {agentChat:e=>`${u}/${encodeURIComponent(e)}`,agentChatSearch:e=>`${u}/search?q=${encodeURIComponent(e)}`,agentChats:(e=0)=>`${u}?offset=${e.toString()}`,agentProfile:()=>`/api/flexkit/${o}/agent/profile`,approval:e=>`${n}/approvals/${encodeURIComponent(e)}`,approvals:(e={})=>{let{limit:r=25,offset:t=0,runId:i,status:l}=e,s=new URLSearchParams({limit:r.toString(),offset:t.toString()});return l&&s.set("status",l),i&&s.set("runId",i),`${n}/approvals?${s.toString()}`},approvalsCount:`${n}/approvals?limit=1`,automation:e=>`${n}/${encodeURIComponent(e)}`,automationRuns:(e,r=0,t=25)=>`${n}/${encodeURIComponent(e)}/runs?offset=${r.toString()}&limit=${t.toString()}`,automations:(e={})=>{let{enabled:r,limit:t=25,offset:i=0,search:l,visibility:s}=e,c=new URLSearchParams({limit:t.toString(),offset:i.toString()});r&&r.length>0&&c.set("enabled",r.map(g=>g?"true":"false").join(",")),s&&s.length>0&&c.set("visibility",s.join(","));let d=l?.trim();return d&&c.set("q",d),`${n}?${c.toString()}`},creditBalance:`${n}/credits`,entities:`${n}/entities`,run:e=>`${n}/runs/${encodeURIComponent(e)}`,runHistory:(e,r=0,t=25)=>`${n}/runs?scope=${e}&offset=${r.toString()}&limit=${t.toString()}`,skill:e=>`${a}/${encodeURIComponent(e)}`,skills:(e={})=>{let{limit:r=25,offset:t=0,search:i,visibility:l}=e,s=new URLSearchParams({limit:r.toString(),offset:t.toString()});l&&l.length>0&&s.set("visibility",l.join(","));let c=i?.trim();return c&&s.set("q",c),`${a}?${s.toString()}`},spaces:`/api/flexkit/${o}/spaces`,tools:e=>e?`${n}/${encodeURIComponent(e)}/tools`:`${n}/tools`}}
2
+ export{I as a,w as b,R as c,_ as d,p as e,k as f,U as g};//# sourceMappingURL=chunk-HROHAMPM.js.map
3
+ //# sourceMappingURL=chunk-HROHAMPM.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/apps/ai/agent/dictation.ts","../src/apps/ai/api.ts"],"names":["appendDictatedText","existing","transcript","dictated","convertRecordedAudioToPcm","blob","AudioContextCtor","arrayBuffer","audioContext","audioBuffer","mono","mixToMono","resampled","resample","pcm","floatToPcm16","durationSeconds","buffer","length","channelCount","index","sum","channel","samples","sourceRate","targetRate","ratio","outputLength","output","sourceIndex","left","right","fraction","leftSample","rightSample","view","sample","AgentUploadError","status","message","code","getApiRootDomain","hostname","getPlatformOrigin","getWebhookTriggerUrl","projectId","token","createApiClient","projectBasePath","automationsBasePath","skillsBasePath","agentChatsBasePath","request","url","init","response","data","error","input","id","runId","chatId","workflowRunId","title","audio","signal","formData","file","tokenResponse","tokenData","put","approvalId","automationId","skillId","artifactId","options","suffix","provider","connectionId","FetcherError","fetcher","paths","basePath","query","offset","limit","params","enabled","search","visibility","value","trimmedSearch","scope"],"mappings":"0DAIO,SAASA,CAAAA,CAAmBC,EAAkBC,CAAAA,CAA4B,CAC/E,IAAMC,CAAAA,CAAWD,CAAAA,CAAW,IAAA,EAAK,CAEjC,OAAKC,CAAAA,CAIAF,EAAS,IAAA,EAAK,CAIf,KAAA,CAAM,IAAA,CAAKA,CAAQ,CAAA,EAAK,YAAY,IAAA,CAAKE,CAAQ,CAAA,CAC5C,CAAA,EAAGF,CAAQ,CAAA,EAAGE,CAAQ,CAAA,CAAA,CAGxB,CAAA,EAAGF,CAAQ,CAAA,CAAA,EAAIE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AAIG,CAAAA,EACFL,CAAAA,CAAO,GAAA,CAAI,GAAA,CAAKK,CAAa,EAGxB,CAAA,EAAGzC,CAAc,CAAA,CAAA,EAAIoC,CAAAA,CAAO,QAAA,EAAU,EAC/C,CAAA,CACA,MAAA,CAAQ,CAAA,aAAA,EAAgBzC,CAAS,CAAA,OAAA,CAAA,CACjC,KAAA,CAAQ2B,GACNA,CAAAA,CAAe,CAAA,EAAGU,CAAQ,CAAA,CAAA,EAAI,kBAAA,CAAmBV,CAAY,CAAC,CAAA,MAAA,CAAA,CAAW,CAAA,EAAGU,CAAQ,CAAA,MAAA,CACxF,CACF","file":"chunk-HROHAMPM.js","sourcesContent":["export const DICTATION_SAMPLE_RATE = 24_000;\nexport const DICTATION_MAX_DURATION_SECONDS = 60;\nexport const DICTATION_MIN_DURATION_SECONDS = 0.25;\n\nexport function appendDictatedText(existing: string, transcript: string): string {\n const dictated = transcript.trim();\n\n if (!dictated) {\n return existing;\n }\n\n if (!existing.trim()) {\n return existing.length === 0 ? dictated : `${existing}${dictated}`;\n }\n\n if (/\\s$/.test(existing) || /^[.,!?;:]/.test(dictated)) {\n return `${existing}${dictated}`;\n }\n\n return `${existing} ${dictated}`;\n}\n\nexport async function convertRecordedAudioToPcm(blob: Blob): Promise<{ durationSeconds: number; pcm: Blob }> {\n if (typeof window === 'undefined') {\n throw new Error('Dictation is only available in the browser.');\n }\n\n const AudioContextCtor = window.AudioContext ?? window.webkitAudioContext;\n\n if (!AudioContextCtor) {\n throw new Error('This browser cannot decode recorded audio.');\n }\n\n const arrayBuffer = await blob.arrayBuffer();\n const audioContext = new AudioContextCtor();\n\n try {\n const audioBuffer = await audioContext.decodeAudioData(arrayBuffer.slice(0));\n const mono = mixToMono(audioBuffer);\n const resampled = resample(mono, audioBuffer.sampleRate, DICTATION_SAMPLE_RATE);\n const pcm = floatToPcm16(resampled);\n const durationSeconds = resampled.length / DICTATION_SAMPLE_RATE;\n\n if (durationSeconds < DICTATION_MIN_DURATION_SECONDS) {\n throw new Error('No speech was captured. Try again.');\n }\n\n if (durationSeconds > DICTATION_MAX_DURATION_SECONDS) {\n throw new Error(`Dictation is limited to ${String(DICTATION_MAX_DURATION_SECONDS)} seconds.`);\n }\n\n return {\n durationSeconds,\n pcm: new Blob([pcm], { type: 'audio/pcm' }),\n };\n } finally {\n await audioContext.close();\n }\n}\n\nfunction mixToMono(buffer: AudioBuffer): Float32Array {\n const { length, numberOfChannels: channelCount } = buffer;\n\n if (channelCount === 1) {\n return buffer.getChannelData(0).slice();\n }\n\n const mono = new Float32Array(length);\n\n for (let index = 0; index < length; index += 1) {\n let sum = 0;\n\n for (let channel = 0; channel < channelCount; channel += 1) {\n sum += buffer.getChannelData(channel)[index] ?? 0;\n }\n\n mono[index] = sum / channelCount;\n }\n\n return mono;\n}\n\nfunction resample(samples: Float32Array, sourceRate: number, targetRate: number): Float32Array {\n if (sourceRate === targetRate) {\n return samples;\n }\n\n const ratio = sourceRate / targetRate;\n const outputLength = Math.max(1, Math.round(samples.length / ratio));\n const output = new Float32Array(outputLength);\n\n for (let index = 0; index < outputLength; index += 1) {\n const sourceIndex = index * ratio;\n const left = Math.floor(sourceIndex);\n const right = Math.min(left + 1, samples.length - 1);\n const fraction = sourceIndex - left;\n const leftSample = samples[left] ?? 0;\n const rightSample = samples[right] ?? 0;\n output[index] = leftSample + (rightSample - leftSample) * fraction;\n }\n\n return output;\n}\n\nfunction floatToPcm16(samples: Float32Array): ArrayBuffer {\n const buffer = new ArrayBuffer(samples.length * 2);\n const view = new DataView(buffer);\n\n for (let index = 0; index < samples.length; index += 1) {\n const sample = Math.max(-1, Math.min(1, samples[index] ?? 0));\n view.setInt16(index * 2, sample < 0 ? sample * 0x8000 : sample * 0x7fff, true);\n }\n\n return buffer;\n}\n\ndeclare global {\n interface Window {\n webkitAudioContext?: typeof AudioContext;\n }\n}\n","import type { PluginConnection, PluginScope, PluginTools } from './plugin-types';\nimport { put } from '@vercel/blob/client';\nimport { convertRecordedAudioToPcm } from './agent/dictation';\nimport type {\n AgentChat,\n AgentChatAttachment,\n AgentChatMessage,\n AgentChatTurn,\n Automation,\n AutomationApproval,\n AutomationApprovalStatus,\n AutomationArtifact,\n AutomationInput,\n AutomationToolChannel,\n AutomationToolProvider,\n AutomationVisibility,\n MutationResult,\n Skill,\n SkillInput,\n} from './types';\n\nexport interface DecideApprovalInput {\n /** Approve and always allow this plugin tool for the automation. */\n remember?: boolean;\n approved: boolean;\n force?: boolean;\n reason?: string;\n}\n\nexport interface SendAgentChatMessageInput {\n attachments?: AgentChatAttachment[];\n content: string;\n modelId?: string | null;\n}\n\n/** Thrown when the API refuses an upload; `code` lets the UI tailor the message. */\nexport class AgentUploadError extends Error {\n code: string | null;\n status: number;\n\n constructor(status: number, message: string, code: string | null = null) {\n super(message);\n this.name = 'AgentUploadError';\n this.code = code;\n this.status = status;\n }\n}\n\nexport interface ApiClient {\n /** Starts OAuth for a new account, or for `connectionId` to reconnect that specific account. */\n connectPlugins: (_input: {\n pluginId: string;\n scope: PluginScope;\n studioOrigin: string;\n connectionId?: string;\n }) => Promise<{ transactionId: string; authorizeUrl: string; completionOrigin: string; launchTicket: string }>;\n /** Renames (label null resets to the provider name) or makes a connection primary. */\n updatePluginConnection: (\n _id: string,\n _input: { label?: string | null; primary?: true }\n ) => Promise<{ connection: PluginConnection }>;\n pluginOAuthStatus: (_id: string) => Promise<{ id: string; status: 'pending' | 'exchanging' | 'complete' | 'failed'; expires_at: string }>;\n disconnectPlugin: (_id: string) => Promise<{ success: boolean }>;\n installPlugin: (_id: string) => Promise<unknown>;\n setPluginPolicy: (_id: string, _input: { enabled: boolean; allowPersonal: boolean }) => Promise<{ success: boolean }>;\n refreshPluginTools: (_id: string) => Promise<PluginTools>;\n\n cancelRun: (_runId: string) => Promise<MutationResult>;\n createAgentChat: (_input?: { modelId?: string | null }) => Promise<{ chat: AgentChat }>;\n deleteAgentChat: (_chatId: string) => Promise<{ success: boolean }>;\n getAgentChatStreamUrl: (_chatId: string, _workflowRunId: string) => string;\n renameAgentChat: (_chatId: string, _title: string) => Promise<{ chat: AgentChat }>;\n sendAgentChatMessage: (_chatId: string, _input: SendAgentChatMessageInput) => Promise<AgentChatTurn>;\n stopAgentChat: (_chatId: string) => Promise<{ message: AgentChatMessage }>;\n transcribeAgentAudio: (_audio: Blob, _signal?: AbortSignal) => Promise<{ text: string }>;\n /** Uploads a chat attachment straight to the platform file store. */\n uploadAgentChatAttachment: (_file: File, _signal?: AbortSignal) => Promise<AgentChatAttachment>;\n decideApproval: (\n _approvalId: string,\n _input: DecideApprovalInput\n ) => Promise<MutationResult & { approval?: AutomationApproval }>;\n createAutomation: (_input: AutomationInput) => Promise<MutationResult & { automation?: Automation }>;\n createSkill: (_input: SkillInput) => Promise<MutationResult & { skill?: Skill }>;\n deleteAutomation: (_automationId: string) => Promise<MutationResult>;\n deleteSkill: (_skillId: string) => Promise<MutationResult>;\n getArtifactUrl: (_artifactId: string, _options?: { download?: boolean }) => string;\n getRunArtifacts: (_workflowRunId: string) => Promise<AutomationArtifact[]>;\n getStreamUrl: (_workflowRunId: string) => string;\n /** JSON transcript of a finished run (owners and developers). */\n getTranscriptUrl: (_runId: string) => string;\n /** Lists delivery channels of `connectionId`, or of the provider's primary project account when omitted. */\n listChannels: (_provider: AutomationToolProvider, _connectionId?: string | null) => Promise<{\n channels: AutomationToolChannel[];\n errorMessage?: string;\n success: boolean;\n }>;\n runAutomation: (_automationId: string) => Promise<MutationResult & { runId?: string }>;\n updateAutomation: (\n _automationId: string,\n _input: AutomationInput\n ) => Promise<MutationResult & { automation?: Automation }>;\n updateSkill: (_skillId: string, _input: SkillInput) => Promise<MutationResult & { skill?: Skill }>;\n}\n\n\nfunction getApiRootDomain(): string {\n if (typeof window === 'undefined') {\n return 'flexkit.io';\n }\n\n const { hostname } = window.location;\n const isDevHost =\n hostname === 'localhost' ||\n hostname === '127.0.0.1' ||\n hostname === 'flexkit.test' ||\n hostname.endsWith('.flexkit.test');\n\n return isDevHost ? 'flexkit.test' : 'flexkit.io';\n}\n\n/** Origin that hosts plugin OAuth start and completion. */\nexport function getPlatformOrigin(): string {\n return `https://${getApiRootDomain()}`;\n}\n\n/** Public URL an external system calls to fire a webhook trigger. */\nexport function getWebhookTriggerUrl(projectId: string, token: string): string {\n return `https://${projectId}.api.${getApiRootDomain()}/automations/webhook/${encodeURIComponent(token)}`;\n}\n\nexport function createApiClient(projectId: string): ApiClient {\n const projectBasePath = `/api/flexkit/${projectId}`;\n const automationsBasePath = `${projectBasePath}/automations`;\n const skillsBasePath = `${projectBasePath}/skills`;\n const agentChatsBasePath = `${projectBasePath}/agent/chats`;\n\n async function request<T>(url: string, init?: RequestInit): Promise<T> {\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n ...(init?.headers ?? {}),\n },\n ...init,\n });\n const data = (await response.json()) as T;\n\n if (!response.ok) {\n const error = data && typeof data === 'object' && 'error' in data ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n }\n\n return data;\n }\n\n return {\n connectPlugins: (input) => request(`${projectBasePath}/plugins/connect`, { method: 'POST', body: JSON.stringify(input) }),\n pluginOAuthStatus: (id) => request(`${projectBasePath}/plugins/oauth-transactions/${encodeURIComponent(id)}`),\n updatePluginConnection: (id, input) =>\n request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(input) }),\n disconnectPlugin: (id) => request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}`, { method: 'DELETE' }),\n installPlugin: (id) => request(`${projectBasePath}/plugins/${encodeURIComponent(id)}/installation`, { method: 'PUT', body: JSON.stringify({}) }),\n setPluginPolicy: (id, input) => request(`${projectBasePath}/plugins/${encodeURIComponent(id)}/policy`, { method: 'PATCH', body: JSON.stringify(input) }),\n refreshPluginTools: (id) => request(`${projectBasePath}/plugin-connections/${encodeURIComponent(id)}/tools/refresh`, { method: 'POST' }),\n cancelRun: async (runId) =>\n request<MutationResult>(`${automationsBasePath}/runs/${encodeURIComponent(runId)}/cancel`, { method: 'POST' }),\n createAgentChat: async (input) =>\n request<{ chat: AgentChat }>(agentChatsBasePath, {\n body: JSON.stringify({ modelId: input?.modelId ?? null }),\n method: 'POST',\n }),\n deleteAgentChat: async (chatId) =>\n request<{ success: boolean }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}`, { method: 'DELETE' }),\n getAgentChatStreamUrl: (chatId, workflowRunId) =>\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/stream?workflowRunId=${encodeURIComponent(workflowRunId)}`,\n renameAgentChat: async (chatId, title) =>\n request<{ chat: AgentChat }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}`, {\n body: JSON.stringify({ title }),\n method: 'PATCH',\n }),\n sendAgentChatMessage: async (chatId, input) =>\n request<AgentChatTurn>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/messages`, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n stopAgentChat: async (chatId) =>\n request<{ message: AgentChatMessage }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/stop`, {\n method: 'POST',\n }),\n transcribeAgentAudio: async (audio, signal) => {\n const { durationSeconds, pcm } = await convertRecordedAudioToPcm(audio);\n const formData = new FormData();\n formData.append('file', pcm, 'audio.pcm');\n formData.append('durationSeconds', String(durationSeconds));\n\n const response = await fetch(`${projectBasePath}/agent/transcribe`, {\n body: formData,\n credentials: 'include',\n method: 'POST',\n signal,\n });\n const data = (await response.json()) as { error?: string; text?: string };\n\n if (!response.ok) {\n const error = data && typeof data === 'object' && data.error ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n }\n\n if (!data.text?.trim()) {\n throw new Error('No speech was recognized. Try again.');\n }\n\n return { text: data.text };\n },\n uploadAgentChatAttachment: async (file, signal) => {\n // The platform issues a token scoped to one pathname, type and size; the\n // browser then writes the bytes to the store directly, so large files\n // never pass through the API function body limit.\n const tokenResponse = await fetch(`${projectBasePath}/agent/uploads`, {\n body: JSON.stringify({ filename: file.name, mediaType: file.type || null, sizeBytes: file.size }),\n credentials: 'include',\n headers: { 'Content-Type': 'application/json' },\n method: 'POST',\n signal,\n });\n const tokenData = (await tokenResponse.json()) as {\n code?: string;\n error?: string;\n mediaType?: string;\n pathname?: string;\n token?: string;\n };\n\n if (!tokenResponse.ok || !tokenData.pathname || !tokenData.token || !tokenData.mediaType) {\n throw new AgentUploadError(\n tokenResponse.status,\n tokenData.error ? String(tokenData.error) : 'The file could not be uploaded.',\n tokenData.code ?? null\n );\n }\n\n const blob = await put(tokenData.pathname, file, {\n abortSignal: signal,\n access: 'public',\n contentType: tokenData.mediaType,\n token: tokenData.token,\n });\n\n return {\n filename: file.name,\n mediaType: tokenData.mediaType,\n sizeBytes: file.size,\n url: blob.url,\n };\n },\n decideApproval: async (approvalId, input) => {\n const response = await fetch(`${automationsBasePath}/approvals/${encodeURIComponent(approvalId)}/decide`, {\n body: JSON.stringify(input),\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n method: 'POST',\n });\n const data = (await response.json()) as MutationResult & { approval?: AutomationApproval; error?: string };\n\n // Business errors (stale_preview, already_decided) come back as 400\n // with a structured body the caller must be able to inspect.\n if (!response.ok && typeof data.success !== 'boolean') {\n throw new Error(data.error ? String(data.error) : 'Request failed');\n }\n\n return data;\n },\n createAutomation: async (input) =>\n request<MutationResult & { automation?: Automation }>(automationsBasePath, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n createSkill: async (input) =>\n request<MutationResult & { skill?: Skill }>(skillsBasePath, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n deleteAutomation: async (automationId) =>\n request<MutationResult>(`${automationsBasePath}/${encodeURIComponent(automationId)}`, { method: 'DELETE' }),\n deleteSkill: async (skillId) =>\n request<MutationResult>(`${skillsBasePath}/${encodeURIComponent(skillId)}`, { method: 'DELETE' }),\n getArtifactUrl: (artifactId, options) => {\n const suffix = options?.download ? '?download=1' : '';\n\n return `${automationsBasePath}/artifacts/${encodeURIComponent(artifactId)}/content${suffix}`;\n },\n getRunArtifacts: async (workflowRunId) =>\n request<{ artifacts: AutomationArtifact[] }>(\n `${automationsBasePath}/runs/${encodeURIComponent(workflowRunId)}/artifacts`\n ).then((response) => response.artifacts),\n getStreamUrl: (workflowRunId) => `${automationsBasePath}/runs/${encodeURIComponent(workflowRunId)}/stream`,\n getTranscriptUrl: (runId) => `${automationsBasePath}/runs/${encodeURIComponent(runId)}/transcript`,\n listChannels: async (provider, connectionId) => {\n const url = connectionId\n ? `${projectBasePath}/plugin-connections/${encodeURIComponent(connectionId)}/channels`\n : `${projectBasePath}/plugins/${provider}/channels`;\n const response = await fetch(url, {\n credentials: 'include',\n headers: {\n 'Content-Type': 'application/json',\n },\n });\n const data = (await response.json()) as {\n channels?: AutomationToolChannel[];\n error?: string;\n errorMessage?: string;\n success?: boolean;\n };\n\n if (response.ok) {\n return {\n channels: data.channels ?? [],\n errorMessage: data.errorMessage,\n success: data.success ?? true,\n };\n }\n\n if (data.success === false) {\n return {\n channels: data.channels ?? [],\n errorMessage: data.errorMessage ?? `Failed to load ${provider === 'slack' ? 'Slack' : 'Teams'} channels.`,\n success: false,\n };\n }\n\n const error = data.error ? String(data.error) : 'Request failed';\n\n throw new Error(error);\n },\n runAutomation: async (automationId) =>\n request<MutationResult & { runId?: string }>(`${automationsBasePath}/${encodeURIComponent(automationId)}/runs`, {\n method: 'POST',\n }),\n updateAutomation: async (automationId, input) =>\n request<MutationResult & { automation?: Automation }>(\n `${automationsBasePath}/${encodeURIComponent(automationId)}`,\n {\n body: JSON.stringify(input),\n method: 'PATCH',\n }\n ),\n updateSkill: async (skillId, input) =>\n request<MutationResult & { skill?: Skill }>(`${skillsBasePath}/${encodeURIComponent(skillId)}`, {\n body: JSON.stringify(input),\n method: 'PATCH',\n }),\n };\n}\n\nexport class FetcherError extends Error {\n status: number;\n\n constructor(status: number, message = 'Request failed') {\n super(message);\n this.name = 'FetcherError';\n this.status = status;\n }\n}\n\nexport const fetcher = async <T>(url: string): Promise<T> => {\n const response = await fetch(url, { credentials: 'include' });\n\n if (!response.ok) {\n throw new FetcherError(response.status);\n }\n\n return (await response.json()) as T;\n};\n\nexport function paths(projectId: string): {\n agentChat: (_chatId: string) => string;\n agentChatSearch: (_query: string) => string;\n agentChats: (_offset?: number) => string;\n agentProfile: () => string;\n approval: (_approvalId: string) => string;\n approvals: (_options?: {\n limit?: number;\n offset?: number;\n runId?: string;\n status?: AutomationApprovalStatus;\n }) => string;\n approvalsCount: string;\n automation: (_automationId: string) => string;\n automationRuns: (_automationId: string, _offset?: number, _limit?: number) => string;\n automations: (_options?: {\n enabled?: boolean[];\n limit?: number;\n offset?: number;\n search?: string;\n visibility?: AutomationVisibility[];\n }) => string;\n creditBalance: string;\n entities: string;\n run: (_runId: string) => string;\n runHistory: (_scope: 'mine' | 'team', _offset?: number, _limit?: number) => string;\n skill: (_skillId: string) => string;\n skills: (_options?: { limit?: number; offset?: number; search?: string; visibility?: AutomationVisibility[] }) => string;\n spaces: string;\n tools: (_automationId?: string) => string;\n} {\n const basePath = `/api/flexkit/${projectId}/automations`;\n const skillsBasePath = `/api/flexkit/${projectId}/skills`;\n const agentChatsBasePath = `/api/flexkit/${projectId}/agent/chats`;\n\n return {\n agentChat: (chatId) => `${agentChatsBasePath}/${encodeURIComponent(chatId)}`,\n agentChatSearch: (query) => `${agentChatsBasePath}/search?q=${encodeURIComponent(query)}`,\n agentChats: (offset = 0) => `${agentChatsBasePath}?offset=${offset.toString()}`,\n agentProfile: () => `/api/flexkit/${projectId}/agent/profile`,\n approval: (approvalId) => `${basePath}/approvals/${encodeURIComponent(approvalId)}`,\n approvals: (options = {}) => {\n const { limit = 25, offset = 0, runId, status } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (status) {\n params.set('status', status);\n }\n\n if (runId) {\n params.set('runId', runId);\n }\n\n return `${basePath}/approvals?${params.toString()}`;\n },\n approvalsCount: `${basePath}/approvals?limit=1`,\n automation: (automationId) => `${basePath}/${encodeURIComponent(automationId)}`,\n automationRuns: (automationId, offset = 0, limit = 25) =>\n `${basePath}/${encodeURIComponent(automationId)}/runs?offset=${offset.toString()}&limit=${limit.toString()}`,\n automations: (options = {}) => {\n const { enabled, limit = 25, offset = 0, search, visibility } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (enabled && enabled.length > 0) {\n params.set('enabled', enabled.map((value) => (value ? 'true' : 'false')).join(','));\n }\n\n if (visibility && visibility.length > 0) {\n params.set('visibility', visibility.join(','));\n }\n\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n return `${basePath}?${params.toString()}`;\n },\n creditBalance: `${basePath}/credits`,\n entities: `${basePath}/entities`,\n run: (runId) => `${basePath}/runs/${encodeURIComponent(runId)}`,\n runHistory: (scope, offset = 0, limit = 25) =>\n `${basePath}/runs?scope=${scope}&offset=${offset.toString()}&limit=${limit.toString()}`,\n skill: (skillId) => `${skillsBasePath}/${encodeURIComponent(skillId)}`,\n skills: (options = {}) => {\n const { limit = 25, offset = 0, search, visibility } = options;\n const params = new URLSearchParams({\n limit: limit.toString(),\n offset: offset.toString(),\n });\n\n if (visibility && visibility.length > 0) {\n params.set('visibility', visibility.join(','));\n }\n\n const trimmedSearch = search?.trim();\n\n if (trimmedSearch) {\n params.set('q', trimmedSearch);\n }\n\n return `${skillsBasePath}?${params.toString()}`;\n },\n spaces: `/api/flexkit/${projectId}/spaces`,\n tools: (automationId) =>\n automationId ? `${basePath}/${encodeURIComponent(automationId)}/tools` : `${basePath}/tools`,\n };\n}\n"]}
@@ -0,0 +1,3 @@
1
+ import'./index.css';import {createContext,useContext}from'react';import v from'swr';import {useParams,useHref}from'react-router-dom';import {jsx}from'react/jsx-runtime';var l="flexkit.io",A={"flexkit.io":true,"flexkit.test":true};function P(){let t=globalThis.process?.env?.FLEXKIT_DOMAIN?.trim();return t&&A[t]?t:l}var n=P();var p=n,f=`https://${p}`,a=t=>t?`https://${t}.api.${p}`:f,L=`${f}/images/`,o="-",m={authProviders:`/api/flexkit/${o}/auth/providers`,logout:`/api/flexkit/${o}/auth/logout`,me:`/api/flexkit/${o}/me`,otpConfirm:`/api/flexkit/${o}/auth/otp/confirm`,otpSend:`/api/flexkit/${o}/auth/otp/send`};function u(t=""){return {assets:`/api/flexkit/${t}/assets`,authProviders:`/api/flexkit/${t}/auth/providers`,completion:`/api/flexkit/${t}/completion`,currentUser:`/api/flexkit/${t}/users/me`,loginOtpConfirm:`${a(t)}/auth/otp/confirm`,loginOtpSend:`${a(t)}/auth/otp/send`,logout:e=>{let i=new URLSearchParams({redirect:e});return `/api/flexkit/${t}/auth/logout?${i.toString()}`},schema:`/api/flexkit/${t}/schema`,search:`/api/flexkit/${t}/search`,sessionId:`${a(t)}/api/auth/login/session`}}async function h(t){try{await fetch(m.logout,{credentials:"same-origin",method:"POST"});}catch{}await fetch("/api/flexkit/logout",{credentials:"include",method:"GET"}),window.location.assign(t);}function c(t="projects"){let{projectId:e}=useParams(),i=useHref(`/${e??""}`),r=useHref("/"),{data:x,isLoading:S}=v(e?u(e).currentUser:null,k=>fetch(k,{mode:"cors",credentials:"include"}).then(s=>s.json()).then(s=>({...s,spaces:s.spaces??[]})));return [!!e&&S,{user:x,logout:async()=>{if(t==="hosted"){await h(r);return}await fetch(u(e??"").logout(i),{method:"POST",mode:"cors",credentials:"include"}),await fetch("/api/flexkit/logout",{method:"GET",credentials:"include"}),window.location.reload();}}]}var g=createContext([true,{user:null,logout:()=>Promise.resolve()}]);function B({children:t,mode:e="projects"}){let[i,r]=c(e);return jsx(g.Provider,{value:[i,r],children:t})}function J(){return useContext(g)}
2
+ export{n as a,f as b,L as c,m as d,u as e,h as f,B as g,J as h};//# sourceMappingURL=chunk-NNA4MLFC.js.map
3
+ //# sourceMappingURL=chunk-NNA4MLFC.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/core/domains.ts","../src/core/api-paths.ts","../src/auth/hosted-logout.ts","../src/auth/use-auth-service.ts","../src/auth/auth-context.tsx"],"names":["defaultFlexkitDomain","allowedFlexkitDomains","getConfiguredFlexkitDomain","configuredDomain","flexkitDomain","domain","baseApiUrl","baseProjectApiUrl","projectId","IMAGES_BASE_URL","USER_API_SEGMENT","userApiPaths","apiPaths","redirectPath","params","signOutHosted","rootHref","useAuthService","mode","useParams","projectHref","useHref","user","isLoadingUser","useSWR","url","res","data","AuthContext","createContext","AuthProvider","children","isLoading","auth","jsx","useAuth","useContext"],"mappings":"yKAAA,IAAMA,CAAAA,CAAuB,aAEvBC,CAAAA,CAAoD,CACxD,aAAc,IAAA,CACd,cAAA,CAAgB,IAClB,CAAA,CAUA,SAASC,GAAqC,CAC5C,IAAMC,EAAoB,UAAA,CAAoC,OAAA,EAAS,KAAK,cAAA,EAAgB,IAAA,GAE5F,OAAKA,CAAAA,EAIDF,EAAsBE,CAAgB,CAAA,CACjCA,EAJAH,CAQX,KAEaI,CAAAA,CAAgBF,CAAAA,GC3B7B,IAAMG,EAASD,CAAAA,CACFE,CAAAA,CAAa,WAAWD,CAAM,CAAA,CAAA,CACrCE,EAAqBC,CAAAA,EACzBA,CAAAA,CAAY,WAAWA,CAAS,CAAA,KAAA,EAAQH,CAAM,CAAA,CAAA,CAAKC,CAAAA,CAiBxCG,EAAkB,CAAA,EAAGH,CAAU,WAQ/BI,CAAAA,CAAmB,GAAA,CAEnBC,EAAe,CAC1B,aAAA,CAAe,gBAAgBD,CAAgB,CAAA,eAAA,CAAA,CAC/C,OAAQ,CAAA,aAAA,EAAgBA,CAAgB,eAExC,EAAA,CAAI,CAAA,aAAA,EAAgBA,CAAgB,CAAA,GAAA,CAAA,CACpC,UAAA,CAAY,gBAAgBA,CAAgB,CAAA,iBAAA,CAAA,CAC5C,QAAS,CAAA,aAAA,EAAgBA,CAAgB,gBAC3C,EAEO,SAASE,EAASJ,CAAAA,CAAY,EAAA,CAAc,CACjD,OAAO,CACL,OAAQ,CAAA,aAAA,EAAgBA,CAAS,U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ACnE,CAEO,SAASI,GAAuB,CACrC,OAAOC,UAAAA,CAAWR,CAAW,CAC/B","file":"chunk-NNA4MLFC.js","sourcesContent":["const defaultFlexkitDomain = 'flexkit.io';\n\nconst allowedFlexkitDomains: { [domain: string]: true } = {\n 'flexkit.io': true,\n 'flexkit.test': true,\n};\n\ntype GlobalWithProcessEnv = typeof globalThis & {\n process?: {\n env?: {\n [key: string]: string | undefined;\n };\n };\n};\n\nfunction getConfiguredFlexkitDomain(): string {\n const configuredDomain = (globalThis as GlobalWithProcessEnv).process?.env?.FLEXKIT_DOMAIN?.trim();\n\n if (!configuredDomain) {\n return defaultFlexkitDomain;\n }\n\n if (allowedFlexkitDomains[configuredDomain]) {\n return configuredDomain;\n }\n\n return defaultFlexkitDomain;\n}\n\nexport const flexkitDomain = getConfiguredFlexkitDomain();\nexport const flexkitApiDomain = `api.${flexkitDomain}`;\n","import { flexkitDomain } from './domains';\n\nconst domain = flexkitDomain;\nexport const baseApiUrl = `https://${domain}`;\nconst baseProjectApiUrl = (projectId?: string): string =>\n projectId ? `https://${projectId}.api.${domain}` : baseApiUrl;\n\ninterface ApiPaths {\n assets: string;\n authProviders: string;\n completion: string;\n currentUser: string;\n loginOtpConfirm: string;\n loginOtpSend: string;\n /** `redirectPath` is the absolute in-app path to return to after logout. */\n logout: (redirectPath: string) => string;\n /** Deployed project schema, scopes, spaces, title and menu groups. */\n schema: string;\n search: string;\n sessionId: string;\n}\n\nexport const IMAGES_BASE_URL = `${baseApiUrl}/images/`;\n\n/**\n * Reserved BFF segment for user-level (project-less) Flexkit API calls:\n * `/api/flexkit/-/me` is proxied to `https://<flexkitDomain>/api/me` with the\n * session as a bearer token. Project ids are ten characters, so `-` can never\n * collide with one.\n */\nexport const USER_API_SEGMENT = '-';\n\nexport const userApiPaths = {\n authProviders: `/api/flexkit/${USER_API_SEGMENT}/auth/providers`,\n logout: `/api/flexkit/${USER_API_SEGMENT}/auth/logout`,\n /** Signed-in user plus every project they can open. */\n me: `/api/flexkit/${USER_API_SEGMENT}/me`,\n otpConfirm: `/api/flexkit/${USER_API_SEGMENT}/auth/otp/confirm`,\n otpSend: `/api/flexkit/${USER_API_SEGMENT}/auth/otp/send`,\n} as const;\n\nexport function apiPaths(projectId = ''): ApiPaths {\n return {\n assets: `/api/flexkit/${projectId}/assets`,\n authProviders: `/api/flexkit/${projectId}/auth/providers`,\n completion: `/api/flexkit/${projectId}/completion`,\n currentUser: `/api/flexkit/${projectId}/users/me`,\n loginOtpConfirm: `${baseProjectApiUrl(projectId)}/auth/otp/confirm`,\n loginOtpSend: `${baseProjectApiUrl(projectId)}/auth/otp/send`,\n logout: (redirectPath: string) => {\n const params = new URLSearchParams({ redirect: redirectPath });\n\n return `/api/flexkit/${projectId}/auth/logout?${params.toString()}`;\n },\n schema: `/api/flexkit/${projectId}/schema`,\n search: `/api/flexkit/${projectId}/search`,\n sessionId: `${baseProjectApiUrl(projectId)}/api/auth/login/session`,\n };\n}\n","import { userApiPaths } from '../core/api-paths';\n\n/** Hosted mode sign-out: end the Flexkit session, drop the first-party cookie, go back to the Studio root. */\nexport async function signOutHosted(rootHref: string): Promise<void> {\n try {\n await fetch(userApiPaths.logout, { credentials: 'same-origin', method: 'POST' });\n } catch {\n // The cookie is cleared below either way; the session expires server-side.\n }\n\n await fetch('/api/flexkit/logout', { credentials: 'include', method: 'GET' });\n window.location.assign(rootHref);\n}\n","'use client';\n\nimport useSWR from 'swr';\nimport { useHref, useParams } from 'react-router-dom';\nimport { apiPaths } from '../core/api-paths';\nimport type { StudioMode } from '../core/config/types';\nimport { signOutHosted } from './hosted-logout';\nimport type { AuthService, User } from './types';\n\nexport default function useAuthService(mode: StudioMode = 'projects'): AuthService {\n const { projectId } = useParams();\n // Absolute path of the current project under the router basename.\n const projectHref = useHref(`/${projectId ?? ''}`);\n const rootHref = useHref('/');\n // Role and spaces are per project, so there is nothing to ask until a project is open.\n const { data: user, isLoading: isLoadingUser } = useSWR(projectId ? apiPaths(projectId).currentUser : null, (url: string) =>\n fetch(url, { mode: 'cors', credentials: 'include' })\n .then((res) => res.json() as Promise<User>)\n .then((data) => ({ ...data, spaces: data.spaces ?? [] }))\n );\n const isLoading = Boolean(projectId) && isLoadingUser;\n\n return [\n isLoading,\n {\n user,\n logout: async () => {\n if (mode === 'hosted') {\n await signOutHosted(rootHref);\n\n return;\n }\n\n // wipe remote session\n await fetch(apiPaths(projectId ?? '').logout(projectHref), {\n method: 'POST',\n mode: 'cors',\n credentials: 'include',\n });\n\n // delete first-party auth cookie\n await fetch('/api/flexkit/logout', { method: 'GET', credentials: 'include' });\n\n window.location.reload();\n },\n },\n ];\n}\n","'use client';\n\nimport { createContext, JSX, useContext } from 'react';\nimport useAuthService from './use-auth-service';\nimport type { Auth, AuthService, User } from './types';\nimport type { StudioMode } from '../core/config/types';\n\nconst AuthContext = createContext([\n true,\n {\n user: null as User | null,\n logout: () => Promise.resolve(),\n } as Auth,\n]);\n\nexport function AuthProvider({\n children,\n mode = 'projects',\n}: {\n children: React.ReactNode;\n mode?: StudioMode;\n}): JSX.Element {\n const [isLoading, auth] = useAuthService(mode);\n\n return <AuthContext.Provider value={[isLoading, auth]}>{children}</AuthContext.Provider>;\n}\n\nexport function useAuth(): AuthService {\n return useContext(AuthContext) as AuthService;\n}\n"]}
@@ -0,0 +1,5 @@
1
+ import'./index.css';import {g,d,f as f$1}from'./chunk-HROHAMPM.js';import {f}from'./chunk-W2EBZZAY.js';import {sa as sa$1,ub,o,pa as pa$1,da as da$1,ea,ha as ha$1,ia as ia$1,fa as fa$1,ja as ja$1,la as la$1,ma as ma$1,na,ka as ka$1,oa as oa$1,f as f$2}from'./chunk-6LYEDKFY.js';import {t}from'./chunk-SZEGGBOC.js';import {b,c,h,i,k,l,j,v}from'./chunk-ODORXGGY.js';import {d as d$1}from'./chunk-5DHOBLAE.js';import {createContext,useCallback,useMemo,useState,useRef,useEffect,useContext,useTransition,useId}from'react';import cr,{useSWRConfig}from'swr';import {formatDistance,format}from'date-fns';import {BotIcon,XCircleIcon,LoaderCircle,XIcon,CheckIcon,CloudUploadIcon,FileTextIcon,DownloadIcon,LinkIcon,MessageSquareIcon,SendIcon,CheckCircle2Icon,CircleSlashIcon,ShieldIcon,DatabaseZapIcon,ShieldCheckIcon,TriangleAlertIcon,ArrowRightIcon,MoveRightIcon,TrendingUpIcon,TrendingDownIcon,MinusIcon,InfoIcon,OctagonAlertIcon,AlertTriangleIcon,LightbulbIcon}from'lucide-react';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {useLocation,Link}from'react-router-dom';import {parseJsonEventStream,uiMessageChunkSchema,readUIMessageStream}from'ai';import {buildSpecFromParts,StateProvider,VisibilityProvider,ActionProvider,Renderer}from'@json-render/react';import {PieChart,Tooltip,Pie,Cell,LineChart,CartesianGrid,XAxis,YAxis,Line,BarChart,Bar,ResponsiveContainer}from'recharts';function _e(){let{currentProjectId:e}=f(),{mutate:t}=useSWRConfig();return useCallback(a=>{if(!e)return;let r=g(e).approvalsCount;a?t(r,a,{revalidate:true}):t(r);},[e,t])}var ht={approved:"fk:bg-success/20 fk:text-success",cancelled:"fk:bg-secondary fk:text-secondary-foreground",expired:"fk:bg-secondary fk:text-secondary-foreground",pending:"fk:bg-amber-500/20 fk:text-amber-600",rejected:"fk:bg-destructive/15 fk:text-destructive"};function xt({status:e}){return jsx(b,{className:`fk:border-none fk:h-4.75 fk:text-[0.6875rem] fk:leading-4.5 fk:tracking-wide ${ht[e]}`,variant:"secondary",children:e})}function O(e){return e==null?"\u2014":typeof e=="object"?JSON.stringify(e):String(e)}function Rt({after:e,before:t}){let a=O(t),r=O(e);return a===r?jsx("span",{className:"fk:text-muted-foreground",children:a}):jsxs("span",{className:"fk:inline-flex fk:flex-wrap fk:items-center fk:gap-1.5",children:[jsx("span",{className:"fk:rounded fk:bg-destructive/10 fk:px-1 fk:text-destructive fk:line-through fk:corner-squircle",children:a}),jsx(MoveRightIcon,{className:"fk:size-3 fk:shrink-0 fk:text-muted-foreground"}),jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:r})]})}function St(e){let t=e.entity??"entities",a=e.affectedCount!==null?` \xB7 ${e.affectedCount.toString()} affected`:"";return e.kind==="create"?`Create ${t}${a}`:e.kind==="update"?`Update ${t}${a}`:e.kind==="delete"?`Delete ${t}${a}`:`Mutation on ${t}${a}`}function wt({operation:e}){if(e.rows.length===0)return null;let t=(e.contextColumns??[]).filter(r=>r!=="_id");if(e.kind==="delete")return jsxs(da$1,{children:[jsx(ea,{children:jsxs(ha$1,{children:[jsx(ia$1,{children:"Records to delete"}),t.map(r=>jsx(ia$1,{children:r},r))]})}),jsx(fa$1,{children:e.rows.map((r,n)=>jsxs(ha$1,{className:"fk:bg-destructive/5",children:[jsx(ja$1,{className:"fk:font-mono fk:text-xs fk:text-destructive",children:r.id??O(r.before?._id)}),t.map(s=>jsx(ja$1,{className:"fk:text-xs fk:text-muted-foreground",children:O(r.before?.[s])},s))]},r.id??n.toString()))})]});let a=e.columns.filter(r=>r!=="_id"&&!t.includes(r));return jsxs(da$1,{children:[jsx(ea,{children:jsxs(ha$1,{children:[jsx(ia$1,{children:"ID"}),t.map(r=>jsx(ia$1,{children:r},r)),a.map(r=>jsx(ia$1,{children:r},r))]})}),jsx(fa$1,{children:e.rows.map((r,n)=>jsxs(ha$1,{children:[jsx(ja$1,{className:"fk:font-mono fk:text-xs fk:text-muted-foreground",children:r.id??"\u2014"}),t.map(s=>jsx(ja$1,{className:"fk:max-w-72 fk:text-xs fk:text-muted-foreground",children:jsx("span",{className:"fk:line-clamp-3",children:O(r.before?.[s])})},s)),a.map(s=>jsx(ja$1,{className:"fk:text-xs",children:e.kind==="create"?jsx("span",{className:"fk:rounded fk:bg-success/15 fk:px-1 fk:text-success fk:corner-squircle",children:O(r.after?.[s])}):jsx(Rt,{after:r.after?.[s],before:r.before?.[s]})},s))]},r.id??n.toString()))})]})}function Pt({operations:e,plugin:t,chat:a,title:r}){return jsxs("details",{className:"fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:[jsx("summary",{className:"fk:cursor-pointer fk:px-3 fk:py-2 fk:text-xs fk:font-medium fk:text-muted-foreground",children:r??(a?"Action details":t?"Plugin tool and arguments":`GraphQL documents (${e.length})`)}),jsx("div",{className:"fk:space-y-3 fk:border-t fk:border-border fk:p-3",children:e.map((n,s)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("pre",{className:"fk:overflow-x-auto fk:rounded-md fk:bg-muted fk:p-3 fk:text-xs fk:corner-squircle",children:n.query}),n.variables&&Object.keys(n.variables).length>0?jsx("pre",{className:"fk:overflow-x-auto fk:rounded-md fk:bg-muted/60 fk:p-3 fk:text-xs fk:corner-squircle",children:JSON.stringify(n.variables,null,2)}):null]},s.toString()))})]})}function qe(e){if(e.kind!=="plugin")return null;let a=e.operations[0]?.query.split(`
2
+ `)[0]?.trim()?.split("/"),r=a?.at(-1),n=a?.[0];if(!r||!n||a?.length<2)return null;let s=r.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase(),u=n.replace(/[_-]+/g," ").replace(/\b\w/g,k=>k.toUpperCase()),d=e.operations[0]?.query??"",f=/^Connection:\s*(Project|Personal)\s+—\s+(.+)$/m.exec(d);if(f?.[1]&&f[2])return {action:s,app:u,account:f[2].trim(),scope:f[1]==="Project"?"project":"personal"};let h=/^Connection:.*?([^\s<>]+@[^\s<>]+)\s*$/m.exec(d)?.[1];return {action:s,app:u,account:h}}function Ct(e){let t=qe(e);return t?`${t.action.charAt(0).toUpperCase()}${t.action.slice(1)} in ${t.app}`:e.kind==="exec"?"Run a sandbox command":e.kind==="plugin"?"Use a connected app":e.operationsSummary}function Nt(e,t){return e.id===t.id&&e.status===t.status&&e.decidedAt===t.decidedAt&&e.decidedBy===t.decidedBy&&e.executedAt===t.executedAt&&e.error===t.error&&e.reason===t.reason&&e.expiresAt===t.expiresAt&&e.operationsSummary===t.operationsSummary&&e.affectedCount===t.affectedCount&&JSON.stringify(e.preview)===JSON.stringify(t.preview)}function Je({api:e,approval:t,onDecided:a}){let[r,n]=useState(t),[s,u]=useState(t),[d,f]=useState(""),[h,k]=useTransition(),[S,g]=useState(false),[y,x]=useState(false),[j,E]=useState(""),re=_e();t!==s&&(u(t),Nt(t,s)||r.id===t.id&&r.status!=="pending"&&t.status==="pending"||n(t));function R(N){n(N),re(),a?.(N);}function P({approved:N,force:ne=false,reason:U,remember:T=false}){k(async()=>{f("");try{let b=await e.decideApproval(r.id,{approved:N,force:ne,reason:U,remember:T});if(b.errorCode==="stale_preview"){x(!0),b.approval&&n(b.approval);return}if(x(!1),g(!1),b.approval?R(b.approval):b.success?R({...r,decidedAt:r.decidedAt??new Date().toISOString(),reason:U??r.reason,status:N?"approved":"rejected"}):b.errorCode==="already_decided"&&a?.(r),!b.success&&(b.errorCode!=="already_decided"||!b.approval)){let C=Array.isArray(b.errorMessage)?b.errorMessage.join(", "):b.errorMessage;f(C||"Failed to submit the decision.");}}catch(b){f(b instanceof Error?b.message:"Failed to submit the decision.");}});}return {approval:r,decide:P,errorMessage:d,isDeciding:h,isPending:r.status==="pending",isRejectDialogOpen:S,isStale:y,rejectReason:j,setIsRejectDialogOpen:g,setRejectReason:E}}function Xe({allowRemember:e=false,askForRejectionReason:t,decide:a,isDeciding:r,isRejectDialogOpen:n,isStale:s,rejectReason:u,setIsRejectDialogOpen:d,setRejectReason:f,variant:h$1}){let k$1=h$1==="header",S=k$1?"fk:px-8 fk:min-w-32":void 0,g=k$1?"default":"sm",[y,x]=useState(false),j$1=useId();return jsxs(Fragment,{children:[jsxs("div",{className:"fk:flex fk:flex-nowrap fk:items-center fk:gap-2",children:[jsxs(d$1,{className:S,disabled:r,size:g,onClick:()=>a({approved:true,force:s,remember:e&&y}),children:[r?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),s?"Approve anyway":"Approve"]}),jsxs(d$1,{className:S,disabled:r,size:g,variant:"outline",onClick:()=>{t?(f(""),d(true)):a({approved:false});},children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]}),e?jsxs("label",{className:"fk:ml-1 fk:flex fk:cursor-pointer fk:items-center fk:gap-1.5 fk:whitespace-nowrap fk:text-xs fk:text-muted-foreground",htmlFor:j$1,children:[jsx(o,{checked:y,id:j$1,onCheckedChange:E=>x(E===true)}),"Always allow this tool for this automation"]}):null]}),t?jsx(c,{open:n,onOpenChange:d,children:jsxs(h,{children:[jsxs(i,{children:[jsx(k,{children:"Reject this proposal?"}),jsx(l,{children:"The mutation will not be executed. The agent receives your reason and can adapt its plan."})]}),jsx(pa$1,{placeholder:"Optional reason for the agent...",value:u,onChange:E=>f(E.target.value)}),jsxs(j,{children:[jsx(d$1,{disabled:r,size:"sm",variant:"outline",onClick:()=>d(false),children:"Cancel"}),jsxs(d$1,{disabled:r,size:"sm",variant:"destructive",onClick:()=>a({approved:false,reason:u.trim()||void 0}),children:[r?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(ArrowRightIcon,{className:"fk:size-4"}),"Reject proposal"]})]})]})}):null]})}function He({approval:e,chat:t,errorMessage:a,isPending:r,isStale:n}){let{preview:s}=e,u=t?qe(e):null;return jsxs("div",{className:"fk:min-w-0 fk:max-w-full fk:space-y-4",children:[jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsx(xt,{status:e.status}),jsx("span",{className:"fk:text-sm fk:font-medium",children:t?Ct(e):e.operationsSummary})]}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[e.automationName?`${e.automationName} \xB7 `:"","requested ",formatDistance(new Date(e.requestedAt),new Date,{addSuffix:true}),r?` \xB7 expires ${formatDistance(new Date(e.expiresAt),new Date,{addSuffix:true})}`:"",e.decidedAt?` \xB7 decided ${format(new Date(e.decidedAt),"PPpp")}`:""]}),n?jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-md fk:border fk:border-amber-500/40 fk:bg-amber-500/10 fk:p-3 fk:text-sm fk:corner-squircle",children:[jsx(TriangleAlertIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0 fk:text-amber-600"}),jsx("span",{children:"The affected data changed since this proposal was created. The preview below has been refreshed \u2014 review it and approve again to proceed."})]}):null,s&&s.operations.length>0?jsx("div",{className:"fk:space-y-4",children:s.operations.map((d,f)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:St(d)}),d.kind==="delete"&&d.affectedCount!==null?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:text-destructive fk:corner-squircle",children:[d.affectedCount.toString()," record",d.affectedCount===1?"":"s"," will be permanently deleted."]}):null,jsx(wt,{operation:d}),d.truncated?jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:["Preview limited to the first ",d.rows.length.toString()," rows."]}):null]},f.toString()))}):jsx("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:p-3 fk:text-xs fk:text-muted-foreground fk:corner-squircle",children:t?u?`This action uses ${u.scope==="project"?"the project's":"your"} ${u.app} account${u.account?` (${u.account})`:""}. Check the details before deciding.`:"The assistant wants to make this change. Check the details before deciding.":e.kind==="plugin"?"Review the account, tool, and arguments before allowing this external call.":e.kind==="exec"?"This command runs inside the run's ephemeral sandbox but may send data out or reach other hosts. Review the command line before allowing it.":"No structured preview is available for this proposal. Review the raw GraphQL documents below."}),jsx(Pt,{chat:t,operations:e.operations,plugin:e.kind==="plugin"||e.kind==="exec",title:e.kind==="exec"?"Command and options":void 0}),e.reason?jsxs("div",{className:"fk:text-sm",children:[jsx("span",{className:"fk:font-medium",children:"Reason:"})," ",e.reason]}):null,e.error?jsxs("div",{className:"fk:rounded-md fk:border fk:border-destructive/30 fk:bg-destructive/5 fk:p-3 fk:text-sm fk:corner-squircle",children:["Execution failed: ",e.error]}):null,e.executedAt&&!e.error?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-sm fk:text-success",children:[jsx(CheckIcon,{className:"fk:size-4"}),"Executed ",format(new Date(e.executedAt),"PPpp")]}):null,a?jsx("div",{className:"fk:text-sm fk:text-destructive",children:a}):null]})}function Fe({api:e,approval:t,chat:a,onDecided:r}){let{approval:n,decide:s,errorMessage:u,isDeciding:d,isPending:f,isRejectDialogOpen:h,isStale:k,rejectReason:S,setIsRejectDialogOpen:g,setRejectReason:y}=Je({api:e,approval:t,onDecided:r});return jsxs(Fragment,{children:[jsx(He,{approval:n,chat:a,errorMessage:u,isPending:f,isStale:k}),f?jsx("div",{className:"fk:mt-4",children:jsx(Xe,{allowRemember:!a&&n.kind==="plugin"&&!!n.automationId,askForRejectionReason:!a,decide:s,isDeciding:d,isRejectDialogOpen:h,isStale:k,rejectReason:S,setIsRejectDialogOpen:g,setRejectReason:y,variant:"inline"})}):null]})}function Zr({api:e,approval:t,onClose:a,onDecided:r}){let{approval:n,decide:s,errorMessage:u,isDeciding:d,isPending:f,isRejectDialogOpen:h,isStale:k,rejectReason:S,setIsRejectDialogOpen:g,setRejectReason:y}=Je({api:e,approval:t,onDecided:r});return jsx(sa$1,{actions:f?jsx(Xe,{allowRemember:n.kind==="plugin"&&!!n.automationId,askForRejectionReason:true,decide:s,isDeciding:d,isRejectDialogOpen:h,isStale:k,rejectReason:S,setIsRejectDialogOpen:g,setRejectReason:y,variant:"header"}):null,depth:0,isFocused:true,onClose:a,title:"Mutation proposal",children:jsx(He,{approval:n,chat:false,errorMessage:u,isPending:f,isStale:k})})}var At="Approved by Flexkit Jev policy",Tt="Approved by automation tool allow rule",Mt=new Set(["data-create-sandbox","data-execute-graphql","data-load-skill","data-plan","data-plugin-call","data-run-command","data-search-schema","data-update-memory","data-validate-graphql","data-web-search"]);function X(e){return Mt.has(e)}function p(e){return e.data}function oe(e){return !e.decidedBy&&!!(e.reason?.startsWith(At)||e.reason?.startsWith(Tt))}function _(e,t=72){let a=e.trim();if(a.length<=t)return a;let r=a.slice(0,t),n=r.lastIndexOf(" ");return `${(n>=Math.floor(t*.6)?r.slice(0,n):r).trimEnd()}\u2026`}function Dt(e){return e.replace(/^#{1,6}\s+/,"").replace(/^(?:[-*+]|\d+[.)])\s+/,"").replace(/!?\[([^\]]*)\]\([^)]*\)/g,"$1").replace(/(\*\*|__)(.*?)\1/g,"$2").replace(/(\*|_)(.*?)\1/g,"$2").replace(/`([^`]*)`/g,"$1").replace(/[*_`#>]/g,"").replace(/\s+/g," ").trim().replace(/[.:]+$/,"")}function It(e){let t=e.lastIndexOf(`
3
+ `),a=-1,r=/[.!?](?=\s)/g,n;for(;(n=r.exec(e))!==null;)a=n.index;let s=Math.max(t,a);return s<0?"":e.slice(0,s+1)}function $t(e,t){let r=(It(e)).split(/\r?\n/).map(f=>f.trim()).filter(Boolean),n=r[r.length-1];if(!n)return null;let u=/^\*\*(.+?)\*\*:?$/.exec(n)?.[1]??/^#{1,6}\s+(.+)$/.exec(n)?.[1]??/^(.+?[.!?])(?:\s|$)/.exec(n)?.[1]??n,d=Dt(u);return !d||/^reasoning$/i.test(d)?null:_(d)}function Ke(e){return e.replace(/[_-]+/g," ").trim()}function Et(e){if(e.type==="data-load-skill"){let t=p(e);return t.status!=="loading"?null:t.skillName?_(`Loading skill "${t.skillName}"`):"Loading skill"}if(e.type==="data-search-schema")return p(e).status==="loading"?"Searching schema":null;if(e.type==="data-validate-graphql")return p(e).status==="loading"?"Validating GraphQL query":null;if(e.type==="data-execute-graphql"){let t=p(e);return t.status!=="loading"?null:t.operationType==="mutation"?"Executing GraphQL mutation":"Executing GraphQL query"}if(e.type==="data-update-memory")return p(e).status==="loading"?"Updating memory":null;if(e.type==="data-web-search"){let t=p(e);return t.status!=="loading"?null:t.query?_(`Searching the web for "${t.query}"`):"Searching the web"}if(e.type==="data-run-command"){let t=p(e);return ["executing","running","waiting"].includes(t.status)?_(`Running ${[t.command,...t.args].join(" ")}`):null}if(e.type==="data-create-sandbox")return p(e).status==="loading"?"Creating sandbox":null;if(e.type==="data-plugin-call"){let t=p(e);return t.status!=="loading"?null:_(`Calling ${t.pluginId}: ${Ke(t.tool)}`)}if(e.type==="data-subtask"){let t=p(e);return t.status==="running"?_(`Running subtask: ${t.title}`):null}return null}var Lt=new Set(["data-execute-graphql","data-search-schema","data-validate-graphql"]);function Y(e){if(!X(e.type)||e.type==="data-plan"||Lt.has(e.type))return null;let t=p(e);if(t.status!=="error")return null;if(t.error?.message)return t.error.message;switch(e.type){case "data-web-search":return "Failed to search the web";case "data-run-command":return `Command failed: ${String(t.command??"")}`.trim();case "data-create-sandbox":return "Failed to create sandbox";case "data-load-skill":return "Failed to load skill";case "data-update-memory":return "Failed to update memory";case "data-plugin-call":return `Plugin call failed: ${String(t.pluginId??"")}: ${Ke(String(t.tool??""))}`;default:return "The tool call failed"}}function Q(e){if(e.type==="step-start"||e.type==="reasoning")return true;if(X(e.type))return Y(e)===null;if(e.type==="data-mutation-approval"){let t=p(e);return oe(t)&&t.status!=="error"}return false}function V(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let a=e.parts[t];if(a?.type!=="data-plan")continue;let r=p(a),n=r.steps.findIndex(s=>s.status==="in_progress");return n<0?null:_(`Step ${(n+1).toString()} of ${r.steps.length.toString()}: ${r.steps[n].step}`)}return null}function _t(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let a=e.parts[t];if(!(!a||a.type==="step-start"))return a.type==="reasoning"?a.state==="streaming"?$t(a.text)??V(e):V(e):a.type==="data-mutation-approval"?p(a).status==="pending"?"Awaiting approval":V(e):a.type==="text"?null:Et(a)??V(e)}return null}var sa={sm:"fk:max-w-sm",md:"fk:max-w-md",lg:"fk:max-w-lg",full:"fk:max-w-full"},oa=({children:e,element:t})=>{let{props:a}=t,r=a.maxWidth?sa[a.maxWidth]:"",n=a.centered?"fk:mx-auto":"";return jsxs("div",{className:`fk:w-full fk:rounded-lg fk:border fk:border-border fk:bg-card fk:p-4 fk:gap-2 fk:flex fk:flex-col ${r} ${n} ${a.className??""} fk:corner-squircle`,children:[a.title&&jsx("div",{className:"fk:text-sm fk:font-medium",children:a.title}),a.description&&jsx("div",{className:"fk:mt-0.5 fk:text-xs fk:text-muted-foreground",children:a.description}),(a.title??a.description)&&e?jsx("div",{className:"fk:mt-3"}):null,e]})},ia={none:"fk:gap-0",sm:"fk:gap-2",md:"fk:gap-3",lg:"fk:gap-4",xl:"fk:gap-6"},la={start:"fk:items-start",center:"fk:items-center",end:"fk:items-end",stretch:"fk:items-stretch"},ua={start:"fk:justify-start",center:"fk:justify-center",end:"fk:justify-end",between:"fk:justify-between",around:"fk:justify-around"},da=({children:e,element:t})=>{let{props:a}=t,r=a.direction==="horizontal"?"fk:flex-row fk:flex-wrap":"fk:flex-col",n=ia[a.gap??"md"],s=a.align?la[a.align]:"",u=a.justify?ua[a.justify]:"";return jsx("div",{className:`fk:flex fk:w-full ${r} ${n} ${s} ${u} ${a.className??""}`,children:e})},ca={1:"fk:grid-cols-1",2:"fk:grid-cols-2",3:"fk:grid-cols-3",4:"fk:grid-cols-4",5:"fk:grid-cols-5",6:"fk:grid-cols-6"},fa={sm:"fk:gap-2",md:"fk:gap-3",lg:"fk:gap-4",xl:"fk:gap-6"},pa=({children:e,element:t})=>{let{props:a}=t,r=ca[a.columns??1]??"fk:grid-cols-1",n=fa[a.gap??"md"];return jsx("div",{className:`fk:grid fk:w-full ${r} ${n} ${a.className??""}`,children:e})},ma=({element:e})=>jsx(v,{orientation:e.props.orientation??"horizontal"}),ka={h1:"fk:text-xl fk:font-semibold fk:tracking-tight",h2:"fk:text-lg fk:font-semibold fk:tracking-tight",h3:"fk:text-base fk:font-medium",h4:"fk:text-sm fk:font-medium"},ga=({element:e})=>{let t=e.props.level??"h2";return jsx(t,{className:ka[t],children:e.props.text})},ya={body:"fk:text-sm",muted:"fk:text-sm fk:text-muted-foreground",caption:"fk:text-xs fk:text-muted-foreground",lead:"fk:text-base",code:"fk:rounded fk:bg-muted fk:px-1 fk:py-0.5 fk:font-mono fk:text-xs fk:corner-squircle"},va=({element:e})=>jsx("p",{className:ya[e.props.variant??"body"],children:e.props.text}),ba=({element:e})=>jsx(b,{variant:e.props.variant??"default",children:e.props.text});function ha({type:e}){switch(e){case "success":return jsx(CheckCircle2Icon,{className:"fk:size-4 fk:translate-y-0.5"});case "warning":return jsx(AlertTriangleIcon,{className:"fk:size-4 fk:translate-y-0.5"});case "error":return jsx(XCircleIcon,{className:"fk:size-4 fk:translate-y-0.5"});default:return jsx(InfoIcon,{className:"fk:size-4 fk:translate-y-0.5"})}}var xa=({element:e})=>{let{props:t}=e,a=t.type==="error"?"fk:border-destructive/50 fk:text-destructive":"fk:text-foreground";return jsxs("div",{className:`fk:flex fk:w-full fk:gap-3 fk:rounded-lg fk:border fk:bg-card fk:px-4 fk:py-3 fk:text-sm ${a} fk:corner-squircle`,role:"alert",children:[jsx(ha,{type:t.type}),jsxs("div",{className:"fk:min-w-0",children:[jsx("div",{className:"fk:font-medium",children:t.title}),t.message&&jsx("div",{className:"fk:text-muted-foreground",children:t.message})]})]})},Ra=({element:e})=>{let t=e.props.columns??[],a=(e.props.rows??[]).map(r=>r.map(String));return jsx("div",{className:"fk:w-full fk:overflow-hidden fk:rounded-md fk:mt-2 fk:corner-squircle",children:jsxs(da$1,{children:[e.props.caption&&jsx(ka$1,{children:e.props.caption}),jsx(ea,{children:jsx(ha$1,{children:t.map((r,n)=>jsx(ia$1,{children:r},`${n.toString()}-${r}`))})}),jsx(fa$1,{children:a.map((r,n)=>jsx(ha$1,{children:r.map((s,u)=>jsx(ja$1,{children:s},u))},n))})]})})},Sa=({element:e})=>{let{props:t}=e,a=t.max??100,r=a>0?Math.min(100,Math.max(0,t.value/a*100)):0;return jsxs("div",{className:"fk:w-full",children:[t.label&&jsxs("div",{className:"fk:mb-1 fk:flex fk:items-center fk:justify-between fk:text-xs fk:text-muted-foreground",children:[jsx("span",{children:t.label}),jsxs("span",{className:"fk:tabular-nums",children:[Math.round(r),"%"]})]}),jsx("div",{className:"fk:h-2 fk:w-full fk:overflow-hidden fk:rounded-full fk:bg-secondary fk:corner-squircle",children:jsx("div",{className:"fk:h-full fk:rounded-full fk:bg-primary fk:corner-squircle",style:{width:`${r.toString()}%`}})})]})},wa=({element:e})=>jsx(t,{className:e.props.rounded?"fk:rounded-full fk:corner-squircle":"",style:{height:e.props.height??"1rem",width:e.props.width??"100%"}}),Pa=({element:e})=>jsx(f$2,{href:e.props.href,children:e.props.label}),Ca=({element:e})=>e.props.src?jsx("img",{alt:e.props.alt,className:"fk:max-w-full fk:rounded-md fk:corner-squircle",height:e.props.height??void 0,src:e.props.src,width:e.props.width??void 0}):null,Na=({element:e})=>jsx("div",{className:"fk:w-full fk:divide-y fk:divide-border fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:(e.props.items??[]).map((t,a)=>jsxs("details",{className:"fk:group fk:px-4 fk:py-3",children:[jsx("summary",{className:"fk:cursor-pointer fk:list-none fk:text-sm fk:font-medium",children:t.title}),jsx("p",{className:"fk:mt-2 fk:text-sm fk:text-muted-foreground",children:t.content})]},a))}),Aa=({children:e,element:t})=>{let a=t.props.tabs??[];return jsxs(la$1,{defaultValue:t.props.value??t.props.defaultValue??a[0]?.value,children:[jsx(ma$1,{children:a.map(r=>jsx(na,{value:r.value,children:r.label},r.value))}),e]})},Ta=({children:e,element:t})=>jsx(oa$1,{value:t.props.value,children:e}),Ma={up:"fk:text-success",down:"fk:text-destructive",neutral:"fk:text-muted-foreground"};function Da({trend:e}){return e==="up"?jsx(TrendingUpIcon,{className:"fk:size-4"}):e==="down"?jsx(TrendingDownIcon,{className:"fk:size-4"}):jsx(MinusIcon,{className:"fk:size-4"})}var Ia=({element:e})=>{let{props:t}=e;return jsxs("div",{className:"fk:w-full fk:rounded-lg fk:border fk:border-border fk:bg-card fk:p-4 fk:corner-squircle",children:[jsx("div",{className:"fk:text-xs fk:font-medium fk:text-muted-foreground",children:t.label}),jsxs("div",{className:"fk:mt-1 fk:flex fk:items-center fk:gap-2",children:[jsx("span",{className:"fk:text-2xl fk:font-semibold fk:tabular-nums fk:tracking-tight",children:t.value}),t.trend&&jsx("span",{className:Ma[t.trend],children:jsx(Da,{trend:t.trend})})]}),t.detail&&jsx("div",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:t.detail})]})},$a={info:"fk:border-blue-500/30 fk:bg-blue-500/5 fk:text-blue-700 fk:dark:text-blue-400",tip:"fk:border-emerald-500/30 fk:bg-emerald-500/5 fk:text-emerald-700 fk:dark:text-emerald-400",warning:"fk:border-amber-500/30 fk:bg-amber-500/5 fk:text-amber-700 fk:dark:text-amber-400",important:"fk:border-red-500/30 fk:bg-red-500/5 fk:text-red-700 fk:dark:text-red-400"};function Ea({type:e}){switch(e){case "tip":return jsx(LightbulbIcon,{className:"fk:size-4 fk:shrink-0 fk:translate-y-0.5"});case "warning":return jsx(AlertTriangleIcon,{className:"fk:size-4 fk:shrink-0 fk:translate-y-0.5"});case "important":return jsx(OctagonAlertIcon,{className:"fk:size-4 fk:shrink-0 fk:translate-y-0.5"});default:return jsx(InfoIcon,{className:"fk:size-4 fk:shrink-0 fk:translate-y-0.5"})}}var La=({element:e})=>{let{props:t}=e,a=t.type??"info";return jsxs("div",{className:`fk:flex fk:w-full fk:gap-3 fk:rounded-lg fk:border fk:px-4 fk:py-3 fk:text-sm ${$a[a]} fk:corner-squircle`,children:[jsx(Ea,{type:a}),jsxs("div",{className:"fk:min-w-0",children:[t.title&&jsx("div",{className:"fk:font-medium",children:t.title}),jsx("div",{className:"fk:text-foreground",children:t.content})]})]})},_a={completed:"fk:border-success fk:bg-success",current:"fk:border-primary fk:bg-primary",upcoming:"fk:border-border fk:bg-background"},za=({element:e})=>jsx("div",{className:"fk:w-full",children:(e.props.items??[]).map((t,a,r)=>jsxs("div",{className:"fk:relative fk:flex fk:gap-3 fk:pb-4 fk:last:pb-0",children:[a<r.length-1&&jsx("div",{className:"fk:absolute fk:left-[5px] fk:top-4 fk:h-full fk:w-px fk:bg-border"}),jsx("div",{className:`fk:mt-1 fk:size-[11px] fk:shrink-0 fk:rounded-full fk:border-2 ${_a[t.status??"upcoming"]} fk:corner-squircle`}),jsxs("div",{className:"fk:min-w-0",children:[jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-baseline fk:gap-x-2",children:[jsx("span",{className:"fk:text-sm fk:font-medium",children:t.title}),t.date&&jsx("span",{className:"fk:text-xs fk:text-muted-foreground",children:t.date})]}),t.description&&jsx("div",{className:"fk:text-sm fk:text-muted-foreground",children:t.description})]})]},a))}),Z=["#6366f1","#10b981","#f59e0b","#ef4444","#06b6d4"],ue={background:"hsl(var(--background))",border:"1px solid hsl(var(--border))",borderRadius:6,color:"hsl(var(--foreground))",fontSize:12},de={color:"hsl(var(--foreground))"},ce={color:"hsl(var(--foreground))"},ee={fill:"hsl(var(--muted-foreground))",fontSize:11};function ie(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:0}function tt(e){let t=e.data??[];if(!e.aggregate)return t.map(r=>({x:String(r[e.xKey]??""),y:ie(r[e.yKey])}));let a=new Map;for(let r of t){let n=String(r[e.xKey]??""),s=a.get(n)??{count:0,sum:0};s.count+=1,s.sum+=ie(r[e.yKey]),a.set(n,s);}return Array.from(a.entries()).map(([r,n])=>e.aggregate==="count"?{x:r,y:n.count}:e.aggregate==="avg"?{x:r,y:n.count===0?0:n.sum/n.count}:{x:r,y:n.sum})}function fe({children:e,height:t,title:a}){return jsxs("div",{className:"fk:w-full",children:[a&&jsx("div",{className:"fk:mb-2 fk:text-sm fk:font-medium",children:a}),jsx("div",{style:{height:t??256},children:jsx(ResponsiveContainer,{height:"100%",width:"100%",children:e})})]})}var ja=({element:e})=>{let t=tt(e.props),a=e.props.color??Z[0];return jsx(fe,{height:e.props.height,title:e.props.title,children:jsxs(BarChart,{data:t,children:[jsx(CartesianGrid,{stroke:"hsl(var(--border))",vertical:false}),jsx(XAxis,{axisLine:false,dataKey:"x",tick:ee,tickLine:false,tickMargin:8}),jsx(YAxis,{axisLine:false,tick:ee,tickLine:false,width:40}),jsx(Tooltip,{contentStyle:ue,cursor:{fill:"hsl(var(--muted))"},itemStyle:de,labelStyle:ce}),jsx(Bar,{dataKey:"y",fill:a,isAnimationActive:false,name:e.props.yKey,radius:4})]})})},Oa=({element:e})=>{let t=tt(e.props),a=e.props.color??Z[0];return jsx(fe,{height:e.props.height,title:e.props.title,children:jsxs(LineChart,{data:t,children:[jsx(CartesianGrid,{stroke:"hsl(var(--border))",vertical:false}),jsx(XAxis,{axisLine:false,dataKey:"x",tick:ee,tickLine:false,tickMargin:8}),jsx(YAxis,{axisLine:false,tick:ee,tickLine:false,width:40}),jsx(Tooltip,{contentStyle:ue,itemStyle:de,labelStyle:ce}),jsx(Line,{dataKey:"y",dot:false,isAnimationActive:false,name:e.props.yKey,stroke:a,strokeWidth:2,type:"monotone"})]})})},Ba=({element:e})=>{let t=(e.props.data??[]).map(a=>({name:String(a[e.props.nameKey]??""),value:ie(a[e.props.valueKey])}));return jsx(fe,{height:e.props.height,title:e.props.title,children:jsxs(PieChart,{children:[jsx(Tooltip,{contentStyle:ue,itemStyle:de,labelStyle:ce}),jsx(Pie,{data:t,dataKey:"value",innerRadius:"45%",isAnimationActive:false,nameKey:"name",children:t.map((a,r)=>jsx(Cell,{fill:Z[r%Z.length]},`${a.name}-${r.toString()}`))})]})})},qa=({element:e})=>{let{chart:t$1,title:a}=e.props,r=useId().replace(/[^a-zA-Z0-9]/g,""),[n,s]=useState(null),[u,d]=useState(null);return useEffect(()=>{let f=false;return (async()=>{try{let{default:k}=await import('mermaid'),S=document.documentElement.classList.contains("dark");k.initialize({securityLevel:"strict",startOnLoad:!1,theme:S?"dark":"default"});let g=await k.render(`fk-mermaid-${r}`,t$1);f||(s(g.svg),d(null));}catch(k){f||d(k instanceof Error?k.message:"Failed to render the diagram.");}})(),()=>{f=true;}},[t$1,r]),jsxs("div",{className:"fk:w-full fk:rounded-lg fk:border fk:border-border fk:bg-card fk:p-4 fk:corner-squircle",children:[a&&jsx("div",{className:"fk:mb-2 fk:text-sm fk:font-medium",children:a}),u?jsx("pre",{className:"fk:overflow-x-auto fk:whitespace-pre-wrap fk:text-xs fk:text-muted-foreground",children:t$1}):null,!u&&n?jsx("div",{className:"fk:flex fk:justify-center fk:overflow-x-auto",dangerouslySetInnerHTML:{__html:n}}):null,!u&&!n?jsx(t,{className:"fk:h-40 fk:w-full"}):null]})},Ja={Accordion:Na,Alert:xa,Badge:ba,BarChart:ja,Callout:La,Card:oa,Grid:pa,Heading:ga,Image:Ca,LineChart:Oa,Link:Pa,Mermaid:qa,Metric:Ia,PieChart:Ba,Progress:Sa,Separator:ma,Skeleton:wa,Stack:da,TabContent:Ta,Table:Ra,Tabs:Aa,Text:va,Timeline:za},Xa=({element:e})=>jsxs("div",{className:"fk:rounded-md fk:border fk:border-dashed fk:border-border fk:p-3 fk:text-sm fk:text-muted-foreground fk:corner-squircle",children:["Unsupported component: ",e.type]});function Ha(e,t){let a=new Set,r=[];for(let n of e??[]){let s=String(n);a.has(s)||!t[s]||(a.add(s),r.push(s));}return r}function Fa(e,t){return e.length!==t.length?true:t.some((a,r)=>a!==e[r])}function Ua(e){if(!e.elements[e.root])return null;let t=false,a={};for(let r of Object.keys(e.elements)){let n=e.elements[r];if(!n)continue;let s=n.children??[],u=Ha(s,e.elements),d=Fa(s,u);d&&(t=true),a[r]=d?{...n,children:u}:n;}return t?{...e,elements:a}:e}var Ka="data-spec";function Ga(e){let t=new Set,a=[];for(let r of e){if(r.type!==Ka)continue;let n=r.data;if(n&&typeof n=="object"&&"type"in n&&n.type==="patch"&&"patch"in n){let s=JSON.stringify(n.patch);if(t.has(s))continue;t.add(s);}a.push(r);}return a}function at({parts:e}){let t=useMemo(()=>{let r=buildSpecFromParts(Ga(e));return r?Ua(r):null},[e]),a=useMemo(()=>JSON.stringify(t?.state??{}),[t]);return t?jsx(StateProvider,{initialState:t.state,children:jsx(VisibilityProvider,{children:jsx(ActionProvider,{children:jsx(Renderer,{fallback:Xa,registry:Ja,spec:t})})})},a):null}function fr(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?d(e):null,[e]),projectId:e}}var nt=5,dt=2e3,pr=120,pe="data-spec",mr=createContext(null),kr=createContext(false);function gr(e){return new Promise(t=>window.setTimeout(t,e))}function yr(e){return e instanceof Error?e.name==="AbortError"||e.message.toLowerCase().includes("aborted"):false}function vr(e){return e.some(t=>!Q(t))}function br(e){let t=new Set;for(let a of e)for(let r of a.parts)r.type==="data-user-message"&&r.id&&t.add(r.id);return t}function hr(e){let t=br(e),a=[];for(let r of e){if(r.role==="user"){t.has(r.id)||a.push(r);continue}if(r.role!=="assistant"){a.push(r);continue}let n=[],s=0,u=()=>{vr(n)&&a.push({...r,id:`${r.id}-${s.toString()}`,parts:n}),s++,n=[];};for(let d of r.parts){if(d.type==="data-user-message"){let f=p(d);u(),a.push({id:d.id??crypto.randomUUID(),parts:f.parts,role:"user"});continue}n.push(d);}u();}return a}function Rn(e){return useMemo(()=>hr(e),[e])}function xr(e){return e?e.parts.some(t=>t.type!=="data-mutation-approval"?false:p(t).status==="pending"):false}function Rr(e){let t=e.parts.filter(a=>a.type!=="data-mutation-approval"?true:p(a).status!=="pending");return t.length===e.parts.length?e:{...e,parts:t}}function H(e){return e==="success"||e==="failed"||e==="cancelled"||e==="skipped"}function Sr(e,t){if(!e)return [];let a=[],r=t?.pendingOnly??false;for(let n of e.parts){if(n.type!=="data-mutation-approval")continue;let s=p(n);r&&s.status!=="pending"||a.push(s.approvalId);}return a}function Sn(e){return Sr(e,{pendingOnly:true})}function wr({latestMessage:e,recordStatus:t,suppressApprovalPause:a}){return H(t)||a||t==="running"?false:t==="awaiting_approval"?true:xr(e)}function wn(e,t){let[a,r]=useState(),[n,s]=useState("streaming"),u=t?.recordStatus,d=t?.resumeToken??0,f=useRef(t?.suppressApprovalPause??false);f.current=t?.suppressApprovalPause??false;let h=useRef(e),k=useRef(a);return k.current=a,useEffect(()=>{let S=h.current!==e;if(h.current=e,!e){r(void 0),s("unavailable");return}let g=new AbortController,y=S?void 0:k.current;if(S)r(void 0);else if(y&&(u==="running"||H(u))){let R=Rr(y);R!==y&&(y=R,r(R));}s("streaming");let x=e.includes("?")?"&":"?",j=async()=>{let R=await fetch(`${e}${x}startIndex=0`,{credentials:"include",signal:g.signal});if(R.status===404)return "unavailable";if(!R.ok||!R.body)throw new Error(`Failed to fetch the run stream (status ${R.status.toString()})`);let P=false,ne=parseJsonEventStream({schema:uiMessageChunkSchema,stream:R.body}).pipeThrough(new TransformStream({transform:(C,ct)=>{if(!C.success)throw C.error;C.value.type==="finish"&&(P=true),ct.enqueue(C.value);}})),U=readUIMessageStream({onError:C=>{g.signal.aborted||console.error("Run stream chunk error",C);},stream:ne}),T=null,b=()=>{g.signal.aborted||!y||r({...y});};try{for await(let C of U){if(g.signal.aborted)break;y=C,T===null&&(T=window.setTimeout(()=>{T=null,b();},pr));}}finally{T!==null&&(window.clearTimeout(T),T=null),b();}return P?"finished":"incomplete"},E=async()=>{let R=0;for(;!g.signal.aborted;){R>0&&await gr(dt);try{let P=await j();if(g.signal.aborted)return;if(P==="unavailable"){s("unavailable");return}if(P==="finished"&&H(u)){s("finished");return}if(H(u)){s("finished");return}if(wr({latestMessage:y,recordStatus:u,suppressApprovalPause:f.current})){s("paused");return}if(!(u==="running"||f.current)&&R>=nt-1){s("error");return}}catch(P){if(g.signal.aborted||yr(P))return;if(console.error("Run stream error",P),H(u)){s("finished");return}if(!(u==="running"||f.current)&&R>=nt-1){s("error");return}}R+=1;}},re=window.setTimeout(()=>{E();},0);return ()=>{window.clearTimeout(re),g.abort("Run replay unmounted");}},[u,d,e]),{message:a,status:n}}function Pn(e){return {affectedCount:e.affectedCount,approvalId:e.id,decidedBy:e.decidedBy??void 0,operationsSummary:e.operationsSummary,reason:e.reason??void 0,status:e.status}}function Pr(e){let t=e.trim();return t?t.split(`
4
+ `).every(a=>/^`{3,}[\w-]*$/.test(a.trim())):false}function Cn({api:e,part:t,partIndex:a,parts:r}){if(Q(t))return null;if(X(t.type)){let n=Y(t);return n?jsx(Nr,{message:n}):null}if(t.type==="text")return Pr(t.text)&&r.some(s=>s.type===pe)?null:jsx(Cr,{part:t});if(t.type==="data-generating-files")return jsx(Ir,{message:p(t)});if(t.type==="data-run-artifact")return jsx($r,{api:e,message:p(t)});if(t.type==="data-tool-delivery")return jsx(Er,{message:p(t)});if(t.type==="data-run-summary")return jsx(Lr,{message:p(t)});if(t.type==="data-subtask"){let n=p(t),s=n.status==="running"?`Running "${n.title}"`:n.status==="done"?`Completed "${n.title}"${typeof n.stepsUsed=="number"?` in ${n.stepsUsed.toString()} steps`:""}`:`"${n.title}" failed: ${n.error?.message??"unknown error"}`;return jsxs(A,{children:[jsxs($,{children:[jsx(BotIcon,{className:"fk:size-3.5"}),"Subtask"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ae,{isError:n.status==="error",loading:n.status==="running"})}),jsx("span",{className:"fk:text-xs",children:s}),n.resultPreview?jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:n.resultPreview}):null]})]})}if(t.type==="data-context-compaction"){let n=p(t);return jsxs("p",{className:"fk:text-xs fk:text-muted-foreground",children:["Earlier messages (",n.summarizedMessageCount.toString(),") were summarized to keep this conversation within the model's context. Details may need to be re-fetched."]})}if(t.type==="data-plugin-connection"){let n=p(t);return jsx(Jr,{pluginId:n.pluginId})}if(t.type==="data-suggested-prompt")return null;if(t.type==="data-turn-error"){let n=p(t);return jsxs(A,{className:"fk:border-red-700/40",children:[jsxs($,{children:[jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),jsx("span",{children:"Turn failed"})]}),jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:n.message})]})}if(t.type==="data-mutation-approval"){let n=p(t);return oe(n)?jsx(zr,{message:n}):jsx(_r,{api:e,message:n})}return t.type==="data-bulk-graphql-action"?jsx(jr,{message:p(t)}):t.type===pe?r.slice(a+1).find(s=>s.type===pe)?null:jsx(at,{parts:r}):t.type.startsWith("data-")?jsx(Or,{part:t}):null}function Cr({part:e}){return jsx(ub,{className:"fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:text-base fk:leading-relaxed fk:text-foreground",isAnimating:e.state==="streaming",children:e.text})}function Nr({message:e}){return jsxs("div",{className:"fk:flex fk:items-start fk:gap-2 fk:rounded-xl fk:border fk:border-red-700/40 fk:bg-destructive/5 fk:px-3.5 fk:py-3 fk:text-sm fk:corner-squircle",children:[jsx(XCircleIcon,{className:"fk:mt-0.5 fk:size-3.5 fk:shrink-0 fk:text-red-700"}),jsx("span",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e})]})}var Ar=1e3;function Tr({text:e}){let t=useRef(typeof performance>"u"?0:performance.now()),a=()=>-(((typeof performance>"u"?0:performance.now())-t.current)%Ar),[r,n]=useState({current:e,currentDelayMs:0,key:0,previous:null,previousDelayMs:0});return useEffect(()=>{n(s=>s.current===e?s:{current:e,currentDelayMs:a(),key:s.key+1,previous:s.current,previousDelayMs:s.currentDelayMs});},[e]),jsxs("span",{className:"fk:relative fk:block fk:h-5 fk:min-w-0 fk:flex-1 fk:overflow-hidden",children:[r.previous?jsx("span",{"aria-hidden":true,className:"fk:absolute fk:inset-x-0 fk:top-0 fk:block fk:animate-roll-up-out",children:jsx("span",{className:"fk:block fk:truncate fk:shimmer fk:shimmer-duration-1000",style:{animationDelay:`${r.previousDelayMs.toString()}ms`},children:r.previous})},`previous-${r.key.toString()}`):null,jsx("span",{className:r.previous?"fk:block fk:animate-roll-up-in":"fk:block",role:"status",children:jsx("span",{className:"fk:block fk:truncate fk:shimmer fk:shimmer-duration-1000",style:{animationDelay:`${r.currentDelayMs.toString()}ms`},children:r.current})},`current-${r.key.toString()}`)]})}var Mr=1e3;function Dr(e,t){let a=Mr,[r,n]=useState(e),s=useRef(Date.now()),u=useRef(e);return u.current=e,useEffect(()=>{if(e===r)return;let d=Math.max(0,a-(Date.now()-s.current)),f=window.setTimeout(()=>{s.current=Date.now(),n(u.current);},d);return ()=>{window.clearTimeout(f);}},[r,e,a]),r}function Nn({label:e,visible:t}){let a=Dr(e);return jsx("div",{"aria-hidden":!t,className:`fk:flex fk:h-9 fk:items-center fk:text-sm fk:text-muted-foreground fk:transition-[opacity,visibility] fk:duration-200 ${t?"fk:visible fk:opacity-100":"fk:invisible fk:opacity-0"}`,children:jsx(Tr,{text:a})})}function A({children:e,className:t=""}){return jsx("div",{className:`fk:min-w-0 fk:max-w-full fk:overflow-x-auto fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-3.5 fk:py-3 fk:text-sm ${t} fk:corner-squircle`,children:e})}function $({children:e}){return jsx("div",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-muted-foreground",children:e})}function ae({isError:e,loading:t}){return t?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):e?jsx(XIcon,{className:"fk:size-4 fk:text-red-700"}):jsx(CheckIcon,{className:"fk:size-4"})}function ge({error:e,icon:t,loading:a,message:r,title:n}){return jsxs(A,{children:[jsxs($,{children:[t,n]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ae,{isError:!!e,loading:a})}),jsx("span",{className:"fk:text-xs",children:r})]})]})}function Ir({message:e}){let t=["error","uploading","generating"].includes(e.status),a=t?e.paths.slice(0,e.paths.length-1):e.paths,r=t?e.paths[e.paths.length-1]??"":null;return jsxs(A,{children:[jsxs($,{children:[jsx(CloudUploadIcon,{className:"fk:size-3.5"}),jsx("span",{children:e.status==="done"?"Uploaded files":"Generating files"})]}),jsxs("div",{className:"fk:space-y-1 fk:text-sm",children:[a.map((n,s)=>jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(CheckIcon,{className:"fk:size-4"}),jsx("span",{className:"fk:whitespace-pre-wrap",children:n})]},`${n}-${s.toString()}`)),typeof r=="string"?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(ae,{isError:e.status==="error",loading:e.status!=="error"}),jsx("span",{children:e.status==="error"?e.error?.message??r:r})]}):null]})]})}function $r({api:e,message:t}){let a=t.status==="done"&&t.artifactId,r=a?e.getArtifactUrl(t.artifactId??""):"",n=a?e.getArtifactUrl(t.artifactId??"",{download:true}):"",s=Br(t.sizeBytes);return jsxs(A,{children:[jsxs($,{children:[jsx(FileTextIcon,{className:"fk:size-3.5"}),t.status==="done"?"Published artifact":"Publishing artifact"]}),jsxs("div",{className:"fk:relative fk:min-h-5 fk:pl-6",children:[jsx("span",{className:"fk:absolute fk:left-0 fk:top-0",children:jsx(ae,{isError:t.status==="error",loading:t.status==="uploading"})}),jsxs("div",{className:"fk:min-w-0 fk:space-y-2",children:[jsxs("div",{className:"fk:min-w-0",children:[jsx("div",{className:"fk:truncate fk:font-medium",children:t.filename}),jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:[t.status==="uploading"&&"Uploading to artifacts",t.status==="done"&&[qr(t),s].filter(Boolean).join(" \xB7 "),t.status==="error"&&(t.error?.message??"Failed to publish artifact")]})]}),a?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[jsx(d$1,{asChild:true,size:"sm",variant:"outline",children:jsx("a",{href:r,rel:"noreferrer",target:"_blank",children:"Preview"})}),jsx(d$1,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:n,children:[jsx(DownloadIcon,{className:"fk:size-3"}),"Download"]})}),t.url?jsx(d$1,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:t.url,rel:"noreferrer",target:"_blank",children:[jsx(LinkIcon,{className:"fk:size-3"}),"Permanent link"]})}):null]}):null]})]})]})}function Er({message:e}){let t=e.provider==="slack"?"Slack":"Microsoft Teams",a=e.provider==="slack"?jsx(MessageSquareIcon,{className:"fk:size-3.5"}):jsx(SendIcon,{className:"fk:size-3.5"});return jsx(ge,{error:e.error?.message,icon:a,loading:e.status==="loading",message:e.status==="error"?e.error?.message??`Failed to send result to ${e.channelName}`:`${e.status==="done"?"Sent":"Sending"} result to ${e.channelName}`,title:`${t} Delivery`})}function Lr({message:e}){let t=e.status==="success"?jsx(CheckCircle2Icon,{className:"fk:size-3.5 fk:text-green-700"}):e.status==="skipped"?jsx(CircleSlashIcon,{className:"fk:size-3.5"}):jsx(XCircleIcon,{className:"fk:size-3.5 fk:text-red-700"}),a=e.status==="success"?"Run completed":e.status==="skipped"?"Run skipped":"Run failed";return jsxs(A,{className:e.status==="failed"?"fk:border-red-700/40":"fk:border-green-700/40",children:[jsxs($,{children:[t,jsx("span",{children:a})]}),e.status==="failed"?jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e.summary}):null]})}function _r({api:e,message:t}){let{projectId:a}=fr(),r=useContext(mr),n=useContext(kr),s=useRef(void 0),{data:u,error:d,isValidating:f,mutate:h}=cr(a?g(a).approval(t.approvalId):null,f$1,{refreshInterval:x=>t.status!=="pending"||x?.approval?.status&&x.approval.status!=="pending"?0:dt}),k=u?.approval?.status,S=(k??t.status)==="pending";useEffect(()=>{h();},[t.status,h]),useEffect(()=>{let x=s.current;s.current=k,!(t.status!=="pending"||!k||k==="pending")&&x==="pending"&&r?.onApprovalDecided(u?.approval?.id??t.approvalId);},[k,u?.approval?.id,t.approvalId,t.status,r]);function g$1(x){x.status!=="pending"&&(s.current=x.status),h(),r?.onApprovalDecided(x.id);}let y;if(u?.approval)y=jsx(Fe,{api:e,approval:u.approval,chat:n,onDecided:g$1},u.approval.status);else if(d&&!f){let x=d instanceof Error&&d.message?d.message:"Request failed";y=jsxs("div",{className:"fk:space-y-2",children:[jsxs("p",{className:"fk:text-xs fk:text-destructive",children:["Failed to load proposal ",t.operationsSummary,": ",x]}),jsx(d$1,{size:"sm",variant:"outline",onClick:()=>{h();},children:"Retry"})]});}else y=jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(LoaderCircle,{className:"fk:size-3.5 fk:animate-spin"}),jsxs("span",{children:["Loading proposal ",t.operationsSummary,"..."]})]});return jsxs(A,{children:[jsxs($,{children:[n?jsx(ShieldIcon,{className:"fk:size-3.5"}):jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),n?"Approval request":"Mutation approval",S?jsx(LoaderCircle,{className:"fk:ml-1 fk:size-3.5 fk:animate-spin"}):null]}),jsx("div",{className:"fk:mt-2",children:y}),t.status==="error"&&t.error?jsx("p",{className:"fk:mt-2 fk:text-xs fk:text-destructive",children:t.error.message}):null]})}function zr({message:e}){let t=e.operationsSummary.replace(/^Call /,"");return jsx(ge,{error:e.status==="error"?e.error?.message??"The call failed.":void 0,icon:jsx(ShieldCheckIcon,{className:"fk:size-3.5"}),loading:false,message:e.status==="error"?`${t}: ${e.error?.message??"The call failed."}`:`${t} \xB7 Auto-approved by Jev`,title:"Plugin call"})}function jr({message:e}){let t=[typeof e.processedItems=="number"?`${e.processedItems.toString()} processed`:"",typeof e.changedItems=="number"?`${e.changedItems.toString()} changed`:"",typeof e.failedItems=="number"?`${e.failedItems.toString()} failed`:"",typeof e.totalItems=="number"?`${e.totalItems.toString()} total`:""].filter(Boolean);return jsx(ge,{error:e.error?.message,icon:jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),loading:e.status==="loading"||e.status==="running",message:e.status==="error"?e.error?.message??`Failed bulk ${e.operationName}`:`${e.status==="done"?"Completed":"Running"} ${e.operationName}${t.length>0?` (${t.join(", ")})`:""}`,title:"Bulk GraphQL action"})}function Or({part:e}){return jsxs(A,{className:"fk:bg-muted/30",children:[jsxs($,{children:[jsx(CheckCircle2Icon,{className:"fk:size-3.5"}),e.type.replace(/^data-/,"").replaceAll("-"," ")]}),jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"This run emitted a structured event that is not yet rendered by Studio."})]})}function Br(e){if(typeof e!="number")return "";if(e<1024)return `${e.toString()} B`;let t=e/1024;return t<1024?`${t.toFixed(1)} KB`:`${(t/1024).toFixed(1)} MB`}function qr(e){return e.kind==="pdf"?"PDF artifact":e.kind==="html"?"HTML artifact":"Artifact"}function Jr({pluginId:e}){let{pathname:t}=useLocation(),[a]=t.split("/ai/");return jsxs(A,{children:[jsxs("p",{className:"fk:text-sm",children:["Connect ",e," to use it in this conversation."]}),jsx(d$1,{asChild:true,size:"sm",variant:"outline",children:jsxs(Link,{to:`${a}/ai/plugins/${encodeURIComponent(e)}`,children:["Connect ",e]})})]})}export{_e as a,xt as b,Zr as c,Q as d,_t as e,fr as f,dt as g,mr as h,kr as i,Rn as j,xr as k,H as l,Sr as m,Sn as n,wn as o,Pn as p,Cn as q,Nr as r,Nn as s,_r as t};//# sourceMappingURL=chunk-NSYO57O3.js.map
5
+ //# sourceMappingURL=chunk-NSYO57O3.js.map