@flexkit/studio 0.2.5 → 0.2.7

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 (59) hide show
  1. package/dist/activity-nav-button-SJW67XZE.js +2 -0
  2. package/dist/{activity-nav-button-AESIPODJ.js.map → activity-nav-button-SJW67XZE.js.map} +1 -1
  3. package/dist/chat-page-6IXM63AU.js +4 -0
  4. package/dist/chat-page-6IXM63AU.js.map +1 -0
  5. package/dist/chunk-3GUFJ6KL.js +2 -0
  6. package/dist/chunk-3GUFJ6KL.js.map +1 -0
  7. package/dist/{chunk-26UJ2WUB.js → chunk-4JWGLBGC.js} +2 -2
  8. package/dist/{chunk-26UJ2WUB.js.map → chunk-4JWGLBGC.js.map} +1 -1
  9. package/dist/{chunk-EUGE3XWF.js → chunk-E7B5FQKW.js} +3 -3
  10. package/dist/{chunk-EUGE3XWF.js.map → chunk-E7B5FQKW.js.map} +1 -1
  11. package/dist/{chunk-XWC47CBM.js → chunk-F47EIXR2.js} +2 -2
  12. package/dist/{chunk-XWC47CBM.js.map → chunk-F47EIXR2.js.map} +1 -1
  13. package/dist/{chunk-NDM2RAQE.js → chunk-FEOT7BNI.js} +3 -3
  14. package/dist/{chunk-NDM2RAQE.js.map → chunk-FEOT7BNI.js.map} +1 -1
  15. package/dist/{chunk-Y7ZSQPKF.js → chunk-HFL6QZIF.js} +3 -3
  16. package/dist/{chunk-Y7ZSQPKF.js.map → chunk-HFL6QZIF.js.map} +1 -1
  17. package/dist/chunk-JK3IOLJZ.js +3 -0
  18. package/dist/chunk-JK3IOLJZ.js.map +1 -0
  19. package/dist/chunk-QNGDJNWD.js +8 -0
  20. package/dist/chunk-QNGDJNWD.js.map +1 -0
  21. package/dist/{chunk-UULO2DWJ.js → chunk-RGTJVPNH.js} +2 -2
  22. package/dist/{chunk-UULO2DWJ.js.map → chunk-RGTJVPNH.js.map} +1 -1
  23. package/dist/{chunk-PWQPA2QL.js → chunk-RKI5N2N4.js} +2 -2
  24. package/dist/{chunk-PWQPA2QL.js.map → chunk-RKI5N2N4.js.map} +1 -1
  25. package/dist/{chunk-UM74MG43.js → chunk-Y4Z3P43B.js} +2 -2
  26. package/dist/{chunk-UM74MG43.js.map → chunk-Y4Z3P43B.js.map} +1 -1
  27. package/dist/index.css +11 -0
  28. package/dist/index.d.ts +3 -1
  29. package/dist/index.js +1 -1
  30. package/dist/{list-WETJWRMH.js → list-GLA2XRW2.js} +2 -2
  31. package/dist/{list-WETJWRMH.js.map → list-GLA2XRW2.js.map} +1 -1
  32. package/dist/pages-PUJH4BYG.js +3 -0
  33. package/dist/pages-PUJH4BYG.js.map +1 -0
  34. package/dist/{plugin-pages-QLMZNHSK.js → plugin-pages-5TS6D4IH.js} +2 -2
  35. package/dist/{plugin-pages-QLMZNHSK.js.map → plugin-pages-5TS6D4IH.js.map} +1 -1
  36. package/dist/{root-R7URTGY7.js → root-6W74NN2R.js} +2 -2
  37. package/dist/{root-R7URTGY7.js.map → root-6W74NN2R.js.map} +1 -1
  38. package/dist/{root-L4SMLNEV.js → root-GMEW7KHI.js} +3 -3
  39. package/dist/{root-L4SMLNEV.js.map → root-GMEW7KHI.js.map} +1 -1
  40. package/dist/{root-QN7KVPCD.js → root-O3WHSEVY.js} +2 -2
  41. package/dist/{root-QN7KVPCD.js.map → root-O3WHSEVY.js.map} +1 -1
  42. package/dist/{root-N6PIMO2T.js → root-TNGHMQHM.js} +3 -3
  43. package/dist/{root-N6PIMO2T.js.map → root-TNGHMQHM.js.map} +1 -1
  44. package/dist/{search-3LHBSNDF.js → search-ZBGHTWVD.js} +2 -2
  45. package/dist/{search-3LHBSNDF.js.map → search-ZBGHTWVD.js.map} +1 -1
  46. package/dist/{skills-pages-ZN4LII2R.js → skills-pages-UXHYS3YQ.js} +2 -2
  47. package/dist/{skills-pages-ZN4LII2R.js.map → skills-pages-UXHYS3YQ.js.map} +1 -1
  48. package/package.json +3 -3
  49. package/dist/activity-nav-button-AESIPODJ.js +0 -2
  50. package/dist/chat-page-EXKQ2EYM.js +0 -4
  51. package/dist/chat-page-EXKQ2EYM.js.map +0 -1
  52. package/dist/chunk-CKNFYN3O.js +0 -3
  53. package/dist/chunk-CKNFYN3O.js.map +0 -1
  54. package/dist/chunk-LP2JI25S.js +0 -2
  55. package/dist/chunk-LP2JI25S.js.map +0 -1
  56. package/dist/chunk-NGO6CTAU.js +0 -8
  57. package/dist/chunk-NGO6CTAU.js.map +0 -1
  58. package/dist/pages-PIZB3YDN.js +0 -3
  59. package/dist/pages-PIZB3YDN.js.map +0 -1
@@ -0,0 +1,3 @@
1
+ import'./index.css';import {put}from'@vercel/blob/client';function I(s,e){let l=e.trim();return l?s.trim()?/\s$/.test(s)||/^[.,!?;:]/.test(l)?`${s}${l}`:`${s} ${l}`:s.length===0?l:`${s}${l}`:s}async function h(s){if(typeof window>"u")throw new Error("Dictation is only available in the browser.");let e=window.AudioContext??window.webkitAudioContext;if(!e)throw new Error("This browser cannot decode recorded audio.");let l=await s.arrayBuffer(),u=new e;try{let n=await u.decodeAudioData(l.slice(0)),i=C(n),t=y(i,n.sampleRate,24e3),o=$(t),r=t.length/24e3;if(r<.25)throw new Error("No speech was captured. Try again.");if(r>60)throw new Error(`Dictation is limited to ${String(60)} seconds.`);return {durationSeconds:r,pcm:new Blob([o],{type:"audio/pcm"})}}finally{await u.close();}}function C(s){let{length:e,numberOfChannels:l}=s;if(l===1)return s.getChannelData(0).slice();let u=new Float32Array(e);for(let n=0;n<e;n+=1){let i=0;for(let t=0;t<l;t+=1)i+=s.getChannelData(t)[n]??0;u[n]=i/l;}return u}function y(s,e,l){if(e===l)return s;let u=e/l,n=Math.max(1,Math.round(s.length/u)),i=new Float32Array(n);for(let t=0;t<n;t+=1){let o=t*u,r=Math.floor(o),a=Math.min(r+1,s.length-1),c=o-r,m=s[r]??0,g=s[a]??0;i[t]=m+(g-m)*c;}return i}function $(s){let e=new ArrayBuffer(s.length*2),l=new DataView(e);for(let u=0;u<s.length;u+=1){let n=Math.max(-1,Math.min(1,s[u]??0));l.setInt16(u*2,n<0?n*32768:n*32767,true);}return e}var d=class extends Error{code;status;constructor(e,l,u=null){super(l),this.name="AgentUploadError",this.code=u,this.status=e;}};function f(){if(typeof window>"u")return "flexkit.io";let{hostname:s}=window.location;return s==="localhost"||s==="127.0.0.1"||s==="flexkit.test"||s.endsWith(".flexkit.test")?"flexkit.test":"flexkit.io"}function T(){return `https://${f()}`}function _(s,e){return `https://${s}.api.${f()}/automations/webhook/${encodeURIComponent(e)}`}function w(s){let e=`/api/flexkit/${s}`,l=`${e}/automations`,u=`${e}/skills`,n=`${e}/agent/chats`;async function i(t,o){let r=await fetch(t,{credentials:"include",headers:{"Content-Type":"application/json",...o?.headers??{}},...o}),a=await r.json();if(!r.ok){let c=a&&typeof a=="object"&&"error"in a?String(a.error):"Request failed";throw new Error(c)}return a}return {connectPlugins:t=>i(`${e}/plugins/connect`,{method:"POST",body:JSON.stringify(t)}),pluginOAuthStatus:t=>i(`${e}/plugins/oauth-transactions/${encodeURIComponent(t)}`),updatePluginConnection:(t,o)=>i(`${e}/plugin-connections/${encodeURIComponent(t)}`,{method:"PATCH",body:JSON.stringify(o)}),disconnectPlugin:t=>i(`${e}/plugin-connections/${encodeURIComponent(t)}`,{method:"DELETE"}),installPlugin:t=>i(`${e}/plugins/${encodeURIComponent(t)}/installation`,{method:"PUT",body:JSON.stringify({})}),setPluginPolicy:(t,o)=>i(`${e}/plugins/${encodeURIComponent(t)}/policy`,{method:"PATCH",body:JSON.stringify(o)}),refreshPluginTools:t=>i(`${e}/plugin-connections/${encodeURIComponent(t)}/tools/refresh`,{method:"POST"}),cancelRun:async t=>i(`${l}/runs/${encodeURIComponent(t)}/cancel`,{method:"POST"}),createAgentChat:async t=>i(n,{body:JSON.stringify({modelId:t?.modelId??null}),method:"POST"}),deleteAgentChat:async t=>i(`${n}/${encodeURIComponent(t)}`,{method:"DELETE"}),getAgentChatStreamUrl:(t,o)=>`${n}/${encodeURIComponent(t)}/stream?workflowRunId=${encodeURIComponent(o)}`,renameAgentChat:async(t,o)=>i(`${n}/${encodeURIComponent(t)}`,{body:JSON.stringify({title:o}),method:"PATCH"}),sendAgentChatMessage:async(t,o)=>i(`${n}/${encodeURIComponent(t)}/messages`,{body:JSON.stringify(o),method:"POST"}),sendAgentChatFollowUp:async(t,o)=>i(`${n}/${encodeURIComponent(t)}/follow-ups`,{body:JSON.stringify(o),method:"POST"}),startAgentChat:async({attachments:t,content:o,modelId:r})=>i(n,{body:JSON.stringify({message:{attachments:t,content:o},modelId:r??null}),method:"POST"}),startQueuedAgentChatMessage:async(t,o)=>i(`${n}/${encodeURIComponent(t)}/follow-ups/${encodeURIComponent(o)}/start`,{method:"POST"}),stopAgentChat:async t=>i(`${n}/${encodeURIComponent(t)}/stop`,{method:"POST"}),stopAgentChatMonitor:async(t,o)=>i(`${n}/${encodeURIComponent(t)}/monitors/${encodeURIComponent(o)}/stop`,{method:"POST"}),transcribeAgentAudio:async(t,o)=>{let{durationSeconds:r,pcm:a}=await h(t),c=new FormData;c.append("file",a,"audio.pcm"),c.append("durationSeconds",String(r));let m=await fetch(`${e}/agent/transcribe`,{body:c,credentials:"include",method:"POST",signal:o}),g=await m.json();if(!m.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,o)=>{let r=await fetch(`${e}/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:o}),a=await r.json();if(!r.ok||!a.pathname||!a.token||!a.mediaType)throw new d(r.status,a.error?String(a.error):"The file could not be uploaded.",a.code??null);let c=await put(a.pathname,t,{abortSignal:o,access:"public",contentType:a.mediaType,token:a.token});return {filename:t.name,mediaType:a.mediaType,sizeBytes:t.size,url:c.url}},decideApproval:async(t,o)=>{let r=await fetch(`${l}/approvals/${encodeURIComponent(t)}/decide`,{body:JSON.stringify(o),credentials:"include",headers:{"Content-Type":"application/json"},method:"POST"}),a=await r.json();if(!r.ok&&typeof a.success!="boolean")throw new Error(a.error?String(a.error):"Request failed");return a},markActivityRead:async t=>i(`${e}/activity/read`,{body:JSON.stringify(t==="all"?{all:true}:{ids:t}),method:"POST"}),setActivityItemState:async(t,o)=>i(`${e}/activity/${encodeURIComponent(t)}`,{body:JSON.stringify({state:o}),method:"PATCH"}),createAutomation:async t=>i(l,{body:JSON.stringify(t),method:"POST"}),createSkill:async t=>i(u,{body:JSON.stringify(t),method:"POST"}),deleteAutomation:async t=>i(`${l}/${encodeURIComponent(t)}`,{method:"DELETE"}),deleteSkill:async t=>i(`${u}/${encodeURIComponent(t)}`,{method:"DELETE"}),getArtifactUrl:(t,o)=>{let r=o?.download?"?download=1":"";return `${l}/artifacts/${encodeURIComponent(t)}/content${r}`},getRunArtifacts:async t=>i(`${l}/runs/${encodeURIComponent(t)}/artifacts`).then(o=>o.artifacts),getStreamUrl:t=>`${l}/runs/${encodeURIComponent(t)}/stream`,getTranscriptUrl:t=>`${l}/runs/${encodeURIComponent(t)}/transcript`,listChannels:async(t,o)=>{let r=o?`${e}/plugin-connections/${encodeURIComponent(o)}/channels`:`${e}/plugins/${t}/channels`,a=await fetch(r,{credentials:"include",headers:{"Content-Type":"application/json"}}),c=await a.json();if(a.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 m=c.error?String(c.error):"Request failed";throw new Error(m)},runAutomation:async t=>i(`${l}/${encodeURIComponent(t)}/runs`,{method:"POST"}),updateAutomation:async(t,o)=>i(`${l}/${encodeURIComponent(t)}`,{body:JSON.stringify(o),method:"PATCH"}),updateSkill:async(t,o)=>i(`${u}/${encodeURIComponent(t)}`,{body:JSON.stringify(o),method:"PATCH"})}}var p=class extends Error{status;constructor(e,l="Request failed"){super(l),this.name="FetcherError",this.status=e;}},k=async s=>{let e=await fetch(s,{credentials:"include"});if(!e.ok)throw new p(e.status);return await e.json()};function U(s){let e=`/api/flexkit/${s}/automations`,l=`/api/flexkit/${s}/skills`,u=`/api/flexkit/${s}/agent/chats`;return {activity:(n={})=>{let{filter:i="all",limit:t=25,offset:o=0}=n,r=new URLSearchParams({filter:i,limit:t.toString(),offset:o.toString()});return `/api/flexkit/${s}/activity?${r.toString()}`},activityItem:n=>`/api/flexkit/${s}/activity/${encodeURIComponent(n)}`,activitySummary:n=>n?`/api/flexkit/${s}/activity/summary?since=${encodeURIComponent(n)}`:`/api/flexkit/${s}/activity/summary`,agentChat:n=>`${u}/${encodeURIComponent(n)}`,agentChatSearch:n=>`${u}/search?q=${encodeURIComponent(n)}`,agentChats:(n=0)=>`${u}?offset=${n.toString()}`,agentProfile:()=>`/api/flexkit/${s}/agent/profile`,approval:n=>`${e}/approvals/${encodeURIComponent(n)}`,approvals:(n={})=>{let{limit:i=25,offset:t=0,runId:o,status:r}=n,a=new URLSearchParams({limit:i.toString(),offset:t.toString()});return r&&a.set("status",r),o&&a.set("runId",o),`${e}/approvals?${a.toString()}`},approvalsCount:`${e}/approvals?limit=1`,automation:n=>`${e}/${encodeURIComponent(n)}`,automationRuns:(n,i=0,t=25)=>`${e}/${encodeURIComponent(n)}/runs?offset=${i.toString()}&limit=${t.toString()}`,automations:(n={})=>{let{enabled:i,limit:t=25,offset:o=0,search:r,visibility:a}=n,c=new URLSearchParams({limit:t.toString(),offset:o.toString()});i&&i.length>0&&c.set("enabled",i.map(g=>g?"true":"false").join(",")),a&&a.length>0&&c.set("visibility",a.join(","));let m=r?.trim();return m&&c.set("q",m),`${e}?${c.toString()}`},creditBalance:`${e}/credits`,entities:`${e}/entities`,run:n=>`${e}/runs/${encodeURIComponent(n)}`,runHistory:(n,i=0,t=25)=>`${e}/runs?scope=${n}&offset=${i.toString()}&limit=${t.toString()}`,skill:n=>`${l}/${encodeURIComponent(n)}`,skills:(n={})=>{let{limit:i=25,offset:t=0,search:o,visibility:r}=n,a=new URLSearchParams({limit:i.toString(),offset:t.toString()});r&&r.length>0&&a.set("visibility",r.join(","));let c=o?.trim();return c&&a.set("q",c),`${l}?${a.toString()}`},spaces:`/api/flexkit/${s}/spaces`,members:n=>n?`/api/flexkit/${s}/members?spaceId=${encodeURIComponent(n)}`:`/api/flexkit/${s}/members`,tools:n=>n?`${e}/${encodeURIComponent(n)}/tools`:`${e}/tools`}}
2
+ export{I as a,T as b,_ as c,w as d,p as e,k as f,U as g};//# sourceMappingURL=chunk-JK3IOLJZ.js.map
3
+ //# sourceMappingURL=chunk-JK3IOLJZ.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","attachments","content","modelId","messageId","monitorId","audio","signal","formData","file","tokenResponse","tokenData","put","approvalId","ids","itemId","state","automationId","skillId","artifactId","options","suffix","provider","connectionId","FetcherError","fetcher","paths","basePath","filter","limit","offset","params","since","query","enabled","search","visibility","value","trimmedSearch","scope","spaceId"],"mappings":"0DAIO,SAASA,CAAAA,CAAmBC,CAAAA,CAAkBC,CAAAA,CAA4B,CAC/E,IAAMC,CAAAA,CAAWD,CAAAA,CAAW,IAAA,EAAK,CAEjC,OAAKC,CAAAA,CAIAF,CAAAA,CAAS,IAAA,GAIV,KAAA,CAAM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P,CAAAA,CAAO,GAAA,CAAI,GAAA,CAAKO,CAAa,CAAA,CAGxB,CAAA,EAAGnD,CAAc,CAAA,CAAA,EAAI4C,CAAAA,CAAO,QAAA,EAAU,CAAA,CAC/C,CAAA,CACA,MAAA,CAAQ,gBAAgBjD,CAAS,CAAA,OAAA,CAAA,CACjC,OAAA,CAAU0D,CAAAA,EACRA,CAAAA,CACI,CAAA,aAAA,EAAgB1D,CAAS,CAAA,iBAAA,EAAoB,kBAAA,CAAmB0D,CAAO,CAAC,CAAA,CAAA,CACxE,CAAA,aAAA,EAAgB1D,CAAS,CAAA,QAAA,CAAA,CAC/B,KAAA,CAAQmC,CAAAA,EACNA,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-JK3IOLJZ.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 ActivityItem,\n ActivityItemState,\n AgentChat,\n AgentChatAttachment,\n AgentChatFollowUpResult,\n AgentChatMessage,\n AgentChatMonitor,\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 /** For a proposed automation: the approver's edited instructions and whether to run it once now. */\n automationEdits?: { instructions?: string; runOnce?: 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/** A new chat and its first turn, started by one request. */\nexport interface StartAgentChatResult {\n chat: AgentChat;\n turn: AgentChatTurn;\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 /**\n * Sends a message while the chat's turn is running. The platform decides\n * whether it steers that turn or waits as the next one; if the turn has\n * meanwhile ended, the message starts the next turn.\n */\n sendAgentChatFollowUp: (_chatId: string, _input: SendAgentChatMessageInput) => Promise<AgentChatFollowUpResult>;\n /** Creates a chat and sends its first message in one request. */\n startAgentChat: (_input: SendAgentChatMessageInput) => Promise<StartAgentChatResult>;\n /** Starts the next turn from a queued follow-up once the previous turn has ended. */\n startQueuedAgentChatMessage: (_chatId: string, _messageId: string) => Promise<AgentChatTurn>;\n stopAgentChat: (_chatId: string) => Promise<{ message: AgentChatMessage }>;\n stopAgentChatMonitor: (_chatId: string, _monitorId: string) => Promise<{ monitor: AgentChatMonitor }>;\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 /** Marks the caller's Activity items read; `'all'` marks every unread item. */\n markActivityRead: (_ids: string[] | 'all') => Promise<{ success: boolean }>;\n setActivityItemState: (\n _itemId: string,\n _state: Extract<ActivityItemState, 'unread' | 'read' | 'dismissed'>\n ) => Promise<{ item: ActivityItem }>;\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 sendAgentChatFollowUp: async (chatId, input) =>\n request<AgentChatFollowUpResult>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/follow-ups`, {\n body: JSON.stringify(input),\n method: 'POST',\n }),\n startAgentChat: async ({ attachments, content, modelId }) =>\n request<StartAgentChatResult>(agentChatsBasePath, {\n body: JSON.stringify({ message: { attachments, content }, modelId: modelId ?? null }),\n method: 'POST',\n }),\n startQueuedAgentChatMessage: async (chatId, messageId) =>\n request<AgentChatTurn>(\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/follow-ups/${encodeURIComponent(messageId)}/start`,\n { method: 'POST' }\n ),\n stopAgentChat: async (chatId) =>\n request<{ message: AgentChatMessage }>(`${agentChatsBasePath}/${encodeURIComponent(chatId)}/stop`, {\n method: 'POST',\n }),\n stopAgentChatMonitor: async (chatId, monitorId) =>\n request<{ monitor: AgentChatMonitor }>(\n `${agentChatsBasePath}/${encodeURIComponent(chatId)}/monitors/${encodeURIComponent(monitorId)}/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 markActivityRead: async (ids) =>\n request<{ success: boolean }>(`${projectBasePath}/activity/read`, {\n body: JSON.stringify(ids === 'all' ? { all: true } : { ids }),\n method: 'POST',\n }),\n setActivityItemState: async (itemId, state) =>\n request<{ item: ActivityItem }>(`${projectBasePath}/activity/${encodeURIComponent(itemId)}`, {\n body: JSON.stringify({ state }),\n method: 'PATCH',\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 activity: (_options?: { filter?: 'all' | 'needs_action'; limit?: number; offset?: number }) => string;\n activityItem: (_itemId: string) => string;\n /** Badge counts; with `since`, also the unread items created after it. */\n activitySummary: (_since?: string | null) => 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 /** Members for pickers; with a space id, only members who can see that space. */\n members: (_spaceId?: string | null) => 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 activity: (options = {}) => {\n const { filter = 'all', limit = 25, offset = 0 } = options;\n const params = new URLSearchParams({ filter, limit: limit.toString(), offset: offset.toString() });\n\n return `/api/flexkit/${projectId}/activity?${params.toString()}`;\n },\n activityItem: (itemId) => `/api/flexkit/${projectId}/activity/${encodeURIComponent(itemId)}`,\n activitySummary: (since) =>\n since\n ? `/api/flexkit/${projectId}/activity/summary?since=${encodeURIComponent(since)}`\n : `/api/flexkit/${projectId}/activity/summary`,\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 members: (spaceId) =>\n spaceId\n ? `/api/flexkit/${projectId}/members?spaceId=${encodeURIComponent(spaceId)}`\n : `/api/flexkit/${projectId}/members`,\n tools: (automationId) =>\n automationId ? `${basePath}/${encodeURIComponent(automationId)}/tools` : `${basePath}/tools`,\n };\n}\n"]}
@@ -0,0 +1,8 @@
1
+ import'./index.css';import {g,f as f$1,d}from'./chunk-JK3IOLJZ.js';import {f,d as d$1}from'./chunk-E7B5FQKW.js';import {na as na$1,Nb,Qb,ob,oa as oa$1,o,ka,ta as ta$1,_,$,ca as ca$1,da as da$1,aa as aa$1,ea as ea$1}from'./chunk-YCCFUGWJ.js';import {b,c as c$1,h as h$1,i,k,l,j as j$1,f as f$2}from'./chunk-32ZU4MLE.js';import {b as b$1,c,e}from'./chunk-USNXQOMJ.js';import {b as b$2}from'./chunk-6NRQMG26.js';import {lazy,createContext,useCallback,useState,useRef,useEffect,useMemo,useContext,useTransition,useId,Suspense}from'react';import Ra,{useSWRConfig}from'swr';import {formatDistance,format}from'date-fns';import {RadarIcon,BotIcon,XIcon,XCircleIcon,LoaderCircle,CheckIcon,CloudUploadIcon,FileTextIcon,DownloadIcon,LinkIcon,MessageSquareIcon,SendIcon,CheckCircle2Icon,CircleSlashIcon,ShieldIcon,DatabaseZapIcon,ShieldCheckIcon,TriangleAlertIcon,PlayIcon,ArrowRightIcon,FileIcon,CornerDownRightIcon,MoveRightIcon}from'lucide-react';import {useLocation,Link}from'react-router-dom';import {jsx,jsxs,Fragment}from'react/jsx-runtime';import {pipeJsonRender}from'@json-render/core';import {readUIMessageStream,parseJsonEventStream,uiMessageChunkSchema}from'ai';function Ge(){let{currentProjectId:e}=f(),{mutate:t}=useSWRConfig();return useCallback(n=>{if(!e)return;let a=g(e).approvalsCount;n?t(a,n,{revalidate:true}):t(a),t(g(e).activitySummary());},[e,t])}var zt=5e3,jt=150,be=new Set;function Lt(e){return async()=>{let t=await fetch(e,{credentials:"include",mode:"cors"});return t.status===404?"missing":t.ok?(await t.json()).approval??"missing":null}}function Ot(e,t,n=d$1){return !e||e.kind!=="schema"||e.status!=="approved"||e.error?false:e.executedAt?(n(t),false):true}function ie({approvalId:e,approvalUrl:t,fetchApproval:n,projectId:a,revalidate:r=d$1,sleep:s=l=>new Promise(d=>setTimeout(d,l))}){let l=`${a}:${e}`,d=n??(t?Lt(t):null);!d||be.has(l)||(be.add(l),(async()=>{try{for(let u=0;u<jt;u+=1){let c=null;try{c=await d();}catch{c=null;}if(c==="missing"||c!==null&&!Ot(c,a,r))return;await s(zt);}}finally{be.delete(l);}})());}var qt={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 Ft({status:e}){return jsx(b,{className:`fk:border-none fk:h-4.75 fk:text-[0.6875rem] fk:leading-4.5 fk:tracking-wide ${qt[e]}`,variant:"secondary",children:e})}function E(e){return e==null?"\u2014":typeof e=="object"?JSON.stringify(e):String(e)}function Ze({after:e,before:t}){let n=E(t),a=E(e);return n===a?jsx("span",{className:"fk:text-muted-foreground",children:n}):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:n}),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:a})]})}function Ht(e){let t=e.entity??"entities",n=e.affectedCount!==null?` \xB7 ${e.affectedCount.toString()} affected`:"";return e.kind==="create"?`Create ${t}${n}`:e.kind==="update"?`Update ${t}${n}`:e.kind==="delete"?`Delete ${t}${n}`:`Mutation on ${t}${n}`}function Vt({operation:e}){if(e.rows.length===0)return null;let t=(e.contextColumns??[]).filter(a=>a!=="_id");if(e.kind==="delete")return jsxs(_,{children:[jsx($,{children:jsxs(ca$1,{children:[jsx(da$1,{children:"Records to delete"}),t.map(a=>jsx(da$1,{children:a},a))]})}),jsx(aa$1,{children:e.rows.map((a,r)=>jsxs(ca$1,{className:"fk:bg-destructive/5",children:[jsx(ea$1,{className:"fk:font-mono fk:text-xs fk:text-destructive",children:a.id??E(a.before?._id)}),t.map(s=>jsx(ea$1,{className:"fk:text-xs fk:text-muted-foreground",children:E(a.before?.[s])},s))]},a.id??r.toString()))})]});let n=e.columns.filter(a=>a!=="_id"&&!t.includes(a));return jsxs(_,{children:[jsx($,{children:jsxs(ca$1,{children:[jsx(da$1,{children:"ID"}),t.map(a=>jsx(da$1,{children:a},a)),n.map(a=>jsx(da$1,{children:a},a))]})}),jsx(aa$1,{children:e.rows.map((a,r)=>jsxs(ca$1,{children:[jsx(ea$1,{className:"fk:font-mono fk:text-xs fk:text-muted-foreground",children:a.id??"\u2014"}),t.map(s=>jsx(ea$1,{className:"fk:max-w-72 fk:text-xs fk:text-muted-foreground",children:jsx("span",{className:"fk:line-clamp-3",children:E(a.before?.[s])})},s)),n.map(s=>jsx(ea$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:E(a.after?.[s])}):jsx(Ze,{after:a.after?.[s],before:a.before?.[s]})},s))]},a.id??r.toString()))})]})}function Gt({operations:e,plugin:t,chat:n,title:a}){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:a??(n?"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((r,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:r.query}),r.variables&&Object.keys(r.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(r.variables,null,2)}):null]},s.toString()))})]})}function et(e){if(e.kind!=="plugin")return null;let n=e.operations[0]?.query.split(`
2
+ `)[0]?.trim()?.split("/"),a=n?.at(-1),r=n?.[0];if(!a||!r||n?.length<2)return null;let s=a.replace(/([a-z])([A-Z])/g,"$1 $2").replace(/[_-]+/g," ").toLowerCase(),l=r.replace(/[_-]+/g," ").replace(/\b\w/g,f=>f.toUpperCase()),d=e.operations[0]?.query??"",u=/^Connection:\s*(Project|Personal)\s+—\s+(.+)$/m.exec(d);if(u?.[1]&&u[2])return {action:s,app:l,account:u[2].trim(),scope:u[1]==="Project"?"project":"personal"};let c=/^Connection:.*?([^\s<>]+@[^\s<>]+)\s*$/m.exec(d)?.[1];return {action:s,app:l,account:c}}function Wt(e){let t=et(e);return t?`${t.action.charAt(0).toUpperCase()}${t.action.slice(1)} in ${t.app}`:e.kind==="exec"?"Run a sandbox command":e.kind==="schema"?e.operationsSummary.replace(/^Schema: /,""):e.kind==="automation"&&e.preview?.automation?`Create the automation \u201C${e.preview.automation.name}\u201D`:e.kind==="automation"&&e.preview?.automationChange?`Change the automation \u201C${e.preview.automationChange.name}\u201D`:e.kind==="plugin"?"Use a connected app":e.operationsSummary}function Yt({operation:e}){if(e.rows.length===0)return null;let t=a=>a!=null&&a!==false,n=e.columns.filter(a=>e.rows.some(s=>t(s.before?.[a])||t(s.after?.[a]))?e.kind!=="update"?true:e.rows.some(s=>E(s.before?.[a])!==E(s.after?.[a])):false);return jsx("div",{className:"fk:overflow-x-auto fk:rounded-md fk:border fk:border-border fk:corner-squircle",children:jsxs(_,{className:"fk:text-xs",children:[jsx($,{children:jsxs(ca$1,{children:[jsx(da$1,{className:"fk:h-8",children:e.entity==="scopes"||e.entity==="spaces"||e.entity==="studio"?"Setting":"Attribute"}),n.map(a=>jsx(da$1,{className:"fk:h-8",children:a},a))]})}),jsx(aa$1,{children:e.rows.map((a,r)=>jsxs(ca$1,{children:[jsxs(ea$1,{className:"fk:py-1.5 fk:font-mono fk:text-[0.7rem]",children:[e.kind==="delete"?jsx("span",{className:"fk:line-through fk:text-destructive",children:a.id}):a.id,e.kind==="update"&&a.before===null?jsx(b,{className:"fk:ml-2",variant:"secondary",children:"new"}):null,e.kind==="update"&&a.after===null?jsx(b,{className:"fk:ml-2",variant:"destructive",children:"removed"}):null]}),n.map(s=>jsx(ea$1,{className:"fk:py-1.5",children:e.kind==="create"?jsx("span",{children:E(a.after?.[s])}):e.kind==="delete"?jsx("span",{className:"fk:text-muted-foreground",children:E(a.before?.[s])}):jsx(Ze,{after:a.after?.[s],before:a.before?.[s]})},s))]},a.id??r.toString()))})]})})}function Qt(e){let t=e.entity??"schema";return t==="scopes"||t==="spaces"||t==="studio"?`Change ${t==="studio"?"Studio settings":t}`:e.kind==="create"?`Add entity ${t} \xB7 ${e.rows.length.toString()} attribute${e.rows.length===1?"":"s"}`:e.kind==="delete"?`Remove entity ${t}`:`Change entity ${t}`}function Kt({preview:e}){let t=e.schema;return jsxs("div",{className:"fk:space-y-4",children:[t&&t.breakingChanges.length>0?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:[jsxs("div",{className:"fk:mb-1 fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-destructive",children:[jsx(TriangleAlertIcon,{className:"fk:size-4"}),"Breaking changes: existing data becomes inaccessible"]}),jsx("ul",{className:"fk:list-disc fk:pl-5 fk:text-destructive",children:t.breakingChanges.map(n=>jsx("li",{children:n},n))})]}):null,t&&t.warnings.length>0?jsx("div",{className:"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("ul",{className:"fk:list-disc fk:pl-5",children:t.warnings.map(n=>jsx("li",{children:n},n))})}):null,e.operations.map((n,a)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:`fk:text-sm fk:font-medium ${n.kind==="delete"?"fk:text-destructive":""}`,children:Qt(n)}),jsx(Yt,{operation:n})]},`${n.entity??""}-${a.toString()}`)),e.operations.length===0?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:"No visible entity changes. Review the operations below."}):null]})}function Zt(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 tt({api:e,approval:t,onDecided:n}){let[a,r]=useState(t),[s,l]=useState(t),[d,u]=useState(""),[c,f]=useTransition(),[k,w]=useState(false),[y,g$1]=useState(false),[p,A]=useState(""),N=Ge();t!==s&&(l(t),Zt(t,s)||a.id===t.id&&a.status!=="pending"&&t.status==="pending"||r(t));function C(b){r(b),N(),b.kind==="schema"&&b.status==="approved"&&ie({approvalId:b.id,approvalUrl:g(b.projectId).approval(b.id),projectId:b.projectId}),n?.(b);}function Y({approved:b,automationEdits:T,force:J=false,reason:P,remember:pe=false}){f(async()=>{u("");try{let R=await e.decideApproval(a.id,{approved:b,...T?{automationEdits:T}:{},force:J,reason:P,remember:pe});if(R.errorCode==="stale_preview"){g$1(!0),R.approval&&r(R.approval);return}if(g$1(!1),w(!1),R.approval?C(R.approval):R.success?C({...a,decidedAt:a.decidedAt??new Date().toISOString(),reason:P??a.reason,status:b?"approved":"rejected"}):R.errorCode==="already_decided"&&n?.(a),!R.success&&(R.errorCode!=="already_decided"||!R.approval)){let Q=Array.isArray(R.errorMessage)?R.errorMessage.join(", "):R.errorMessage;u(Q||"Failed to submit the decision.");}}catch(R){u(R instanceof Error?R.message:"Failed to submit the decision.");}});}return {approval:a,decide:Y,errorMessage:d,isDeciding:c,isPending:a.status==="pending",isRejectDialogOpen:k,isStale:y,rejectReason:p,setIsRejectDialogOpen:w,setRejectReason:A}}function at({allowRemember:e=false,askForRejectionReason:t,decide:n,isDeciding:a,isRejectDialogOpen:r,isStale:s,rejectReason:l$1,setIsRejectDialogOpen:d,setRejectReason:u,variant:c}){let f=c==="header",k$1=f?"fk:px-8 fk:min-w-32":void 0,w=f?"default":"sm",[y,g]=useState(false),p=useId();return jsxs(Fragment,{children:[jsxs("div",{className:"fk:flex fk:flex-nowrap fk:items-center fk:gap-2",children:[jsxs(b$2,{className:k$1,disabled:a,size:w,onClick:()=>n({approved:true,force:s,remember:e&&y}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),s?"Approve anyway":"Approve"]}),jsxs(b$2,{className:k$1,disabled:a,size:w,variant:"outline",onClick:()=>{t?(u(""),d(true)):n({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:p,children:[jsx(o,{checked:y,id:p,onCheckedChange:A=>g(A===true)}),"Always allow this tool for this automation"]}):null]}),t?jsx(c$1,{open:r,onOpenChange:d,children:jsxs(h$1,{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(ka,{placeholder:"Optional reason for the agent...",value:l$1,onChange:A=>u(A.target.value)}),jsxs(j$1,{children:[jsx(b$2,{disabled:a,size:"sm",variant:"outline",onClick:()=>d(false),children:"Cancel"}),jsxs(b$2,{disabled:a,size:"sm",variant:"destructive",onClick:()=>n({approved:false,reason:l$1.trim()||void 0}),children:[a?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(ArrowRightIcon,{className:"fk:size-4"}),"Reject proposal"]})]})]})}):null]})}var ea={always:"Every finished run",failures:"Failures only",never:"Never",when_flagged:"Results that need attention"};function ta(e){return e.visibility==="personal"?"Only you":e.visibility==="space"?`Space: ${e.spaceLabel??"unknown"}`:"Everyone in the project"}function aa({approval:e,instructions:t,isPending:n,proposal:a,onInstructionsChange:r}){let s=useId(),l=e.createdAutomation??null,d=[...a.replacesMonitor?[{label:"Replaces",value:`The monitor \u201C${a.replacesMonitor}\u201D, which stops once this exists`}]:[],{label:"Runs",value:a.triggers.join(`
3
+ `)},{label:"Visible to",value:ta(a)},{label:"Data changes",value:a.mutationPolicy==="auto_approve"?"Applied without review":"Wait for approval"},{label:"Notifications",value:`${ea[a.notifyRule]}${a.notifyCreator?", to you":""}${a.subscribers.length>0?` and ${a.subscribers.join(", ")}`:""}`},...a.plugins.length>0?[{label:"Plugins",value:a.plugins.map(u=>[u.account?`${u.name} as ${u.account}`:u.name,u.deliveryChannels.length>0?`posting to ${u.deliveryChannels.join(", ")}`:""].filter(Boolean).join(", ")).join(`
4
+ `)}]:[],...a.skills.length>0?[{label:"Skills",value:a.skills.join(", ")}]:[],...a.customTools.length>0?[{label:"Custom tools",value:a.customTools.join(", ")}]:[],{label:"Model",value:a.modelLabel}];return jsxs("div",{className:"fk:space-y-4",children:[a.mutationPolicy==="auto_approve"?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",role:"status",children:[jsx(TriangleAlertIcon,{className:"fk:mt-0.5 fk:size-4 fk:shrink-0 fk:text-amber-600"}),jsxs("span",{children:["Every run will change data",a.plugins.length>0?" and call these plugins":""," without asking anyone first. Reject and ask for review if that is not what you want."]})]}):null,jsx("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-1.5 fk:text-sm",children:d.map(u=>jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:u.label}),jsx("dd",{className:"fk:whitespace-pre-line",children:u.value})]},u.label))}),jsxs("div",{className:"fk:space-y-1.5",children:[jsx("label",{className:"fk:text-sm fk:font-medium",htmlFor:s,children:"Instructions"}),n&&r?jsxs(Fragment,{children:[jsx("p",{className:"fk:text-xs fk:text-muted-foreground",children:"The automation never sees this chat, so these instructions are all it has to go on. Edit them before creating it."}),jsx(ka,{className:"fk:min-h-40 fk:text-sm",id:s,value:t,onChange:u=>r(u.target.value)})]}):jsx("p",{className:"fk:whitespace-pre-wrap fk:rounded-md fk:border fk:p-3 fk:text-sm fk:corner-squircle",id:s,children:t})]}),l?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[jsx(b$2,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${l.automationId}`,children:"Open the automation"})}),l.runId?jsx(b$2,{asChild:true,size:"sm",variant:"ghost",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${l.automationId}/runs/${l.runId}`,children:"View its first run"})}):null]}):null]})}function na({approval:e,change:t}){let n=t.changes.filter(r=>r.field!=="instructions"),a=t.changes.find(r=>r.field==="instructions");return jsxs("div",{className:"fk:space-y-4",children:[n.length>0?jsx("dl",{className:"fk:grid fk:grid-cols-[max-content_1fr] fk:gap-x-4 fk:gap-y-2 fk:text-sm",children:n.map(r=>jsxs("div",{className:"fk:contents",children:[jsx("dt",{className:"fk:text-muted-foreground",children:r.label}),jsxs("dd",{className:"fk:space-y-0.5",children:[jsx("div",{className:"fk:whitespace-pre-line fk:text-muted-foreground fk:line-through",children:r.before}),jsx("div",{className:"fk:whitespace-pre-line",children:r.after})]})]},r.field))}):null,a?jsx("div",{className:"fk:grid fk:gap-3 fk:md:grid-cols-2",children:[{label:"Current instructions",muted:true,text:a.before},{label:"New instructions",muted:false,text:a.after}].map(r=>jsxs("div",{className:"fk:min-w-0 fk:space-y-1.5",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:r.label}),jsx("p",{className:`fk:whitespace-pre-wrap fk:rounded-md fk:border fk:p-3 fk:text-sm fk:corner-squircle${r.muted?" fk:text-muted-foreground":""}`,children:r.text})]},r.label))}):null,jsx(b$2,{asChild:true,size:"sm",variant:"outline",children:jsx(Link,{to:`/${e.projectId}/ai/automations/${t.automationId}`,children:"Open the automation"})})]})}function nt({decide:e,instructions:t,isDeciding:n,proposal:a}){let r=t.trim(),s=r!==a.instructions.trim()?{instructions:r}:{};return jsxs("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:[jsxs(b$2,{disabled:n||r.length===0,size:"sm",variant:a.runOnceAfterCreate?"outline":"default",onClick:()=>e({approved:true,automationEdits:{...s,runOnce:false}}),children:[n?jsx(LoaderCircle,{className:"fk:size-4 fk:animate-spin"}):jsx(CheckIcon,{className:"fk:size-4"}),"Create"]}),jsxs(b$2,{disabled:n||r.length===0,size:"sm",variant:a.runOnceAfterCreate?"default":"outline",onClick:()=>e({approved:true,automationEdits:{...s,runOnce:true}}),children:[jsx(PlayIcon,{className:"fk:size-4"}),"Create and run once now"]}),jsxs(b$2,{disabled:n,size:"sm",variant:"outline",onClick:()=>e({approved:false}),children:[jsx(XIcon,{className:"fk:size-4"}),"Reject"]})]})}function rt({approval:e,automationInstructions:t,chat:n,errorMessage:a,isPending:r,isStale:s,onAutomationInstructionsChange:l}){let{preview:d}=e,u=n?et(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(Ft,{status:e.status}),e.kind==="schema"?jsx(b,{variant:"outline",children:"Schema change"}):null,e.kind==="automation"?jsx(b,{variant:"outline",children:d?.automationChange?"Automation change":"New automation"}):null,jsx("span",{className:"fk:text-sm fk:font-medium",children:n?Wt(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")}`:""]}),s?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,e.kind==="automation"&&d?.automation?jsx(aa,{approval:e,instructions:t??d.automation.instructions,isPending:r,proposal:d.automation,onInstructionsChange:l}):e.kind==="automation"&&d?.automationChange?jsx(na,{approval:e,change:d.automationChange}):e.kind==="schema"&&d?jsx(Kt,{preview:d}):d&&d.operations.length>0?jsx("div",{className:"fk:space-y-4",children:d.operations.map((c,f)=>jsxs("div",{className:"fk:space-y-2",children:[jsx("div",{className:"fk:text-sm fk:font-medium",children:Ht(c)}),c.kind==="delete"&&c.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:[c.affectedCount.toString()," record",c.affectedCount===1?"":"s"," will be permanently deleted."]}):null,jsx(Vt,{operation:c}),c.truncated?jsxs("div",{className:"fk:text-xs fk:text-muted-foreground",children:["Preview limited to the first ",c.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:n?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."}),e.kind==="automation"?null:jsx(Gt,{chat:n,operations:e.operations,plugin:e.kind==="plugin"||e.kind==="exec",title:e.kind==="exec"?"Command and options":e.kind==="schema"?"Operations":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 st({api:e,approval:t,chat:n,onDecided:a}){let{approval:r,decide:s,errorMessage:l,isDeciding:d,isPending:u,isRejectDialogOpen:c,isStale:f,rejectReason:k,setIsRejectDialogOpen:w,setRejectReason:y}=tt({api:e,approval:t,onDecided:a}),g=r.kind==="automation"?r.preview?.automation??null:null,[p,A]=useState(g?.instructions??"");return jsxs(Fragment,{children:[jsx(rt,{approval:r,automationInstructions:g?p:void 0,chat:n,errorMessage:l,isPending:u,isStale:f,onAutomationInstructionsChange:g?A:void 0}),u&&g?jsx("div",{className:"fk:mt-4",children:jsx(nt,{decide:s,instructions:p,isDeciding:d,proposal:g})}):u?jsx("div",{className:"fk:mt-4",children:jsx(at,{allowRemember:!n&&r.kind==="plugin"&&!!r.automationId,askForRejectionReason:!n,decide:s,isDeciding:d,isRejectDialogOpen:c,isStale:f,rejectReason:k,setIsRejectDialogOpen:w,setRejectReason:y,variant:"inline"})}):null]})}function jn({api:e,approval:t,onClose:n,onDecided:a}){let{approval:r,decide:s,errorMessage:l,isDeciding:d,isPending:u,isRejectDialogOpen:c,isStale:f,rejectReason:k,setIsRejectDialogOpen:w,setRejectReason:y}=tt({api:e,approval:t,onDecided:a}),g=r.kind==="automation"?r.preview?.automation??null:null,[p,A]=useState(g?.instructions??"");return jsx(na$1,{actions:u&&g?jsx(nt,{decide:s,instructions:p,isDeciding:d,proposal:g}):u?jsx(at,{allowRemember:r.kind==="plugin"&&!!r.automationId,askForRejectionReason:true,decide:s,isDeciding:d,isRejectDialogOpen:c,isStale:f,rejectReason:k,setIsRejectDialogOpen:w,setRejectReason:y,variant:"header"}):null,depth:0,isFocused:true,onClose:n,title:g?"Automation proposal":r.preview?.automationChange?"Automation change":"Mutation proposal",children:jsx(rt,{approval:r,automationInstructions:g?p:void 0,chat:false,errorMessage:l,isPending:u,isStale:f,onAutomationInstructionsChange:g?A:void 0})})}var ra="Approved by Flexkit Jev policy",sa="Approved by automation tool allow rule",oa=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 K(e){return oa.has(e)}function h(e){return e.data}function Ne(e){return !e.decidedBy&&!!(e.reason?.startsWith(ra)||e.reason?.startsWith(sa))}function q(e,t=72){let n=e.trim();if(n.length<=t)return n;let a=n.slice(0,t),r=a.lastIndexOf(" ");return `${(r>=Math.floor(t*.6)?a.slice(0,r):a).trimEnd()}\u2026`}function ia(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 la(e){let t=e.lastIndexOf(`
5
+ `),n=-1,a=/[.!?](?=\s)/g,r;for(;(r=a.exec(e))!==null;)n=r.index;let s=Math.max(t,n);return s<0?"":e.slice(0,s+1)}function ua(e,t){let a=(la(e)).split(/\r?\n/).map(u=>u.trim()).filter(Boolean),r=a[a.length-1];if(!r)return null;let l=/^\*\*(.+?)\*\*:?$/.exec(r)?.[1]??/^#{1,6}\s+(.+)$/.exec(r)?.[1]??/^(.+?[.!?])(?:\s|$)/.exec(r)?.[1]??r,d=ia(l);return !d||/^reasoning$/i.test(d)?null:q(d)}function ot(e){return e.replace(/[_-]+/g," ").trim()}function da(e){if(e.type==="data-load-skill"){let t=h(e);return t.status!=="loading"?null:t.skillName?q(`Loading skill "${t.skillName}"`):"Loading skill"}if(e.type==="data-search-schema")return h(e).status==="loading"?"Searching schema":null;if(e.type==="data-validate-graphql")return h(e).status==="loading"?"Validating GraphQL query":null;if(e.type==="data-execute-graphql"){let t=h(e);return t.status!=="loading"?null:t.operationType==="mutation"?"Executing GraphQL mutation":"Executing GraphQL query"}if(e.type==="data-update-memory")return h(e).status==="loading"?"Updating memory":null;if(e.type==="data-web-search"){let t=h(e);return t.status!=="loading"?null:t.query?q(`Searching the web for "${t.query}"`):"Searching the web"}if(e.type==="data-run-command"){let t=h(e);return ["executing","running","waiting"].includes(t.status)?q(`Running ${[t.command,...t.args].join(" ")}`):null}if(e.type==="data-create-sandbox")return h(e).status==="loading"?"Creating sandbox":null;if(e.type==="data-plugin-call"){let t=h(e);return t.status!=="loading"?null:q(`Calling ${t.pluginId}: ${ot(t.tool)}`)}if(e.type==="data-subtask"){let t=h(e);return t.status==="running"?q(`Running subtask: ${t.title}`):null}return null}var ca=new Set(["data-execute-graphql","data-search-schema","data-validate-graphql"]);function ue(e){if(!K(e.type)||e.type==="data-plan"||ca.has(e.type))return null;let t=h(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??"")}: ${ot(String(t.tool??""))}`;default:return "The tool call failed"}}function de(e){if(e.type==="step-start"||e.type==="reasoning")return true;if(K(e.type))return ue(e)===null;if(e.type==="data-mutation-approval"){let t=h(e);return Ne(t)&&t.status!=="error"}return false}function le(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let n=e.parts[t];if(n?.type!=="data-plan")continue;let a=h(n),r=a.steps.findIndex(s=>s.status==="in_progress");return r<0?null:q(`Step ${(r+1).toString()} of ${a.steps.length.toString()}: ${a.steps[r].step}`)}return null}function fa(e){if(!e)return null;for(let t=e.parts.length-1;t>=0;t--){let n=e.parts[t];if(!(!n||n.type==="step-start"))return n.type==="reasoning"?n.state==="streaming"?ua(n.text)??le(e):le(e):n.type==="data-mutation-approval"?h(n).status==="pending"?"Awaiting approval":le(e):n.type==="text"?null:da(n)??le(e)}return null}function Ce(e){return e?e.parts.some(t=>t.type!=="data-mutation-approval"?false:h(t).status==="pending"):false}function Te(e,t={}){let n=false,a=[];for(let r of e.parts){if(r.type!=="data-mutation-approval"){a.push(r);continue}let s=h(r);if(s.status!=="pending"){a.push(r);continue}n=true;let l=t[s.approvalId];l&&l!=="pending"&&a.push({...r,data:{...s,status:l}});}return n?{...e,parts:a}:e}function it(e,t){if(!e)return [];let n=[],a=t?.pendingOnly??false;for(let r of e.parts){if(r.type!=="data-mutation-approval")continue;let s=h(r);a&&s.status!=="pending"||n.push(s.approvalId);}return n}function pa(e){return it(e,{pendingOnly:true})}var lt=20*1024*1024,Hn=10,dt=new Set(["css","csv","gif","gql","graphql","htm","html","jpeg","jpg","js","json","jsx","log","markdown","md","mjs","ndjson","pdf","png","py","sql","ts","tsv","tsx","txt","webp","xml","yaml","yml"]),ct=new Set(["application/pdf","image/gif","image/jpeg","image/png","image/webp"]),Vn=[...[...dt].map(e=>`.${e}`),...ct].join(",");function ft(e){let t=e.lastIndexOf(".");return t<=0?"":e.slice(t+1).toLowerCase()}function va(e){let t=ft(e.name);return (t?dt.has(t):ct.has(e.type))?e.size===0?`"${e.name}" is empty.`:e.size>lt?`"${e.name}" exceeds the ${String(Math.round(lt/(1024*1024)))} MB limit.`:null:`"${e.name}" is not supported. Attach images, PDFs, or text files.`}async function ya(e){let n=await(await fetch(e.url)).blob();return new File([n],e.filename??"file",{type:e.mediaType||n.type})}function Gn(e,t){let{attachments:n}=Nb(),a=useRef({}),[,r]=useState(0),s=useCallback(()=>r(c=>c+1),[]),l=useRef(n.remove);l.current=n.remove;let d=useRef(t);d.current=t,useEffect(()=>{let c=new Set(n.files.map(f=>f.id));for(let[f,k]of Object.entries(a.current))c.has(f)||(k.controller.abort(),delete a.current[f]);for(let f of n.files){if(a.current[f.id])continue;let k=new AbortController,w={controller:k,status:"uploading"};a.current[f.id]=w,(async()=>{try{let y=await ya(f),g=va(y);if(g)throw new Error(g);let p=await e.uploadAgentChatAttachment(y,k.signal);if(k.signal.aborted)return;w.attachment=p,w.status="done";}catch(y){if(k.signal.aborted)return;w.status="error",delete a.current[f.id],l.current(f.id),d.current(y instanceof Error?y.message:"The file could not be uploaded.");}finally{s();}})();}s();},[e,n.files,s]);let u=Object.values(a.current).some(c=>c.status==="uploading");return {getUploaded:c=>c.map(f=>a.current[f]?.attachment).filter(f=>!!f),isUploading:u,isUploadingFile:c=>a.current[c]?.status==="uploading"}}function De(e){return !!e?.startsWith("image/")}function pt({image:e,onClose:t}){return jsx(c$1,{onOpenChange:n=>n?void 0:t(),open:e!==null,children:jsxs(h$1,{className:"fk:h-dvh fk:w-dvw fk:max-w-none fk:sm:max-w-none fk:rounded-none fk:border-0 fk:bg-black/90 fk:p-4 fk:shadow-none fk:flex fk:items-center fk:justify-center fk:corner-squircle",showCloseButton:false,children:[jsx(k,{className:"fk:sr-only",children:e?.filename??"Image preview"}),e?jsx("img",{alt:e.filename,className:"fk:block fk:h-auto fk:w-auto fk:max-h-full fk:max-w-full fk:object-contain",src:e.url}):null,jsx(f$2,{"aria-label":"Close preview",className:"fk:absolute fk:top-4 fk:right-4 fk:flex fk:size-9 fk:items-center fk:justify-center fk:rounded-full fk:bg-white/10 fk:text-white fk:transition-colors fk:hover:bg-white/20 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-white/60 fk:corner-squircle",children:jsx(XIcon,{className:"fk:size-5"})})]})})}function mt({label:e,onRemove:t}){return jsx("button",{"aria-label":e,className:"fk:absolute fk:top-1 fk:right-1 fk:z-10 fk:flex fk:size-5 fk:items-center fk:justify-center fk:rounded-full fk:border fk:border-border fk:bg-background fk:text-foreground fk:shadow-sm fk:transition-colors fk:hover:bg-accent fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring fk:corner-squircle",onClick:n=>{n.stopPropagation(),t();},type:"button",children:jsx(XIcon,{className:"fk:size-3"})})}function kt({image:e,isUploading:t=false,onOpen:n,onRemove:a,sizeClassName:r}){return jsxs("div",{className:`fk:relative fk:shrink-0 fk:overflow-hidden fk:rounded-xl fk:bg-muted ${r} fk:corner-squircle`,children:[jsx("button",{"aria-label":`Preview ${e.filename}`,className:"fk:block fk:size-full fk:cursor-zoom-in fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring",onClick:n,type:"button",children:jsx("img",{alt:e.filename,className:"fk:size-full fk:object-cover",src:e.url})}),t?jsx("div",{className:"fk:pointer-events-none fk:absolute fk:inset-0 fk:flex fk:items-center fk:justify-center fk:bg-background/60",children:jsx(ta$1,{className:"fk:size-4"})}):null,a?jsx(mt,{label:`Remove ${e.filename}`,onRemove:a}):null]})}function ha(e,t){let n=ft(e);if(n)return n.toUpperCase();let a=t?.split("/")[1]?.split("+")[0];return a?a.toUpperCase():"FILE"}function gt({file:e,href:t,isUploading:n=false,onRemove:a}){let r=jsxs(Fragment,{children:[jsx("div",{className:"fk:flex fk:size-10 fk:shrink-0 fk:items-center fk:justify-center fk:rounded-lg fk:bg-muted fk:text-muted-foreground fk:corner-squircle",children:n?jsx(ta$1,{className:"fk:size-4"}):jsx(FileIcon,{className:"fk:size-5"})}),jsxs("div",{className:"fk:min-w-0 fk:pr-4 fk:text-left",children:[jsx("div",{className:"fk:truncate fk:text-sm fk:font-medium fk:text-foreground",children:e.filename}),jsx("div",{className:"fk:truncate fk:text-xs fk:text-muted-foreground",children:ha(e.filename,e.mediaType)})]})]}),s="fk:flex fk:h-14 fk:max-w-64 fk:items-center fk:gap-2.5 fk:rounded-xl fk:border fk:border-border fk:bg-background fk:px-2 fk:corner-squircle";return jsxs("div",{className:"fk:relative fk:shrink-0",children:[t?jsx("a",{className:`${s} fk:transition-colors fk:hover:bg-accent/50 fk:focus-visible:outline-none fk:focus-visible:ring-2 fk:focus-visible:ring-ring`,href:t,rel:"noreferrer",target:"_blank",children:r}):jsx("div",{className:s,children:r}),a?jsx(mt,{label:`Remove ${e.filename}`,onRemove:a}):null]})}function Wn({uploads:e}){let t=Qb(),[n,a]=useState(null);return t.files.length===0?null:jsxs(Fragment,{children:[jsx("div",{className:"fk:flex fk:flex-wrap fk:items-center fk:gap-2",children:t.files.map(r=>{if(De(r.mediaType)&&r.url){let s={filename:r.filename??"Image",url:r.url};return jsx(kt,{image:s,isUploading:e.isUploadingFile(r.id),onOpen:()=>a(s),onRemove:()=>t.remove(r.id),sizeClassName:"fk:size-14"},r.id)}return jsx(gt,{file:{filename:r.filename??"file",mediaType:r.mediaType},isUploading:e.isUploadingFile(r.id),onRemove:()=>t.remove(r.id)},r.id)})}),jsx(pt,{image:n,onClose:()=>a(null)})]})}function Yn(e){return Array.isArray(e)?e.filter(t=>t.type==="file"&&typeof t.url=="string").map(t=>({filename:t.filename??"file",mediaType:t.mediaType??"application/octet-stream",sizeBytes:t.sizeBytes??0,url:t.url??""})):[]}function vt({attachments:e}){let[t,n]=useState(null);if(e.length===0)return null;let a=e.filter(s=>De(s.mediaType)),r=e.filter(s=>!De(s.mediaType));return jsxs("div",{className:"fk:flex fk:flex-col fk:items-end fk:gap-2",children:[a.length>0?jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-end fk:gap-2",children:a.map(s=>jsx(kt,{image:s,onOpen:()=>n(s),sizeClassName:"fk:size-24"},s.url))}):null,jsx(pt,{image:t,onClose:()=>n(null)}),r.length>0?jsx("div",{className:"fk:flex fk:flex-wrap fk:justify-end fk:gap-2",children:r.map(s=>jsx(gt,{file:s,href:s.url},s.url))}):null]})}function sr(e){let t=(Array.isArray(e.parts)?e.parts:[]).find(n=>n.type==="data-monitor-event");return t&&typeof t.data=="object"&&t.data!==null?t.data:null}function bt({data:e,error:t}){let n=e.total-e.events.length;return jsxs("div",{className:"fk:mr-auto fk:w-full fk:max-w-[85%] fk:space-y-1.5 fk:rounded-lg fk:border fk:border-border fk:bg-muted/40 fk:px-3.5 fk:py-2.5 fk:text-sm fk:corner-squircle",children:[jsxs("div",{className:"fk:flex fk:items-center fk:gap-2 fk:text-xs fk:text-muted-foreground",children:[jsx(RadarIcon,{className:"fk:size-3.5 fk:shrink-0"}),jsxs("span",{className:"fk:truncate",children:["Monitor \xB7 ",e.description]})]}),jsxs("ul",{className:"fk:space-y-0.5",children:[e.events.map(a=>jsx("li",{children:a.summary},a.id)),n>0?jsxs("li",{className:"fk:text-muted-foreground",children:["\u2026and ",n.toString()," more"]}):null]}),t?jsx("p",{className:"fk:text-xs fk:text-destructive",children:t}):null]})}function or({api:e$1,chatId:t,onTurnIntoAutomation:n,projectId:a,sending:r=false}){let{data:s,mutate:l}=Ra(g(a).agentChat(t),f$1,{revalidateOnMount:false}),[d,u]=useState(null),c$1=s?.monitors??[];if(c$1.length===0)return null;async function f(k){u(k.id);try{await e$1.stopAgentChatMonitor(t,k.id),await l();}catch{oa$1.error("Unable to stop the monitor.");}finally{u(null);}}return jsx("div",{className:"fk:mx-auto fk:mb-2 fk:flex fk:max-w-4xl fk:flex-wrap fk:gap-2",children:c$1.map(k=>jsxs("div",{className:"fk:flex fk:max-w-full fk:items-center fk:gap-2 fk:rounded-full fk:border fk:border-border fk:py-1 fk:pl-3 fk:pr-1 fk:text-xs fk:text-muted-foreground",children:[jsx(RadarIcon,{className:"fk:size-3.5 fk:shrink-0 fk:animate-pulse"}),jsxs("span",{className:"fk:truncate",children:["Watching: ",k.description," \xB7 expires ",formatDistance(new Date(k.expiresAt),new Date,{addSuffix:true})]}),n&&k.sourceType&&k.sourceType!=="job"?jsxs(b$1,{children:[jsx(c,{asChild:true,children:jsx(b$2,{"aria-label":`Turn ${k.description} into an automation`,className:"fk:size-6 fk:rounded-full",disabled:r,size:"icon",variant:"ghost",onClick:()=>n(k),children:jsx(BotIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Turn into automation"})]}):null,jsxs(b$1,{children:[jsx(c,{asChild:true,children:jsx(b$2,{"aria-label":`Stop watching ${k.description}`,className:"fk:size-6 fk:rounded-full",disabled:d===k.id,size:"icon",variant:"ghost",onClick:()=>{f(k);},children:jsx(XIcon,{className:"fk:size-3.5"})})}),jsx(e,{children:"Stop watching"})]})]},k.id))})}var G=class extends Error{},ce=class extends Error{};function xt({url:e,signal:t,state:n,onState:a,wake:r,fetchStream:s=fetch,retryMs:l=2e3}){let d=0,u=0,c=new TransformStream,f=c.writable.getWriter(),k=new AbortController;f.closed.catch(p=>k.abort(p));let w=()=>{k.abort(t.reason),f.abort(t.reason).catch(()=>{});};t.addEventListener("abort",w,{once:true}),t.aborted&&w();let y=()=>new Promise(p=>{let A=()=>{clearTimeout(N),k.signal.removeEventListener("abort",A),r?.removeEventListener("wake",A),p();},N=setTimeout(A,l);k.signal.addEventListener("abort",A,{once:true}),r?.addEventListener("wake",A,{once:true}),k.signal.aborted&&A();});async function g(){try{for(await f.write({type:"start"});!k.signal.aborted;){try{let p=await s(`${e}${e.includes("?")?"&":"?"}wire=2&startIndex=${d}`,{credentials:"include",signal:k.signal});if(p.status===404){a("unavailable"),await f.close();return}if(p.status===401||p.status===403)throw new ce("Stream access denied");if(!p.ok||!p.body)throw new Error(`Stream request failed: ${p.status}`);if(p.headers.get("x-flexkit-stream-version")!=="2")throw await p.body.cancel(),new G("Backend uses legacy replay");a("streaming");let A=p.body.pipeThrough(new TextDecoderStream).getReader(),N="",C=!1;try{for(;!k.signal.aborted;){let{value:Y,done:b}=await A.read();if(b)break;N+=Y;let T;for(;(T=N.indexOf(`
6
+ `))>=0;){let J=N.slice(0,T);if(N=N.slice(T+1),!J)continue;let P=JSON.parse(J);if(!Number.isSafeInteger(P.index)||P.index<0)throw new Error("Invalid replay cursor");if(!(P.index<d)){if(P.index!==d)throw new Error("Replay cursor gap");P.chunk&&await f.write(P.chunk),d=P.index+1,u=0,P.chunk?.type==="finish"&&P.chunk.messageMetadata?.flexkitTerminal&&(C=!0);}}if(N.length>2e6)throw new Error("Oversized replay frame");if(C)break}}finally{await A.cancel().catch(()=>{}),A.releaseLock();}if(C||n().terminal&&!N){await f.write({type:"finish"}),await f.close(),a("finished");return}}catch(p){if(k.signal.aborted||p instanceof G||p instanceof ce||++u>=5)throw p}do a(n().paused?"paused":"streaming"),await y();while(!k.signal.aborted&&n().paused&&!n().terminal)}}catch(p){await f.abort(p).catch(()=>{});}finally{t.removeEventListener("abort",w),f.releaseLock();}}return g(),pipeJsonRender(c.readable)}var Fa=lazy(()=>import('./spec-renderer-EX7SCFWH.js').then(e=>({default:e.RunSpecPart})));function Ha(e){return jsx(Suspense,{fallback:null,children:jsx(Fa,{...e})})}function Va(){let{currentProjectId:e}=f();return {api:useMemo(()=>e?d(e):null,[e]),projectId:e}}var At=5,Dt=2e3,Mt=120,Ie="data-spec",Ga=createContext(null),Wa=createContext(false);function Ya(e){return new Promise(t=>window.setTimeout(t,e))}function Qa(e){return e instanceof Error?e.name==="AbortError"||e.message.toLowerCase().includes("aborted"):false}function Ka(e){return e.some(t=>!de(t))}function Za(e){let t=new Set;for(let n of e)for(let a of n.parts)a.type==="data-user-message"&&a.id&&t.add(a.id);return t}function en(e){let t=Za(e),n=[];for(let a of e){if(a.role==="user"){t.has(a.id)||n.push(a);continue}if(a.role!=="assistant"){n.push(a);continue}let r=[],s=0,l=()=>{Ka(r)&&n.push({...a,id:`${a.id}-${s.toString()}`,parts:r}),s++,r=[];};for(let d of a.parts){if(d.type==="data-user-message"){let u=h(d);l(),n.push({id:d.id??crypto.randomUUID(),parts:u.parts,role:"user"});continue}r.push(d);}l();}return n}function Cr(e){return useMemo(()=>en(e),[e])}function W(e){return e==="success"||e==="failed"||e==="cancelled"||e==="skipped"}function It({latestMessage:e,recordStatus:t,suppressApprovalPause:n}){return W(t)||n||t==="running"?false:t==="awaiting_approval"?true:Ce(e)}function Tr(e,t){let[n,a]=useState(false),r=tn(n?e:"",t),[s,l]=useState(),[d,u]=useState("streaming"),c=useRef(t);c.current=t;let f=useRef(null);f.current||(f.current=new EventTarget);let k=f.current,w=t?.resumeToken;return useEffect(()=>{k.dispatchEvent(new Event("wake"));},[w,k]),useEffect(()=>{if(a(false),l(void 0),!e){u("unavailable");return}let y=new AbortController,g,p,A=()=>{g=void 0,p&&!y.signal.aborted&&l({...p});},N=xt({url:e,signal:y.signal,state:()=>({terminal:W(c.current?.recordStatus),paused:It({latestMessage:p,recordStatus:c.current?.recordStatus,suppressApprovalPause:c.current?.suppressApprovalPause??false})}),onState:C=>{y.signal.aborted||u(C);},wake:k});return (async()=>{try{for await(let C of readUIMessageStream({stream:N,terminateOnError:!0}))p=C,g||(g=setTimeout(A,Mt));A();}catch(C){if(y.signal.aborted)return;C instanceof G?a(true):(console.error("Run stream error",C),u("error"));}})(),()=>{y.abort(),g&&clearTimeout(g);}},[e,k]),n?r:{message:s?Te(s,t?.decidedApprovals??{}):void 0,status:d}}function tn(e,t){let[n,a]=useState(),[r,s]=useState("streaming"),l=t?.recordStatus,d=t?.resumeToken??0,u=useRef(t?.decidedApprovals??{});u.current=t?.decidedApprovals??{};let c=useRef(t?.suppressApprovalPause??false);c.current=t?.suppressApprovalPause??false;let f=useRef(e),k=useRef(n);return k.current=n,useEffect(()=>{let w=f.current!==e;if(f.current=e,!e){a(void 0),s("unavailable");return}let y=new AbortController,g=w?void 0:k.current,p=w?0:g?.parts.length??0;if(w)a(void 0);else if(g&&(l==="running"||W(l))){let b=Te(g,u.current);b!==g&&(g=b,a(b));}s("streaming");let A=e.includes("?")?"&":"?",N=async()=>{let b=await fetch(`${e}${A}startIndex=0`,{credentials:"include",signal:y.signal});if(b.status===404)return "unavailable";if(!b.ok||!b.body)throw new Error(`Failed to fetch the run stream (status ${b.status.toString()})`);let T=false,P=parseJsonEventStream({schema:uiMessageChunkSchema,stream:b.body}).pipeThrough(new TransformStream({transform:(M,Et)=>{if(!M.success)throw M.error;M.value.type==="finish"&&(T=true),Et.enqueue(M.value);}})),pe=readUIMessageStream({onError:M=>{y.signal.aborted||console.error("Run stream chunk error",M);},stream:P}),R=null,Q=p===0,ze=(M=false)=>{y.signal.aborted||!g||!Q&&(Q=M||g.parts.length>=p,!Q)||a({...g});};try{for await(let M of pe){if(y.signal.aborted)break;g=M,R===null&&(R=window.setTimeout(()=>{R=null,ze();},Mt));}}finally{R!==null&&(window.clearTimeout(R),R=null),ze(true);}return T?"finished":"incomplete"},C=async()=>{let b=0;for(;!y.signal.aborted;){b>0&&await Ya(Dt);try{let T=await N();if(y.signal.aborted)return;if(T==="unavailable"){s("unavailable");return}if(T==="finished"&&W(l)){s("finished");return}if(W(l)){s("finished");return}if(It({latestMessage:g,recordStatus:l,suppressApprovalPause:c.current})){s("paused");return}if(!(l==="running"||c.current)&&b>=At-1){s("error");return}}catch(T){if(y.signal.aborted||Qa(T))return;if(console.error("Run stream error",T),W(l)){s("finished");return}if(!(l==="running"||c.current)&&b>=At-1){s("error");return}}b+=1;}},Y=window.setTimeout(()=>{C();},0);return ()=>{window.clearTimeout(Y),y.abort("Run replay unmounted");}},[l,d,e]),{message:n,status:r}}function Pr(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 an(e){let t=e.trim();return t?t.split(`
7
+ `).every(n=>/^`{3,}[\w-]*$/.test(n.trim())):false}function nn({attachments:e,text:t}){return jsxs("div",{className:"fk:ml-auto fk:flex fk:w-fit fk:max-w-[70%] fk:flex-col fk:items-end fk:gap-1",children:[jsx(vt,{attachments:e}),t.trim()?jsx("div",{className:"fk:whitespace-pre-wrap fk:rounded-xl fk:bg-muted fk:dark:bg-white/20 fk:px-3.5 fk:py-2 fk:text-base fk:corner-squircle",children:t}):null,jsxs("span",{className:"fk:inline-flex fk:items-center fk:gap-1 fk:text-xs fk:text-muted-foreground",children:[jsx(CornerDownRightIcon,{className:"fk:size-3 fk:shrink-0"}),"Added while the agent was working"]})]})}function Dr({api:e,part:t,partIndex:n,parts:a}){if(de(t))return null;if(K(t.type)){let r=ue(t);return r?jsx(sn,{message:r}):null}if(t.type==="text")return an(t.text)&&a.some(s=>s.type===Ie)?null:jsx(rn,{part:t});if(t.type==="data-generating-files")return jsx(cn,{message:h(t)});if(t.type==="data-run-artifact")return jsx(fn,{api:e,message:h(t)});if(t.type==="data-tool-delivery")return jsx(pn,{message:h(t)});if(t.type==="data-run-summary")return jsx(mn,{message:h(t)});if(t.type==="data-subtask"){let r=h(t),s=r.status==="running"?`Running "${r.title}"`:r.status==="done"?`Completed "${r.title}"${typeof r.stepsUsed=="number"?` in ${r.stepsUsed.toString()} steps`:""}`:`"${r.title}" failed: ${r.error?.message??"unknown error"}`;return jsxs(j,{children:[jsxs(B,{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(fe,{isError:r.status==="error",loading:r.status==="running"})}),jsx("span",{className:"fk:text-xs",children:s}),r.resultPreview?jsx("p",{className:"fk:mt-1 fk:text-xs fk:text-muted-foreground",children:r.resultPreview}):null]})]})}if(t.type==="data-mid-turn-message"){let r=h(t);return r.monitorEvent?jsx(bt,{data:r.monitorEvent}):jsx(nn,{attachments:r.attachments,text:r.text})}if(t.type==="data-context-compaction"){let r=h(t);return jsxs("p",{className:"fk:text-xs fk:text-muted-foreground",children:["Earlier messages (",r.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 r=h(t);return jsx(xn,{pluginId:r.pluginId})}if(t.type==="data-suggested-prompt")return null;if(t.type==="data-turn-error"){let r=h(t);return jsxs(j,{className:"fk:border-red-700/40",children:[jsxs(B,{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:r.message})]})}if(t.type==="data-mutation-approval"){let r=h(t);return Ne(r)?jsx(gn,{message:r}):jsx(kn,{api:e,message:r})}return t.type==="data-bulk-graphql-action"?jsx(vn,{message:h(t)}):t.type===Ie?a.slice(n+1).find(s=>s.type===Ie)?null:jsx(Ha,{parts:a}):t.type.startsWith("data-")?jsx(yn,{part:t}):null}function rn({part:e}){return jsx(ob,{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 sn({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 on=1e3;function ln({text:e}){let t=useRef(typeof performance>"u"?0:performance.now()),n=()=>-(((typeof performance>"u"?0:performance.now())-t.current)%on),[a,r]=useState({current:e,currentDelayMs:0,key:0,previous:null,previousDelayMs:0});return useEffect(()=>{r(s=>s.current===e?s:{current:e,currentDelayMs:n(),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:[a.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:`${a.previousDelayMs.toString()}ms`},children:a.previous})},`previous-${a.key.toString()}`):null,jsx("span",{className:a.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:`${a.currentDelayMs.toString()}ms`},children:a.current})},`current-${a.key.toString()}`)]})}var un=1e3;function dn(e,t){let n=un,[a,r]=useState(e),s=useRef(Date.now()),l=useRef(e);return l.current=e,useEffect(()=>{if(e===a)return;let d=Math.max(0,n-(Date.now()-s.current)),u=window.setTimeout(()=>{s.current=Date.now(),r(l.current);},d);return ()=>{window.clearTimeout(u);}},[a,e,n]),a}function Mr({label:e,visible:t}){let n=dn(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(ln,{text:n})})}function j({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 B({children:e}){return jsx("div",{className:"fk:flex fk:items-center fk:gap-2 fk:font-medium fk:text-muted-foreground",children:e})}function fe({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 _e({error:e,icon:t,loading:n,message:a,title:r}){return jsxs(j,{children:[jsxs(B,{children:[t,r]}),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(fe,{isError:!!e,loading:n})}),jsx("span",{className:"fk:text-xs",children:a})]})]})}function cn({message:e}){let t=["error","uploading","generating"].includes(e.status),n=t?e.paths.slice(0,e.paths.length-1):e.paths,a=t?e.paths[e.paths.length-1]??"":null;return jsxs(j,{children:[jsxs(B,{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:[n.map((r,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:r})]},`${r}-${s.toString()}`)),typeof a=="string"?jsxs("div",{className:"fk:flex fk:items-center fk:gap-2",children:[jsx(fe,{isError:e.status==="error",loading:e.status!=="error"}),jsx("span",{children:e.status==="error"?e.error?.message??a:a})]}):null]})]})}function fn({api:e,message:t}){let n=t.status==="done"&&t.artifactId,a=n?e.getArtifactUrl(t.artifactId??""):"",r=n?e.getArtifactUrl(t.artifactId??"",{download:true}):"",s=hn(t.sizeBytes);return jsxs(j,{children:[jsxs(B,{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(fe,{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"&&[bn(t),s].filter(Boolean).join(" \xB7 "),t.status==="error"&&(t.error?.message??"Failed to publish artifact")]})]}),n?jsxs("div",{className:"fk:flex fk:flex-wrap fk:gap-2",children:[jsx(b$2,{asChild:true,size:"sm",variant:"outline",children:jsx("a",{href:a,rel:"noreferrer",target:"_blank",children:"Preview"})}),jsx(b$2,{asChild:true,size:"sm",variant:"outline",children:jsxs("a",{href:r,children:[jsx(DownloadIcon,{className:"fk:size-3"}),"Download"]})}),t.url?jsx(b$2,{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 pn({message:e}){let t=e.provider==="slack"?"Slack":"Microsoft Teams",n=e.provider==="slack"?jsx(MessageSquareIcon,{className:"fk:size-3.5"}):jsx(SendIcon,{className:"fk:size-3.5"});return jsx(_e,{error:e.error?.message,icon:n,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 mn({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"}),n=e.status==="success"?"Run completed":e.status==="skipped"?"Run skipped":"Run failed";return jsxs(j,{className:e.status==="failed"?"fk:border-red-700/40":"fk:border-green-700/40",children:[jsxs(B,{children:[t,jsx("span",{children:n})]}),e.status==="failed"?jsx("p",{className:"fk:whitespace-pre-wrap fk:text-xs",children:e.summary}):null]})}function kn({api:e,message:t}){let{projectId:n}=Va(),a=useContext(Ga),r=useContext(Wa),s=useRef(void 0),{data:l,error:d,isValidating:u,mutate:c}=Ra(n?g(n).approval(t.approvalId):null,f$1,{refreshInterval:p=>t.status!=="pending"||p?.approval?.status&&p.approval.status!=="pending"?0:Dt}),f=l?.approval?.status,k=(f??t.status)==="pending",w=l?.approval?.kind==="schema"&&l.approval.status==="approved";useEffect(()=>{!w||!n||ie({approvalId:t.approvalId,approvalUrl:g(n).approval(t.approvalId),projectId:n});},[w,t.approvalId,n]),useEffect(()=>{c();},[t.status,c]),useEffect(()=>{let p=s.current;s.current=f,!(t.status!=="pending"||!f||f==="pending")&&p==="pending"&&a?.onApprovalDecided(l?.approval?.id??t.approvalId,f);},[f,l?.approval?.id,t.approvalId,t.status,a]);function y(p){p.status!=="pending"&&(s.current=p.status),c(),a?.onApprovalDecided(p.id,p.status);}let g$1;if(l?.approval)g$1=jsx(st,{api:e,approval:l.approval,chat:r,onDecided:y},l.approval.status);else if(d&&!u){let p=d instanceof Error&&d.message?d.message:"Request failed";g$1=jsxs("div",{className:"fk:space-y-2",children:[jsxs("p",{className:"fk:text-xs fk:text-destructive",children:["Failed to load proposal ",t.operationsSummary,": ",p]}),jsx(b$2,{size:"sm",variant:"outline",onClick:()=>{c();},children:"Retry"})]});}else g$1=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(j,{children:[jsxs(B,{children:[r?jsx(ShieldIcon,{className:"fk:size-3.5"}):jsx(DatabaseZapIcon,{className:"fk:size-3.5"}),r?"Approval request":"Mutation approval",k?jsx(LoaderCircle,{className:"fk:ml-1 fk:size-3.5 fk:animate-spin"}):null]}),jsx("div",{className:"fk:mt-2",children:g$1}),t.status==="error"&&t.error?jsx("p",{className:"fk:mt-2 fk:text-xs fk:text-destructive",children:t.error.message}):null]})}function gn({message:e}){let t=e.operationsSummary.replace(/^Call /,"");return jsx(_e,{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 vn({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(_e,{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 yn({part:e}){return jsxs(j,{className:"fk:bg-muted/30",children:[jsxs(B,{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 hn(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 bn(e){return e.kind==="pdf"?"PDF artifact":e.kind==="html"?"HTML artifact":"Artifact"}function xn({pluginId:e}){let{pathname:t}=useLocation(),[n]=t.split("/ai/");return jsxs(j,{children:[jsxs("p",{className:"fk:text-sm",children:["Connect ",e," to use it in this conversation."]}),jsx(b$2,{asChild:true,size:"sm",variant:"outline",children:jsxs(Link,{to:`${n}/ai/plugins/${encodeURIComponent(e)}`,children:["Connect ",e]})})]})}export{Pr as A,Dr as B,sn as C,Mr as D,kn as E,Ge as a,Ft as b,st as c,jn as d,de as e,fa as f,Ce as g,it as h,pa as i,lt as j,Hn as k,Vn as l,Gn as m,Wn as n,Yn as o,vt as p,sr as q,bt as r,or as s,Va as t,Dt as u,Ga as v,Wa as w,Cr as x,W as y,Tr as z};//# sourceMappingURL=chunk-QNGDJNWD.js.map
8
+ //# sourceMappingURL=chunk-QNGDJNWD.js.map