bunqueue-dashboard 0.0.29 → 0.0.31

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 (74) hide show
  1. package/agent/db.ts +16 -19
  2. package/agent/server.ts +4 -4
  3. package/dist/.vite/manifest.json +194 -146
  4. package/dist/assets/{AddJob-UCSTFuum.js → AddJob-CAhdg38n.js} +1 -1
  5. package/dist/assets/{Alerts-CofRabaP.js → Alerts-70bxf-PT.js} +1 -1
  6. package/dist/assets/{AreaChart-Dl_9G6GH.js → AreaChart-2gM0YoZT.js} +1 -1
  7. package/dist/assets/{Benchmark-B1VUJJLw.js → Benchmark-CFZ3WCvj.js} +1 -1
  8. package/dist/assets/{BulkAddJobs-DVgkRtrp.js → BulkAddJobs-BzgzpGg_.js} +1 -1
  9. package/dist/assets/CopilotPanel-DZUGIf1q.js +44 -0
  10. package/dist/assets/{Cron-CqlZj2V5.js → Cron-ltjSoTjj.js} +1 -1
  11. package/dist/assets/CronManager-BcFALDeT.js +1 -0
  12. package/dist/assets/{Database-BYZ8LJb5.js → Database-CV2yt5O2.js} +2 -2
  13. package/dist/assets/{Diagnostics-Dk1ErNCF.js → Diagnostics-D-EK4GEi.js} +1 -1
  14. package/dist/assets/Dlq-fZAKwQoC.js +1 -0
  15. package/dist/assets/DlqControl-eTrrQCrn.js +1 -0
  16. package/dist/assets/{DlqPro-D8DOy5MI.js → DlqPro-CF79339e.js} +1 -1
  17. package/dist/assets/{Flows-DP9-h7a0.js → Flows-Ba8G7mcC.js} +1 -1
  18. package/dist/assets/JobInspector--d_8ca9p.js +2 -0
  19. package/dist/assets/Jobs-DEqAc1A5.js +1 -0
  20. package/dist/assets/JobsPro-BcaokZIf.js +1 -0
  21. package/dist/assets/Logs-DBTukPIX.js +1 -0
  22. package/dist/assets/LogsPro-Wl_e6hZM.js +1 -0
  23. package/dist/assets/{McpServer-MfQ0qsAI.js → McpServer-CnWJsKw7.js} +1 -1
  24. package/dist/assets/{Metrics-C4Dwg_DP.js → Metrics-DzeIhNL-.js} +1 -1
  25. package/dist/assets/{MetricsPro-Bt9zLjkN.js → MetricsPro-O9eVJSH0.js} +1 -1
  26. package/dist/assets/Overview-Bnu7rWqt.js +1 -0
  27. package/dist/assets/{Pagination-BQg6KGW1.js → Pagination-D4ki-pGz.js} +1 -1
  28. package/dist/assets/QueueActions-DHoSkWRz.js +1 -0
  29. package/dist/assets/QueueControl-DKqEXnkM.js +1 -0
  30. package/dist/assets/{QueueDetail-wjRLlCYY.js → QueueDetail-DLRow04B.js} +1 -1
  31. package/dist/assets/QueueDetailPro-BYmOVd4T.js +1 -0
  32. package/dist/assets/Queues-CoyjRFN7.js +1 -0
  33. package/dist/assets/{QueuesOverview-DfRqAfS1.js → QueuesOverview-BeWdJpKi.js} +1 -1
  34. package/dist/assets/{S3Backup-UQ_HKrn0.js → S3Backup-BaLFgl9d.js} +1 -1
  35. package/dist/assets/{S3BackupPro-V3JNhUK8.js → S3BackupPro-DJB4oWgz.js} +1 -1
  36. package/dist/assets/{ServerControl-DXidWdsq.js → ServerControl-_0lVB33E.js} +1 -1
  37. package/dist/assets/{Settings-0j8DZK9n.js → Settings-zKFJTtnq.js} +1 -1
  38. package/dist/assets/Usage-CKGkvl0j.js +1 -0
  39. package/dist/assets/{UsagePro-CbVFCD3J.js → UsagePro-B-TJ6fp4.js} +1 -1
  40. package/dist/assets/{Webhooks-Dr0oBZr9.js → Webhooks-C3zmvY-_.js} +1 -1
  41. package/dist/assets/{Workers-Bwil4zIU.js → Workers-jKhhXl3W.js} +1 -1
  42. package/dist/assets/{WorkersPro-BRYPAhyx.js → WorkersPro-mvY5VX8I.js} +1 -1
  43. package/dist/assets/{connectionStore-B-hNUqwK.js → connectionStore-Ci04lJmR.js} +1 -1
  44. package/dist/assets/dist-1f1fMHVO.js +11 -0
  45. package/dist/assets/dist-BlWBaCN6.js +11 -0
  46. package/dist/assets/dist-DZL8soAh.js +79 -0
  47. package/dist/assets/dist-DjvZiKhB.js +2 -0
  48. package/dist/assets/dist-DpZcbP9W.js +11 -0
  49. package/dist/assets/{form-C-zZyKfB.js → form-DGinTEEb.js} +1 -1
  50. package/dist/assets/index-BOcegTHa.js +8 -0
  51. package/dist/assets/index-DWV3tgrk.css +1 -0
  52. package/dist/assets/{react-vendor-B68RYDeC.js → react-vendor-BcouBxpZ.js} +2 -2
  53. package/dist/assets/{useThroughputSeries-defI_JpV.js → useThroughputSeries-Chp5OLx3.js} +1 -1
  54. package/dist/index.html +4 -4
  55. package/package.json +5 -5
  56. package/scripts/embedded.gen.ts +122 -112
  57. package/scripts/serve.ts +11 -0
  58. package/dist/assets/CopilotPanel-BJeJYfaz.js +0 -152
  59. package/dist/assets/CronManager-C6kjWCLE.js +0 -1
  60. package/dist/assets/Dlq-DANXiXsm.js +0 -1
  61. package/dist/assets/DlqControl-DUturU7q.js +0 -1
  62. package/dist/assets/JobInspector-BHZtkFL6.js +0 -2
  63. package/dist/assets/Jobs-Bgr-HRmL.js +0 -1
  64. package/dist/assets/JobsPro-C2Vc2iRC.js +0 -1
  65. package/dist/assets/Logs-CaOn3IpL.js +0 -1
  66. package/dist/assets/LogsPro-BpSZaHzN.js +0 -1
  67. package/dist/assets/Overview-BO3xG6I0.js +0 -1
  68. package/dist/assets/QueueActions-Bez_iOjl.js +0 -1
  69. package/dist/assets/QueueControl-CEXlJDkE.js +0 -1
  70. package/dist/assets/QueueDetailPro-CuVyxX4Z.js +0 -1
  71. package/dist/assets/Queues-2W2E6e5R.js +0 -1
  72. package/dist/assets/Usage-C5DsZvR5.js +0 -1
  73. package/dist/assets/index-BjRjwWwc.js +0 -8
  74. package/dist/assets/index-mF63w920.css +0 -1
@@ -1 +1 @@
1
- import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,r,t as i,u as a}from"./react-vendor-B68RYDeC.js";import{A as o,G as s,J as c,M as l,T as u,U as d,W as f,b as p,c as m,h,m as g,nt as _,rt as v,w as y,x as b}from"./index-BjRjwWwc.js";import{t as x}from"./Pagination-BQg6KGW1.js";import{t as S}from"./promisePool-Daxkc1OB.js";var C=e(n(),1),w=i(),T=6,E=15,D=[[`waiting`,`Waiting`],[`active`,`Active`],[`completed`,`Completed`],[`failed`,`Failed`],[`delayed`,`Delayed`]];function O(){let e=a(),[n,i]=(0,C.useState)(``),[O,k]=(0,C.useState)(0),[A,j]=(0,C.useState)(new Set),[M,N]=(0,C.useState)(!1),[P,F]=(0,C.useState)(null),[I,L]=(0,C.useState)(null),[R,z]=(0,C.useState)(`desc`),{data:B,error:V,loading:H,refetch:U}=o(()=>_.queuesSummary(),[]),W=B??[],G=e=>{I===e?R===`desc`?z(`asc`):L(null):(L(e),z(`desc`)),k(0)},K=(0,C.useMemo)(()=>{let e=n.trim().toLowerCase(),t=[...e?W.filter(t=>t.name.toLowerCase().includes(e)):W].sort((e,t)=>e.name.localeCompare(t.name));if(I){let e=R===`desc`?-1:1;t.sort((t,n)=>e*(t.counts[I]-n.counts[I]))}return t},[W,n,I,R]),q=(0,C.useMemo)(()=>W.reduce((e,t)=>(e.waiting+=t.counts.waiting,e.active+=t.counts.active,e.failed+=t.counts.failed,e.paused+=+!!t.paused,e),{waiting:0,active:0,failed:0,paused:0}),[W]),J=Math.max(1,Math.ceil(K.length/E)),Y=Math.min(O,J-1),X=K.slice(Y*E,Y*E+E),Z=async e=>{j(t=>new Set(t).add(e.name)),F(null);try{await(e.paused?_.resume(e.name):_.pause(e.name)),F({ok:!0,text:`${e.name} ${e.paused?`resumed`:`paused`} ✓`})}catch(t){F({ok:!1,text:t.message}),v.error(`Failed to ${e.paused?`resume`:`pause`} ${e.name}`,t.message)}finally{j(t=>{let n=new Set(t);return n.delete(e.name),n}),U()}},Q=async e=>{let t=W.filter(t=>e===`pause`?!t.paused:t.paused);if(t.length===0){v.info(`No queues to ${e}`);return}if(!window.confirm(`${e===`pause`?`Pause`:`Resume`} ${t.length} queue(s)?`))return;N(!0),F(null);let n=(await S(t,T,t=>e===`pause`?_.pause(t.name):_.resume(t.name))).filter(e=>e.status===`rejected`).length,r=`${e===`pause`?`Paused`:`Resumed`} ${t.length-n}/${t.length} queues${n?`, ${n} failed`:``}`;F({ok:n===0,text:r}),n===0?v.success(r):v.error(r),N(!1),U()};return H&&!B&&!V?(0,w.jsx)(p,{label:`Loading queues…`}):(0,w.jsxs)(`div`,{children:[(0,w.jsx)(h,{title:`Queues`,description:`${W.length} queues`,live:!0,actions:W.length>0?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(y,{variant:`warning`,size:`sm`,disabled:M||q.paused>=W.length,onClick:()=>Q(`pause`),children:[(0,w.jsx)(d,{className:`size-3.5`}),` Pause all`]}),(0,w.jsxs)(y,{variant:`success`,size:`sm`,disabled:M||q.paused===0,onClick:()=>Q(`resume`),children:[(0,w.jsx)(f,{className:`size-3.5`}),` Resume all`]})]}):void 0}),V&&(0,w.jsx)(b,{onRetry:U}),(0,w.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,w.jsx)(g,{label:`Waiting`,value:m(q.waiting),tone:`amber`,compact:!0}),(0,w.jsx)(g,{label:`Active`,value:m(q.active),tone:`blue`,compact:!0}),(0,w.jsx)(g,{label:`Failed`,value:m(q.failed),tone:q.failed?`red`:`default`,compact:!0}),(0,w.jsx)(g,{label:`Paused`,value:m(q.paused),tone:q.paused?`amber`:`default`,compact:!0})]}),(0,w.jsxs)(`div`,{className:`relative mb-4 max-w-sm`,children:[(0,w.jsx)(c,{className:`pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-faint`}),(0,w.jsx)(`input`,{value:n,onChange:e=>{i(e.target.value),k(0)},placeholder:`Search queues…`,"aria-label":`Filter queues`,className:`h-9 w-full rounded-lg border border-line bg-surface pl-9 pr-3 text-sm text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`})]}),P&&(0,w.jsx)(`div`,{role:`status`,className:t(`mb-3 text-sm`,P.ok?`text-success`:`text-danger`),children:P.text}),(0,w.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,w.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,w.jsx)(`thead`,{children:(0,w.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,w.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Queue`}),D.map(([e,t])=>(0,w.jsx)(`th`,{scope:`col`,"aria-sort":I===e?R===`desc`?`descending`:`ascending`:void 0,className:`px-5 py-3 text-right font-medium`,children:(0,w.jsxs)(`button`,{type:`button`,onClick:()=>G(e),className:`inline-flex items-center gap-1 rounded uppercase tracking-wider hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,children:[t,I===e&&(0,w.jsx)(`span`,{"aria-hidden":`true`,children:R===`desc`?`↓`:`↑`})]})},e)),(0,w.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Status`}),(0,w.jsx)(`th`,{scope:`col`,className:`w-24 px-5 py-3 text-right font-medium`,children:`Actions`})]})}),(0,w.jsx)(`tbody`,{children:X.length===0?(0,w.jsx)(`tr`,{children:(0,w.jsx)(`td`,{colSpan:8,className:`px-5 py-12 text-center text-sm text-faint`,children:n?`No queues match your search.`:`No queues yet.`})}):X.map(n=>{let i=A.has(n.name);return(0,w.jsxs)(`tr`,{onClick:()=>e(`/queues/${encodeURIComponent(n.name)}`),className:`group cursor-pointer border-b border-line last:border-0 transition-colors hover:bg-surface-2/50`,children:[(0,w.jsx)(`td`,{className:`px-5 py-3`,children:(0,w.jsxs)(r,{to:`/queues/${encodeURIComponent(n.name)}`,onClick:e=>e.stopPropagation(),className:`flex items-center gap-2 rounded font-medium text-fg hover:text-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,children:[(0,w.jsx)(s,{className:`size-4 text-faint`}),n.name]})}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-warning`,children:m(n.counts.waiting)}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-blue-400`,children:m(n.counts.active)}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-success`,children:m(n.counts.completed)}),(0,w.jsx)(`td`,{className:t(`px-5 py-3 text-right tnum`,n.counts.failed?`text-danger`:`text-muted`),children:m(n.counts.failed)}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:m(n.counts.delayed)}),(0,w.jsx)(`td`,{className:`px-5 py-3`,children:(0,w.jsxs)(`span`,{className:t(`inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium`,n.paused?`bg-orange-500/10 text-orange-400`:`bg-emerald-500/10 text-success`),children:[(0,w.jsx)(`span`,{className:`size-1.5 rounded-full bg-current`}),n.paused?`Paused`:`Active`]})}),(0,w.jsx)(`td`,{className:`px-5 py-3`,children:(0,w.jsxs)(`div`,{className:`flex items-center justify-end gap-1`,children:[(0,w.jsx)(u,{"aria-label":n.paused?`Resume queue`:`Pause queue`,disabled:i,onClick:e=>{e.stopPropagation(),Z(n)},children:n.paused?(0,w.jsx)(f,{className:`size-3.5 text-success`}):(0,w.jsx)(d,{className:`size-3.5 text-warning`})}),(0,w.jsx)(l,{className:`size-4 text-faint opacity-0 transition-opacity group-hover:opacity-100`})]})})]},n.name)})})]})}),(0,w.jsx)(x,{page:Y,pageSize:E,total:K.length,onPageChange:k,label:`queues`})]})}export{O as QueuesOverview};
1
+ import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,r,t as i,u as a}from"./react-vendor-BcouBxpZ.js";import{A as o,G as s,J as c,M as l,T as u,U as d,W as f,b as p,c as m,h,m as g,nt as _,rt as v,w as y,x as b}from"./index-BOcegTHa.js";import{t as x}from"./Pagination-D4ki-pGz.js";import{t as S}from"./promisePool-Daxkc1OB.js";var C=e(n(),1),w=i(),T=6,E=15,D=[[`waiting`,`Waiting`],[`active`,`Active`],[`completed`,`Completed`],[`failed`,`Failed`],[`delayed`,`Delayed`]];function O(){let e=a(),[n,i]=(0,C.useState)(``),[O,k]=(0,C.useState)(0),[A,j]=(0,C.useState)(new Set),[M,N]=(0,C.useState)(!1),[P,F]=(0,C.useState)(null),[I,L]=(0,C.useState)(null),[R,z]=(0,C.useState)(`desc`),{data:B,error:V,loading:H,refetch:U}=o(()=>_.queuesSummary(),[]),W=B??[],G=e=>{I===e?R===`desc`?z(`asc`):L(null):(L(e),z(`desc`)),k(0)},K=(0,C.useMemo)(()=>{let e=n.trim().toLowerCase(),t=[...e?W.filter(t=>t.name.toLowerCase().includes(e)):W].sort((e,t)=>e.name.localeCompare(t.name));if(I){let e=R===`desc`?-1:1;t.sort((t,n)=>e*(t.counts[I]-n.counts[I]))}return t},[W,n,I,R]),q=(0,C.useMemo)(()=>W.reduce((e,t)=>(e.waiting+=t.counts.waiting,e.active+=t.counts.active,e.failed+=t.counts.failed,e.paused+=+!!t.paused,e),{waiting:0,active:0,failed:0,paused:0}),[W]),J=Math.max(1,Math.ceil(K.length/E)),Y=Math.min(O,J-1),X=K.slice(Y*E,Y*E+E),Z=async e=>{j(t=>new Set(t).add(e.name)),F(null);try{await(e.paused?_.resume(e.name):_.pause(e.name)),F({ok:!0,text:`${e.name} ${e.paused?`resumed`:`paused`} ✓`})}catch(t){F({ok:!1,text:t.message}),v.error(`Failed to ${e.paused?`resume`:`pause`} ${e.name}`,t.message)}finally{j(t=>{let n=new Set(t);return n.delete(e.name),n}),U()}},Q=async e=>{let t=W.filter(t=>e===`pause`?!t.paused:t.paused);if(t.length===0){v.info(`No queues to ${e}`);return}if(!window.confirm(`${e===`pause`?`Pause`:`Resume`} ${t.length} queue(s)?`))return;N(!0),F(null);let n=(await S(t,T,t=>e===`pause`?_.pause(t.name):_.resume(t.name))).filter(e=>e.status===`rejected`).length,r=`${e===`pause`?`Paused`:`Resumed`} ${t.length-n}/${t.length} queues${n?`, ${n} failed`:``}`;F({ok:n===0,text:r}),n===0?v.success(r):v.error(r),N(!1),U()};return H&&!B&&!V?(0,w.jsx)(p,{label:`Loading queues…`}):(0,w.jsxs)(`div`,{children:[(0,w.jsx)(h,{title:`Queues`,description:`${W.length} queues`,live:!0,actions:W.length>0?(0,w.jsxs)(w.Fragment,{children:[(0,w.jsxs)(y,{variant:`warning`,size:`sm`,disabled:M||q.paused>=W.length,onClick:()=>Q(`pause`),children:[(0,w.jsx)(d,{className:`size-3.5`}),` Pause all`]}),(0,w.jsxs)(y,{variant:`success`,size:`sm`,disabled:M||q.paused===0,onClick:()=>Q(`resume`),children:[(0,w.jsx)(f,{className:`size-3.5`}),` Resume all`]})]}):void 0}),V&&(0,w.jsx)(b,{onRetry:U}),(0,w.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,w.jsx)(g,{label:`Waiting`,value:m(q.waiting),tone:`amber`,compact:!0}),(0,w.jsx)(g,{label:`Active`,value:m(q.active),tone:`blue`,compact:!0}),(0,w.jsx)(g,{label:`Failed`,value:m(q.failed),tone:q.failed?`red`:`default`,compact:!0}),(0,w.jsx)(g,{label:`Paused`,value:m(q.paused),tone:q.paused?`amber`:`default`,compact:!0})]}),(0,w.jsxs)(`div`,{className:`relative mb-4 max-w-sm`,children:[(0,w.jsx)(c,{className:`pointer-events-none absolute left-3 top-1/2 size-4 -translate-y-1/2 text-faint`}),(0,w.jsx)(`input`,{value:n,onChange:e=>{i(e.target.value),k(0)},placeholder:`Search queues…`,"aria-label":`Filter queues`,className:`h-9 w-full rounded-lg border border-line bg-surface pl-9 pr-3 text-sm text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`})]}),P&&(0,w.jsx)(`div`,{role:`status`,className:t(`mb-3 text-sm`,P.ok?`text-success`:`text-danger`),children:P.text}),(0,w.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,w.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,w.jsx)(`thead`,{children:(0,w.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,w.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Queue`}),D.map(([e,t])=>(0,w.jsx)(`th`,{scope:`col`,"aria-sort":I===e?R===`desc`?`descending`:`ascending`:void 0,className:`px-5 py-3 text-right font-medium`,children:(0,w.jsxs)(`button`,{type:`button`,onClick:()=>G(e),className:`inline-flex items-center gap-1 rounded uppercase tracking-wider hover:text-fg focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,children:[t,I===e&&(0,w.jsx)(`span`,{"aria-hidden":`true`,children:R===`desc`?`↓`:`↑`})]})},e)),(0,w.jsx)(`th`,{scope:`col`,className:`px-5 py-3 font-medium`,children:`Status`}),(0,w.jsx)(`th`,{scope:`col`,className:`w-24 px-5 py-3 text-right font-medium`,children:`Actions`})]})}),(0,w.jsx)(`tbody`,{children:X.length===0?(0,w.jsx)(`tr`,{children:(0,w.jsx)(`td`,{colSpan:8,className:`px-5 py-12 text-center text-sm text-faint`,children:n?`No queues match your search.`:`No queues yet.`})}):X.map(n=>{let i=A.has(n.name);return(0,w.jsxs)(`tr`,{onClick:()=>e(`/queues/${encodeURIComponent(n.name)}`),className:`group cursor-pointer border-b border-line last:border-0 transition-colors hover:bg-surface-2/50`,children:[(0,w.jsx)(`td`,{className:`px-5 py-3`,children:(0,w.jsxs)(r,{to:`/queues/${encodeURIComponent(n.name)}`,onClick:e=>e.stopPropagation(),className:`flex items-center gap-2 rounded font-medium text-fg hover:text-accent focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-accent/50`,children:[(0,w.jsx)(s,{className:`size-4 text-faint`}),n.name]})}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-warning`,children:m(n.counts.waiting)}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-blue-400`,children:m(n.counts.active)}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-success`,children:m(n.counts.completed)}),(0,w.jsx)(`td`,{className:t(`px-5 py-3 text-right tnum`,n.counts.failed?`text-danger`:`text-muted`),children:m(n.counts.failed)}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:m(n.counts.delayed)}),(0,w.jsx)(`td`,{className:`px-5 py-3`,children:(0,w.jsxs)(`span`,{className:t(`inline-flex items-center gap-1.5 rounded-full px-2 py-0.5 text-xs font-medium`,n.paused?`bg-orange-500/10 text-orange-400`:`bg-emerald-500/10 text-success`),children:[(0,w.jsx)(`span`,{className:`size-1.5 rounded-full bg-current`}),n.paused?`Paused`:`Active`]})}),(0,w.jsx)(`td`,{className:`px-5 py-3`,children:(0,w.jsxs)(`div`,{className:`flex items-center justify-end gap-1`,children:[(0,w.jsx)(u,{"aria-label":n.paused?`Resume queue`:`Pause queue`,disabled:i,onClick:e=>{e.stopPropagation(),Z(n)},children:n.paused?(0,w.jsx)(f,{className:`size-3.5 text-success`}):(0,w.jsx)(d,{className:`size-3.5 text-warning`})}),(0,w.jsx)(l,{className:`size-4 text-faint opacity-0 transition-opacity group-hover:opacity-100`})]})})]},n.name)})})]})}),(0,w.jsx)(x,{page:Y,pageSize:E,total:K.length,onPageChange:k,label:`queues`})]})}export{O as QueuesOverview};
@@ -1 +1 @@
1
- import{t as e}from"./react-vendor-B68RYDeC.js";import{A as t,C as n,S as r,b as i,h as a,j as o,x as s}from"./index-BjRjwWwc.js";var c=e(),l=[[`S3_BACKUP_ENABLED`,`Set to 1 to enable periodic backups`],[`S3_BUCKET`,`Target bucket name`],[`S3_REGION`,`Bucket region (default us-east-1)`],[`S3_ENDPOINT`,`Custom endpoint (for S3-compatible stores)`],[`S3_ACCESS_KEY_ID`,`Access key`],[`S3_SECRET_ACCESS_KEY`,`Secret key`],[`S3_BACKUP_INTERVAL`,`Interval in ms (default 21600000 = 6h)`],[`S3_BACKUP_RETENTION`,`Backups to keep (default 7)`]];function u(){let{data:e,error:u,loading:d,refetch:f}=t(()=>o.storage(),[]);return(0,c.jsxs)(`div`,{children:[u&&(0,c.jsx)(s,{onRetry:f}),(0,c.jsx)(a,{title:`S3 Backup`,description:`SQLite snapshot backups to object storage.`,live:!0}),(0,c.jsx)(`div`,{className:`mb-6 rounded-lg border border-line bg-surface/60 px-4 py-3 text-sm text-muted`,children:`S3 backup runs on the server and is configured via environment variables — it cannot be toggled from the dashboard. The status below reflects the connected server's storage.`}),(0,c.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,c.jsxs)(r,{children:[(0,c.jsx)(n,{title:`Storage status`}),d&&!e&&!u?(0,c.jsx)(i,{}):(0,c.jsxs)(`dl`,{className:`divide-y divide-line text-sm`,children:[(0,c.jsxs)(`div`,{className:`flex items-center justify-between py-2.5`,children:[(0,c.jsx)(`dt`,{className:`text-muted`,children:`Disk`}),(0,c.jsx)(`dd`,{className:e?.status?.diskFull?`font-medium text-red-400`:`font-medium text-emerald-400`,children:e?.status?.diskFull?`Full`:`Healthy`})]}),(0,c.jsxs)(`div`,{className:`flex items-center justify-between py-2.5`,children:[(0,c.jsx)(`dt`,{className:`text-muted`,children:`Path`}),(0,c.jsx)(`dd`,{className:`font-mono text-xs text-fg`,children:String(e?.status?.path??`—`)})]})]})]}),(0,c.jsxs)(r,{children:[(0,c.jsx)(n,{title:`Configuration (server env)`}),(0,c.jsx)(`dl`,{className:`divide-y divide-line text-sm`,children:l.map(([e,t])=>(0,c.jsxs)(`div`,{className:`flex items-center justify-between gap-4 py-2.5`,children:[(0,c.jsx)(`dt`,{className:`font-mono text-xs text-accent/90`,children:e}),(0,c.jsx)(`dd`,{className:`text-right text-xs text-faint`,children:t})]},e))})]})]})]})}export{u as S3Backup};
1
+ import{t as e}from"./react-vendor-BcouBxpZ.js";import{A as t,C as n,S as r,b as i,h as a,j as o,x as s}from"./index-BOcegTHa.js";var c=e(),l=[[`S3_BACKUP_ENABLED`,`Set to 1 to enable periodic backups`],[`S3_BUCKET`,`Target bucket name`],[`S3_REGION`,`Bucket region (default us-east-1)`],[`S3_ENDPOINT`,`Custom endpoint (for S3-compatible stores)`],[`S3_ACCESS_KEY_ID`,`Access key`],[`S3_SECRET_ACCESS_KEY`,`Secret key`],[`S3_BACKUP_INTERVAL`,`Interval in ms (default 21600000 = 6h)`],[`S3_BACKUP_RETENTION`,`Backups to keep (default 7)`]];function u(){let{data:e,error:u,loading:d,refetch:f}=t(()=>o.storage(),[]);return(0,c.jsxs)(`div`,{children:[u&&(0,c.jsx)(s,{onRetry:f}),(0,c.jsx)(a,{title:`S3 Backup`,description:`SQLite snapshot backups to object storage.`,live:!0}),(0,c.jsx)(`div`,{className:`mb-6 rounded-lg border border-line bg-surface/60 px-4 py-3 text-sm text-muted`,children:`S3 backup runs on the server and is configured via environment variables — it cannot be toggled from the dashboard. The status below reflects the connected server's storage.`}),(0,c.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,c.jsxs)(r,{children:[(0,c.jsx)(n,{title:`Storage status`}),d&&!e&&!u?(0,c.jsx)(i,{}):(0,c.jsxs)(`dl`,{className:`divide-y divide-line text-sm`,children:[(0,c.jsxs)(`div`,{className:`flex items-center justify-between py-2.5`,children:[(0,c.jsx)(`dt`,{className:`text-muted`,children:`Disk`}),(0,c.jsx)(`dd`,{className:e?.data?.diskFull?`font-medium text-red-400`:`font-medium text-emerald-400`,children:e?.data?.diskFull?`Full`:`Healthy`})]}),(0,c.jsxs)(`div`,{className:`flex items-center justify-between py-2.5`,children:[(0,c.jsx)(`dt`,{className:`text-muted`,children:`Error`}),(0,c.jsx)(`dd`,{className:`font-mono text-xs text-fg`,children:e?.data?.error?String(e.data.error):`—`})]})]})]}),(0,c.jsxs)(r,{children:[(0,c.jsx)(n,{title:`Configuration (server env)`}),(0,c.jsx)(`dl`,{className:`divide-y divide-line text-sm`,children:l.map(([e,t])=>(0,c.jsxs)(`div`,{className:`flex items-center justify-between gap-4 py-2.5`,children:[(0,c.jsx)(`dt`,{className:`font-mono text-xs text-accent/90`,children:e}),(0,c.jsx)(`dd`,{className:`text-right text-xs text-faint`,children:t})]},e))})]})]})]})}export{u as S3Backup};
@@ -1 +1 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-B68RYDeC.js";import{a as r,o as i}from"./connectionStore-B-hNUqwK.js";import{S as a,h as o,nt as s,q as c,v as l,w as u}from"./index-BjRjwWwc.js";import{a as d,n as f,r as p,t as m}from"./form-C-zZyKfB.js";var h=e(t(),1);function g(e){return{endpoint:e.endpoint,region:e.region,bucket:e.bucket,schedule:e.schedule,pathPrefix:e.pathPrefix}}var _=i()(r(e=>({endpoint:``,region:`us-east-1`,bucket:``,accessKeyId:``,secretAccessKey:``,schedule:`disabled`,pathPrefix:``,set:t=>e(t)}),{name:`bq-dash-s3`,partialize:g})),v=n();function y(){let e=_(),[t,n]=(0,h.useState)(null),r=e.bucket.trim()!==``;return(0,v.jsxs)(`div`,{children:[(0,v.jsx)(o,{title:`S3 Backup`,description:`Automatic backups to S3-compatible storage.`}),(0,v.jsxs)(`div`,{className:`mb-6 flex items-center justify-between rounded-xl border border-line bg-surface px-5 py-4`,children:[(0,v.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,v.jsx)(`span`,{className:`flex size-10 items-center justify-center rounded-lg bg-surface-2 text-faint`,children:(0,v.jsx)(c,{className:`size-5`})}),(0,v.jsxs)(`div`,{children:[(0,v.jsx)(`div`,{className:`font-semibold text-fg`,children:r?`Backup configured`:`No backup configured`}),(0,v.jsx)(`div`,{className:`text-xs text-faint`,children:r?`Target: ${e.bucket}`:`Set up S3 to protect your queue data`})]})]}),(0,v.jsx)(`span`,{className:r?`rounded-full bg-emerald-500/10 px-3 py-1 text-xs font-medium text-success`:`rounded-full bg-amber-500/10 px-3 py-1 text-xs font-medium text-warning`,children:r?`Local draft`:`Configure`})]}),(0,v.jsx)(`div`,{className:`mb-6 rounded-lg border border-line bg-surface/60 px-4 py-2.5 text-xs text-faint`,children:`bunqueue reads S3 backup settings from server environment variables (S3_BUCKET, S3_REGION, …). This form helps you assemble that configuration; it is stored locally in your browser.`}),(0,v.jsxs)(a,{className:`mb-6`,children:[(0,v.jsx)(`h3`,{className:`mb-1 text-base font-semibold text-fg`,children:`Connection Settings`}),(0,v.jsx)(`p`,{className:`mb-4 text-xs text-faint`,children:`Works with AWS S3, Cloudflare R2, MinIO, DigitalOcean Spaces, and any S3-compatible provider.`}),(0,v.jsxs)(`div`,{className:`grid grid-cols-1 gap-4 md:grid-cols-2`,children:[(0,v.jsx)(m,{label:`Endpoint`,children:(0,v.jsx)(f,{value:e.endpoint,onChange:t=>e.set({endpoint:t.target.value}),placeholder:`https://s3.amazonaws.com`})}),(0,v.jsx)(m,{label:`Region`,children:(0,v.jsx)(f,{value:e.region,onChange:t=>e.set({region:t.target.value}),placeholder:`us-east-1`})}),(0,v.jsx)(`div`,{className:`md:col-span-2`,children:(0,v.jsx)(m,{label:`Bucket name`,children:(0,v.jsx)(f,{value:e.bucket,onChange:t=>e.set({bucket:t.target.value}),placeholder:`my-bunqueue-backups`})})}),(0,v.jsx)(m,{label:`Access key ID`,children:(0,v.jsx)(f,{value:e.accessKeyId,onChange:t=>e.set({accessKeyId:t.target.value}),placeholder:`AKIA…`})}),(0,v.jsx)(m,{label:`Secret access key`,children:(0,v.jsx)(f,{type:`password`,value:e.secretAccessKey,onChange:t=>e.set({secretAccessKey:t.target.value}),placeholder:`••••••••••••••••`})}),(0,v.jsx)(`p`,{className:`-mt-2 text-xs text-faint md:col-span-2`,children:`Keys are kept in memory only and cleared on reload.`}),(0,v.jsxs)(`div`,{children:[(0,v.jsx)(p,{children:`Backup schedule`}),(0,v.jsxs)(d,{value:e.schedule,onChange:t=>e.set({schedule:t.target.value}),className:`mt-1.5`,title:`Local note only — actual scheduling requires server-side S3 config`,children:[(0,v.jsx)(`option`,{value:`disabled`,children:`Disabled`}),(0,v.jsx)(`option`,{value:`6h`,children:`Every 6 hours`}),(0,v.jsx)(`option`,{value:`12h`,children:`Every 12 hours`}),(0,v.jsx)(`option`,{value:`24h`,children:`Every 24 hours`})]})]}),(0,v.jsx)(m,{label:`Path prefix (optional)`,children:(0,v.jsx)(f,{value:e.pathPrefix,onChange:t=>e.set({pathPrefix:t.target.value}),placeholder:`backups/production/`})})]}),(0,v.jsxs)(`div`,{className:`mt-5 flex flex-wrap items-center gap-2`,children:[(0,v.jsx)(u,{onClick:async()=>{n(null);try{let e=await s.storage();n({ok:!e.data?.diskFull,msg:e.data?.diskFull?`Server disk is full`:`Server disk healthy — this does not validate the S3 credentials`})}catch(e){n({ok:!1,msg:e.message})}},children:`Check server storage`}),(0,v.jsx)(u,{disabled:!0,title:`Trigger a manual backup — requires server-side S3 config`,children:`Backup Now`}),(0,v.jsx)(`span`,{className:`text-xs text-faint`,children:`Saved locally as you type (keys excluded).`}),t&&(0,v.jsx)(`span`,{className:t.ok?`text-xs text-success`:`text-xs text-danger`,children:t.msg})]})]}),(0,v.jsxs)(a,{children:[(0,v.jsx)(`h3`,{className:`mb-4 text-base font-semibold text-fg`,children:`Backup History`}),(0,v.jsx)(l,{icon:(0,v.jsx)(c,{}),title:`No backups yet`,hint:`Configure your S3 connection and run a backup to get started.`})]})]})}export{y as S3BackupPro};
1
+ import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-BcouBxpZ.js";import{a as r,o as i}from"./connectionStore-Ci04lJmR.js";import{S as a,h as o,nt as s,q as c,v as l,w as u}from"./index-BOcegTHa.js";import{a as d,n as f,r as p,t as m}from"./form-DGinTEEb.js";var h=e(t(),1);function g(e){return{endpoint:e.endpoint,region:e.region,bucket:e.bucket,schedule:e.schedule,pathPrefix:e.pathPrefix}}var _=i()(r(e=>({endpoint:``,region:`us-east-1`,bucket:``,accessKeyId:``,secretAccessKey:``,schedule:`disabled`,pathPrefix:``,set:t=>e(t)}),{name:`bq-dash-s3`,partialize:g})),v=n();function y(){let e=_(),[t,n]=(0,h.useState)(null),r=e.bucket.trim()!==``;return(0,v.jsxs)(`div`,{children:[(0,v.jsx)(o,{title:`S3 Backup`,description:`Automatic backups to S3-compatible storage.`}),(0,v.jsxs)(`div`,{className:`mb-6 flex items-center justify-between rounded-xl border border-line bg-surface px-5 py-4`,children:[(0,v.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,v.jsx)(`span`,{className:`flex size-10 items-center justify-center rounded-lg bg-surface-2 text-faint`,children:(0,v.jsx)(c,{className:`size-5`})}),(0,v.jsxs)(`div`,{children:[(0,v.jsx)(`div`,{className:`font-semibold text-fg`,children:r?`Backup configured`:`No backup configured`}),(0,v.jsx)(`div`,{className:`text-xs text-faint`,children:r?`Target: ${e.bucket}`:`Set up S3 to protect your queue data`})]})]}),(0,v.jsx)(`span`,{className:r?`rounded-full bg-emerald-500/10 px-3 py-1 text-xs font-medium text-success`:`rounded-full bg-amber-500/10 px-3 py-1 text-xs font-medium text-warning`,children:r?`Local draft`:`Configure`})]}),(0,v.jsx)(`div`,{className:`mb-6 rounded-lg border border-line bg-surface/60 px-4 py-2.5 text-xs text-faint`,children:`bunqueue reads S3 backup settings from server environment variables (S3_BUCKET, S3_REGION, …). This form helps you assemble that configuration; it is stored locally in your browser.`}),(0,v.jsxs)(a,{className:`mb-6`,children:[(0,v.jsx)(`h3`,{className:`mb-1 text-base font-semibold text-fg`,children:`Connection Settings`}),(0,v.jsx)(`p`,{className:`mb-4 text-xs text-faint`,children:`Works with AWS S3, Cloudflare R2, MinIO, DigitalOcean Spaces, and any S3-compatible provider.`}),(0,v.jsxs)(`div`,{className:`grid grid-cols-1 gap-4 md:grid-cols-2`,children:[(0,v.jsx)(m,{label:`Endpoint`,children:(0,v.jsx)(f,{value:e.endpoint,onChange:t=>e.set({endpoint:t.target.value}),placeholder:`https://s3.amazonaws.com`})}),(0,v.jsx)(m,{label:`Region`,children:(0,v.jsx)(f,{value:e.region,onChange:t=>e.set({region:t.target.value}),placeholder:`us-east-1`})}),(0,v.jsx)(`div`,{className:`md:col-span-2`,children:(0,v.jsx)(m,{label:`Bucket name`,children:(0,v.jsx)(f,{value:e.bucket,onChange:t=>e.set({bucket:t.target.value}),placeholder:`my-bunqueue-backups`})})}),(0,v.jsx)(m,{label:`Access key ID`,children:(0,v.jsx)(f,{value:e.accessKeyId,onChange:t=>e.set({accessKeyId:t.target.value}),placeholder:`AKIA…`})}),(0,v.jsx)(m,{label:`Secret access key`,children:(0,v.jsx)(f,{type:`password`,value:e.secretAccessKey,onChange:t=>e.set({secretAccessKey:t.target.value}),placeholder:`••••••••••••••••`})}),(0,v.jsx)(`p`,{className:`-mt-2 text-xs text-faint md:col-span-2`,children:`Keys are kept in memory only and cleared on reload.`}),(0,v.jsxs)(`div`,{children:[(0,v.jsx)(p,{children:`Backup schedule`}),(0,v.jsxs)(d,{value:e.schedule,onChange:t=>e.set({schedule:t.target.value}),className:`mt-1.5`,title:`Local note only — actual scheduling requires server-side S3 config`,children:[(0,v.jsx)(`option`,{value:`disabled`,children:`Disabled`}),(0,v.jsx)(`option`,{value:`6h`,children:`Every 6 hours`}),(0,v.jsx)(`option`,{value:`12h`,children:`Every 12 hours`}),(0,v.jsx)(`option`,{value:`24h`,children:`Every 24 hours`})]})]}),(0,v.jsx)(m,{label:`Path prefix (optional)`,children:(0,v.jsx)(f,{value:e.pathPrefix,onChange:t=>e.set({pathPrefix:t.target.value}),placeholder:`backups/production/`})})]}),(0,v.jsxs)(`div`,{className:`mt-5 flex flex-wrap items-center gap-2`,children:[(0,v.jsx)(u,{onClick:async()=>{n(null);try{let e=await s.storage();n({ok:!e.data?.diskFull,msg:e.data?.diskFull?`Server disk is full`:`Server disk healthy — this does not validate the S3 credentials`})}catch(e){n({ok:!1,msg:e.message})}},children:`Check server storage`}),(0,v.jsx)(u,{disabled:!0,title:`Trigger a manual backup — requires server-side S3 config`,children:`Backup Now`}),(0,v.jsx)(`span`,{className:`text-xs text-faint`,children:`Saved locally as you type (keys excluded).`}),t&&(0,v.jsx)(`span`,{className:t.ok?`text-xs text-success`:`text-xs text-danger`,children:t.msg})]})]}),(0,v.jsxs)(a,{children:[(0,v.jsx)(`h3`,{className:`mb-4 text-base font-semibold text-fg`,children:`Backup History`}),(0,v.jsx)(l,{icon:(0,v.jsx)(c,{}),title:`No backups yet`,hint:`Configure your S3 connection and run a backup to get started.`})]})]})}export{y as S3BackupPro};
@@ -1,3 +1,3 @@
1
- import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,t as r}from"./react-vendor-B68RYDeC.js";import{A as i,C as a,J as o,K as s,O as c,S as l,U as u,W as d,a as f,d as p,h as m,nt as h,p as g,r as _,u as v,w as y,x as b}from"./index-BjRjwWwc.js";import{i as x,n as S,t as C}from"./form-C-zZyKfB.js";var w=e(n(),1),T=r();function E({children:e}){return(0,T.jsx)(`code`,{className:`rounded bg-surface-2 px-1.5 py-0.5 text-xs text-fg`,children:e})}function D({agentBase:e}){return(0,T.jsx)(l,{children:(0,T.jsxs)(`details`,{className:`group`,children:[(0,T.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center justify-between gap-2`,children:[(0,T.jsx)(`span`,{className:`text-base font-semibold text-fg`,children:`How server control works`}),(0,T.jsx)(`span`,{className:`text-xs text-muted transition-transform group-open:rotate-90`,children:`▶`})]}),(0,T.jsxs)(`div`,{className:`mt-4 space-y-4 text-sm leading-relaxed text-muted`,children:[(0,T.jsxs)(`p`,{children:[`A browser can't start or stop an OS process, so the dashboard talks to a small local`,` `,(0,T.jsx)(`span`,{className:`font-medium text-fg`,children:`control agent`}),` (`,(0,T.jsx)(E,{children:e}),`) that supervises the bunqueue server process — start, stop and restart — and streams its logs back here.`]}),(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`mb-1 font-medium text-fg`,children:`Launch & environment`}),(0,T.jsxs)(`p`,{children:[`The agent runs your `,(0,T.jsx)(`span`,{className:`text-fg`,children:`Command`}),` and injects`,` `,(0,T.jsx)(E,{children:`HTTP_PORT`}),`, `,(0,T.jsx)(E,{children:`TCP_PORT`}),` and `,(0,T.jsx)(E,{children:`BUNQUEUE_DATA_PATH`}),` — plus any `,(0,T.jsx)(`span`,{className:`text-fg`,children:`Environment variables`}),` you add — into its environment. The default `,(0,T.jsx)(E,{children:`bunqueue start`}),` needs a globally-installed binary; pointing the command at a local entry (e.g.`,` `,(0,T.jsx)(E,{children:`bun run /path/to/bunqueue/src/main.ts`}),`) works without one.`]})]}),(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`mb-1 font-medium text-fg`,children:`When changes apply`}),(0,T.jsxs)(`p`,{children:[`Config is editable any time, but `,(0,T.jsx)(`span`,{className:`text-fg`,children:`Command`}),`, ports and data path only take effect on the `,(0,T.jsx)(`span`,{className:`text-fg`,children:`next start/restart`}),` `,`— the running process keeps the config it launched with until then.`]})]}),(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`mb-1 font-medium text-fg`,children:`Data path`}),(0,T.jsxs)(`p`,{children:[`Relative paths resolve against the `,(0,T.jsx)(`span`,{className:`text-fg`,children:`agent's`}),` working directory. SQLite creates the database `,(0,T.jsx)(`span`,{className:`text-fg`,children:`file`}),` but not its parent `,(0,T.jsx)(`span`,{className:`text-fg`,children:`folder`}),` — if start fails with`,` `,(0,T.jsx)(E,{children:`SQLITE_CANTOPEN`}),`, create the directory first or use a path whose folder already exists.`]})]}),(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`mb-1 font-medium text-fg`,children:`Security`}),(0,T.jsxs)(`p`,{children:[`The agent can spawn processes, so it binds `,(0,T.jsx)(E,{children:`127.0.0.1`}),` only, locks CORS to an allowlist (never `,(0,T.jsx)(E,{children:`*`}),`), rejects any disallowed `,(0,T.jsx)(E,{children:`Origin`}),` or`,` `,(0,T.jsx)(E,{children:`Host`}),` with a `,(0,T.jsx)(E,{children:`403`}),` (the latter blocks DNS-rebinding reads), and honours an optional `,(0,T.jsx)(E,{children:`AGENT_TOKEN`}),` on state-changing requests. Keep its port on loopback.`]}),(0,T.jsxs)(`p`,{children:[`If you started the agent with `,(0,T.jsx)(E,{children:`AGENT_TOKEN`}),`, enter that token under`,` `,(0,T.jsx)(`span`,{className:`text-fg`,children:`Settings → Agent token`}),` (or when the lock screen prompts) so start / stop / restart and config changes are authorized.`]})]})]})]})})}var O=0,k=e=>Object.entries(e).map(([e,t])=>({id:O++,key:e,value:t})),A=e=>{let t={};for(let n of e){let e=n.key.trim();e&&(t[e]=n.value)}return t},j=[`AUTH_TOKENS`,`LOG_LEVEL`,`S3_BACKUP_ENABLED`,`S3_BUCKET`,`METRICS_ENABLED`];function M({value:e,onChange:t,disabled:n}){let[r,i]=(0,w.useState)(()=>k(e)),a=e=>{i(e),t(A(e))},o=(e,t)=>a(r.map(n=>n.id===e?{...n,...t}:n)),s=(e=``)=>a([...r,{id:O++,key:e,value:``}]),c=e=>a(r.filter(t=>t.id!==e)),l=new Set(r.map(e=>e.key.trim()).filter(Boolean)),u=r.map(e=>e.key.trim()).filter((e,t,n)=>e&&n.indexOf(e)!==t),d=[...new Set(r.map(e=>e.key.trim()).filter(e=>e&&(/[\s=]/.test(e)||/[a-z]/.test(e))))];return(0,T.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[r.length===0&&(0,T.jsxs)(`p`,{className:`text-xs leading-relaxed text-faint`,children:[`No custom variables. The agent already injects`,` `,(0,T.jsx)(`code`,{className:`rounded bg-surface-2 px-1 py-0.5`,children:`HTTP_PORT`}),`,`,` `,(0,T.jsx)(`code`,{className:`rounded bg-surface-2 px-1 py-0.5`,children:`TCP_PORT`}),` and`,` `,(0,T.jsx)(`code`,{className:`rounded bg-surface-2 px-1 py-0.5`,children:`BUNQUEUE_DATA_PATH`}),`.`]}),r.map(e=>(0,T.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,T.jsx)(`div`,{className:`w-2/5 shrink-0`,children:(0,T.jsx)(S,{className:`font-mono`,placeholder:`KEY`,value:e.key,disabled:n,onChange:t=>o(e.id,{key:t.target.value})})}),(0,T.jsx)(`span`,{className:`text-faint`,children:`=`}),(0,T.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,T.jsx)(S,{className:`font-mono`,placeholder:`value`,value:e.value,disabled:n,onChange:t=>o(e.id,{value:t.target.value})})}),(0,T.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.key||`variable`}`,disabled:n,onClick:()=>c(e.id),className:`shrink-0 rounded-md px-2 py-1 text-xs text-faint transition-colors hover:text-danger disabled:opacity-40`,children:`✕`})]},e.id)),u.length>0&&(0,T.jsxs)(`p`,{className:`text-xs text-warning`,children:[`Duplicate key`,u.length>1?`s`:``,` — the last value wins: `,u.join(`, `)]}),d.length>0&&(0,T.jsxs)(`p`,{className:`text-xs text-faint`,children:[`Unusual key`,d.length>1?`s`:``,` — env names are usually UPPER_SNAKE_CASE with no spaces or "=": `,d.join(`, `),`. Saved as-is.`]}),(0,T.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 pt-1`,children:[(0,T.jsx)(y,{size:`sm`,variant:`ghost`,disabled:n,onClick:()=>s(),children:`+ Add variable`}),j.filter(e=>!l.has(e)).map(e=>(0,T.jsxs)(`button`,{type:`button`,disabled:n,onClick:()=>s(e),className:`rounded-md border border-line bg-surface-2 px-2 py-1 font-mono text-[11px] text-muted transition-colors hover:border-line-strong hover:text-fg disabled:opacity-40`,children:[`+ `,e]},e))]})]})}var N=[`all`,`stdout`,`stderr`,`sys`],P=e=>`${new Date(e).toLocaleTimeString([],{hour12:!1})}.${String(e%1e3).padStart(3,`0`)}`,F=e=>e===`stderr`?`text-danger/90`:e===`sys`?`text-accent/80`:`text-muted`;function I(){let{data:e}=R(),n=(0,w.useMemo)(()=>e?.lines??[],[e]),[r,i]=(0,w.useState)(`all`),[a,s]=(0,w.useState)(``),[u,d]=(0,w.useState)(!0),[f,p]=(0,w.useState)(!1),m=(0,w.useRef)(null),h=(0,w.useMemo)(()=>{let e=a.trim().toLowerCase();return n.map(e=>e.line.includes(`\x1B`)?{...e,line:g(e.line)}:e).filter(t=>(r===`all`||t.stream===r)&&(!e||t.line.toLowerCase().includes(e)))},[n,r,a]);(0,w.useEffect)(()=>{if(!u)return;let e=m.current;e&&(e.scrollTop=e.scrollHeight)},[h.length,u]);let _=(0,w.useMemo)(()=>h.map(e=>f?`${P(e.ts)} [${e.stream}] ${e.line}`:e.line).join(`
1
+ import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,t as r}from"./react-vendor-BcouBxpZ.js";import{A as i,C as a,J as o,K as s,O as c,S as l,U as u,W as d,a as f,d as p,h as m,nt as h,p as g,r as _,u as v,w as y,x as b}from"./index-BOcegTHa.js";import{i as x,n as S,t as C}from"./form-DGinTEEb.js";var w=e(n(),1),T=r();function E({children:e}){return(0,T.jsx)(`code`,{className:`rounded bg-surface-2 px-1.5 py-0.5 text-xs text-fg`,children:e})}function D({agentBase:e}){return(0,T.jsx)(l,{children:(0,T.jsxs)(`details`,{className:`group`,children:[(0,T.jsxs)(`summary`,{className:`flex cursor-pointer list-none items-center justify-between gap-2`,children:[(0,T.jsx)(`span`,{className:`text-base font-semibold text-fg`,children:`How server control works`}),(0,T.jsx)(`span`,{className:`text-xs text-muted transition-transform group-open:rotate-90`,children:`▶`})]}),(0,T.jsxs)(`div`,{className:`mt-4 space-y-4 text-sm leading-relaxed text-muted`,children:[(0,T.jsxs)(`p`,{children:[`A browser can't start or stop an OS process, so the dashboard talks to a small local`,` `,(0,T.jsx)(`span`,{className:`font-medium text-fg`,children:`control agent`}),` (`,(0,T.jsx)(E,{children:e}),`) that supervises the bunqueue server process — start, stop and restart — and streams its logs back here.`]}),(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`mb-1 font-medium text-fg`,children:`Launch & environment`}),(0,T.jsxs)(`p`,{children:[`The agent runs your `,(0,T.jsx)(`span`,{className:`text-fg`,children:`Command`}),` and injects`,` `,(0,T.jsx)(E,{children:`HTTP_PORT`}),`, `,(0,T.jsx)(E,{children:`TCP_PORT`}),` and `,(0,T.jsx)(E,{children:`BUNQUEUE_DATA_PATH`}),` — plus any `,(0,T.jsx)(`span`,{className:`text-fg`,children:`Environment variables`}),` you add — into its environment. The default `,(0,T.jsx)(E,{children:`bunqueue start`}),` needs a globally-installed binary; pointing the command at a local entry (e.g.`,` `,(0,T.jsx)(E,{children:`bun run /path/to/bunqueue/src/main.ts`}),`) works without one.`]})]}),(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`mb-1 font-medium text-fg`,children:`When changes apply`}),(0,T.jsxs)(`p`,{children:[`Config is editable any time, but `,(0,T.jsx)(`span`,{className:`text-fg`,children:`Command`}),`, ports and data path only take effect on the `,(0,T.jsx)(`span`,{className:`text-fg`,children:`next start/restart`}),` `,`— the running process keeps the config it launched with until then.`]})]}),(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`mb-1 font-medium text-fg`,children:`Data path`}),(0,T.jsxs)(`p`,{children:[`Relative paths resolve against the `,(0,T.jsx)(`span`,{className:`text-fg`,children:`agent's`}),` working directory. SQLite creates the database `,(0,T.jsx)(`span`,{className:`text-fg`,children:`file`}),` but not its parent `,(0,T.jsx)(`span`,{className:`text-fg`,children:`folder`}),` — if start fails with`,` `,(0,T.jsx)(E,{children:`SQLITE_CANTOPEN`}),`, create the directory first or use a path whose folder already exists.`]})]}),(0,T.jsxs)(`div`,{children:[(0,T.jsx)(`div`,{className:`mb-1 font-medium text-fg`,children:`Security`}),(0,T.jsxs)(`p`,{children:[`The agent can spawn processes, so it binds `,(0,T.jsx)(E,{children:`127.0.0.1`}),` only, locks CORS to an allowlist (never `,(0,T.jsx)(E,{children:`*`}),`), rejects any disallowed `,(0,T.jsx)(E,{children:`Origin`}),` or`,` `,(0,T.jsx)(E,{children:`Host`}),` with a `,(0,T.jsx)(E,{children:`403`}),` (the latter blocks DNS-rebinding reads), and honours an optional `,(0,T.jsx)(E,{children:`AGENT_TOKEN`}),` on state-changing requests. Keep its port on loopback.`]}),(0,T.jsxs)(`p`,{children:[`If you started the agent with `,(0,T.jsx)(E,{children:`AGENT_TOKEN`}),`, enter that token under`,` `,(0,T.jsx)(`span`,{className:`text-fg`,children:`Settings → Agent token`}),` (or when the lock screen prompts) so start / stop / restart and config changes are authorized.`]})]})]})]})})}var O=0,k=e=>Object.entries(e).map(([e,t])=>({id:O++,key:e,value:t})),A=e=>{let t={};for(let n of e){let e=n.key.trim();e&&(t[e]=n.value)}return t},j=[`AUTH_TOKENS`,`LOG_LEVEL`,`S3_BACKUP_ENABLED`,`S3_BUCKET`,`METRICS_ENABLED`];function M({value:e,onChange:t,disabled:n}){let[r,i]=(0,w.useState)(()=>k(e)),a=e=>{i(e),t(A(e))},o=(e,t)=>a(r.map(n=>n.id===e?{...n,...t}:n)),s=(e=``)=>a([...r,{id:O++,key:e,value:``}]),c=e=>a(r.filter(t=>t.id!==e)),l=new Set(r.map(e=>e.key.trim()).filter(Boolean)),u=r.map(e=>e.key.trim()).filter((e,t,n)=>e&&n.indexOf(e)!==t),d=[...new Set(r.map(e=>e.key.trim()).filter(e=>e&&(/[\s=]/.test(e)||/[a-z]/.test(e))))];return(0,T.jsxs)(`div`,{className:`flex flex-col gap-2`,children:[r.length===0&&(0,T.jsxs)(`p`,{className:`text-xs leading-relaxed text-faint`,children:[`No custom variables. The agent already injects`,` `,(0,T.jsx)(`code`,{className:`rounded bg-surface-2 px-1 py-0.5`,children:`HTTP_PORT`}),`,`,` `,(0,T.jsx)(`code`,{className:`rounded bg-surface-2 px-1 py-0.5`,children:`TCP_PORT`}),` and`,` `,(0,T.jsx)(`code`,{className:`rounded bg-surface-2 px-1 py-0.5`,children:`BUNQUEUE_DATA_PATH`}),`.`]}),r.map(e=>(0,T.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,T.jsx)(`div`,{className:`w-2/5 shrink-0`,children:(0,T.jsx)(S,{className:`font-mono`,placeholder:`KEY`,value:e.key,disabled:n,onChange:t=>o(e.id,{key:t.target.value})})}),(0,T.jsx)(`span`,{className:`text-faint`,children:`=`}),(0,T.jsx)(`div`,{className:`min-w-0 flex-1`,children:(0,T.jsx)(S,{className:`font-mono`,placeholder:`value`,value:e.value,disabled:n,onChange:t=>o(e.id,{value:t.target.value})})}),(0,T.jsx)(`button`,{type:`button`,"aria-label":`Remove ${e.key||`variable`}`,disabled:n,onClick:()=>c(e.id),className:`shrink-0 rounded-md px-2 py-1 text-xs text-faint transition-colors hover:text-danger disabled:opacity-40`,children:`✕`})]},e.id)),u.length>0&&(0,T.jsxs)(`p`,{className:`text-xs text-warning`,children:[`Duplicate key`,u.length>1?`s`:``,` — the last value wins: `,u.join(`, `)]}),d.length>0&&(0,T.jsxs)(`p`,{className:`text-xs text-faint`,children:[`Unusual key`,d.length>1?`s`:``,` — env names are usually UPPER_SNAKE_CASE with no spaces or "=": `,d.join(`, `),`. Saved as-is.`]}),(0,T.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 pt-1`,children:[(0,T.jsx)(y,{size:`sm`,variant:`ghost`,disabled:n,onClick:()=>s(),children:`+ Add variable`}),j.filter(e=>!l.has(e)).map(e=>(0,T.jsxs)(`button`,{type:`button`,disabled:n,onClick:()=>s(e),className:`rounded-md border border-line bg-surface-2 px-2 py-1 font-mono text-[11px] text-muted transition-colors hover:border-line-strong hover:text-fg disabled:opacity-40`,children:[`+ `,e]},e))]})]})}var N=[`all`,`stdout`,`stderr`,`sys`],P=e=>`${new Date(e).toLocaleTimeString([],{hour12:!1})}.${String(e%1e3).padStart(3,`0`)}`,F=e=>e===`stderr`?`text-danger/90`:e===`sys`?`text-accent/80`:`text-muted`;function I(){let{data:e}=R(),n=(0,w.useMemo)(()=>e?.lines??[],[e]),[r,i]=(0,w.useState)(`all`),[a,s]=(0,w.useState)(``),[u,d]=(0,w.useState)(!0),[f,p]=(0,w.useState)(!1),m=(0,w.useRef)(null),h=(0,w.useMemo)(()=>{let e=a.trim().toLowerCase();return n.map(e=>e.line.includes(`\x1B`)?{...e,line:g(e.line)}:e).filter(t=>(r===`all`||t.stream===r)&&(!e||t.line.toLowerCase().includes(e)))},[n,r,a]);(0,w.useEffect)(()=>{if(!u)return;let e=m.current;e&&(e.scrollTop=e.scrollHeight)},[h.length,u]);let _=(0,w.useMemo)(()=>h.map(e=>f?`${P(e.ts)} [${e.stream}] ${e.line}`:e.line).join(`
2
2
  `),[h,f]);return(0,T.jsxs)(l,{padded:!1,className:`overflow-hidden`,children:[(0,T.jsxs)(`div`,{className:`flex flex-wrap items-center gap-2 border-b border-line px-4 py-3`,children:[(0,T.jsx)(`h3`,{className:`mr-1 text-base font-semibold text-fg`,children:`Process logs`}),(0,T.jsx)(x,{options:N,value:r,onChange:i}),(0,T.jsxs)(`div`,{className:`relative min-w-40 flex-1`,children:[(0,T.jsx)(o,{className:`pointer-events-none absolute left-2.5 top-1/2 size-3.5 -translate-y-1/2 text-faint`}),(0,T.jsx)(`input`,{value:a,onChange:e=>s(e.target.value),"aria-label":`Filter log lines`,placeholder:`Filter…`,className:`h-8 w-full rounded-lg border border-line bg-surface-2 pl-8 pr-2 text-xs text-fg placeholder:text-faint focus:border-accent/60 focus:outline-none focus:ring-2 focus:ring-accent/30`})]}),(0,T.jsx)(L,{on:u,onClick:()=>d(e=>!e),label:`Follow`}),(0,T.jsx)(L,{on:f,onClick:()=>p(e=>!e),label:`Times`}),(0,T.jsx)(c,{value:_}),(0,T.jsx)(`button`,{type:`button`,onClick:()=>{let e=new Blob([_],{type:`text/plain`}),t=URL.createObjectURL(e),n=document.createElement(`a`);n.href=t,n.download=`bunqueue-logs-${Date.now()}.log`,n.click(),URL.revokeObjectURL(t)},disabled:h.length===0,className:`rounded-md border border-line bg-surface-2 px-2 py-1 text-xs text-muted transition-colors hover:text-fg disabled:opacity-40`,children:`Download`})]}),(0,T.jsx)(`div`,{ref:m,className:`max-h-80 min-h-40 overflow-y-auto p-4 font-mono text-xs leading-relaxed`,children:h.length===0?(0,T.jsx)(`p`,{className:`text-faint`,children:n.length===0?`No output yet.`:`No lines match the current filter.`}):h.map(e=>(0,T.jsxs)(`div`,{className:t(`whitespace-pre-wrap`,F(e.stream)),children:[f&&(0,T.jsx)(`span`,{className:`mr-2 text-faint`,children:P(e.ts)}),e.line]},e.seq))}),(0,T.jsxs)(`div`,{className:`flex items-center justify-between border-t border-line px-4 py-2 text-[11px] text-faint`,children:[(0,T.jsx)(`span`,{children:h.length===n.length?`${n.length} lines`:`${h.length} of ${n.length} lines`}),(0,T.jsx)(`span`,{children:u?`following tail`:`paused`})]})]})}function L({on:e,onClick:n,label:r}){return(0,T.jsx)(`button`,{type:`button`,onClick:n,"aria-pressed":e,className:t(`rounded-md border px-2 py-1 text-xs transition-colors`,e?`border-accent/40 bg-accent/10 text-accent`:`border-line bg-surface-2 text-muted hover:text-fg`),children:r})}function R(){return i(()=>h.control.logs(),[])}var z={running:{label:`Running`,tone:`text-success`,dot:`bg-emerald-400`},starting:{label:`Starting`,tone:`text-warning`,dot:`bg-amber-400`},stopping:{label:`Stopping`,tone:`text-warning`,dot:`bg-amber-400`},stopped:{label:`Stopped`,tone:`text-danger`,dot:`bg-red-400`}};function B({startedAt:e}){let[,t]=(0,w.useState)(0);return(0,w.useEffect)(()=>{let e=setInterval(()=>t(e=>e+1),1e3);return()=>clearInterval(e)},[]),(0,T.jsx)(T.Fragment,{children:p((Date.now()-e)/1e3)})}function V({label:e,children:t,title:n}){return(0,T.jsxs)(`div`,{className:`min-w-0`,title:n,children:[(0,T.jsx)(`div`,{className:`text-[10px] font-semibold uppercase tracking-wider text-faint`,children:e}),(0,T.jsx)(`div`,{className:`mt-0.5 truncate font-mono text-sm text-fg`,children:t})]})}function H({status:e,agentBase:n,transitioning:r,stale:i=!1,vitals:a=null,busy:o,onStart:l,onStop:p,onRestart:m}){let h=e?.status??`stopped`,g=h===`running`,_=z[h]??z.stopped,v=!!e?.healthy&&!i,b=!g&&e?.exitCode!=null&&e.exitCode!==0,x=e?.runningConfig??e?.config??null,S=`http://localhost:${x?.httpPort??6790}`;return(0,T.jsxs)(`section`,{className:`mb-6 overflow-hidden rounded-xl border border-line bg-surface`,children:[(0,T.jsx)(`div`,{className:t(`h-0.5 bg-gradient-to-r to-transparent`,g&&v?`from-emerald-400/80 via-emerald-400/25`:g||r?`from-amber-400/80 via-amber-400/25`:`from-red-400/70 via-red-400/20`)}),(0,T.jsxs)(`div`,{className:`flex flex-col gap-5 p-5 lg:flex-row lg:items-center lg:justify-between`,children:[(0,T.jsxs)(`div`,{className:`flex items-center gap-4`,children:[(0,T.jsxs)(`span`,{className:`relative flex size-3.5 shrink-0`,children:[g&&v&&(0,T.jsx)(`span`,{className:`absolute inline-flex size-full rounded-full bg-emerald-400 opacity-50 motion-safe:animate-ping`}),(0,T.jsx)(`span`,{className:t(`relative inline-flex size-3.5 rounded-full`,_.dot)})]}),(0,T.jsxs)(`div`,{className:`min-w-0`,children:[(0,T.jsxs)(`div`,{className:`flex flex-wrap items-baseline gap-x-3 gap-y-1`,children:[(0,T.jsx)(`span`,{className:t(`text-2xl font-bold tracking-tight`,_.tone),children:r&&o?`${o}…`:_.label}),e?.version&&(0,T.jsxs)(`span`,{className:`font-mono text-xs text-muted`,children:[`bunqueue v`,e.version]}),b&&(0,T.jsxs)(`span`,{className:`rounded-full bg-red-500/15 px-2 py-0.5 font-mono text-[11px] font-medium text-danger`,children:[`crashed · exit `,e?.exitCode]})]}),(0,T.jsx)(`div`,{className:`mt-1 font-mono text-xs text-muted`,children:i?(0,T.jsxs)(`span`,{className:`text-warning`,children:[`last known: pid `,e?.pid??`—`,` — agent unreachable, state may have changed`]}):g?(0,T.jsxs)(T.Fragment,{children:[v?`healthy`:`waiting for health…`,` · pid `,e?.pid??`—`,` · up`,` `,e?.startedAt?(0,T.jsx)(B,{startedAt:e.startedAt}):`—`]}):`process not running — start it below or point the dashboard at an external server`})]})]}),(0,T.jsxs)(`div`,{className:`flex shrink-0 items-center gap-2`,children:[(0,T.jsxs)(y,{variant:`success`,disabled:g||r||i,onClick:l,children:[(0,T.jsx)(d,{className:`size-4`}),` Start`]}),(0,T.jsxs)(y,{variant:`warning`,disabled:!g||r||i,onClick:p,children:[(0,T.jsx)(u,{className:`size-4`}),` Stop`]}),(0,T.jsxs)(y,{disabled:r||i,onClick:m,children:[(0,T.jsx)(s,{className:`size-4`}),` Restart`]})]})]}),(0,T.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 border-t border-line bg-surface-2/30 px-5 py-4 md:grid-cols-3 xl:grid-cols-7`,children:[(0,T.jsx)(V,{label:`Memory`,children:a?.memory?.rss==null?(0,T.jsx)(`span`,{className:`text-faint`,children:`—`}):(0,T.jsxs)(`span`,{title:`heap ${a.memory.heapUsed??`?`} / ${a.memory.heapTotal??`?`} MB`,children:[a.memory.rss,` MB rss`]})}),(0,T.jsx)(V,{label:`Connections`,children:a?.connections?`${a.connections.tcp??0} tcp · ${a.connections.ws??0} ws · ${a.connections.sse??0} sse`:(0,T.jsx)(`span`,{className:`text-faint`,children:`—`})}),(0,T.jsx)(V,{label:`API endpoint`,title:S,children:g?(0,T.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,T.jsx)(`a`,{href:`${S}/health`,target:`_blank`,rel:`noreferrer`,className:`truncate text-accent hover:underline`,children:S}),(0,T.jsx)(c,{value:S})]}):(0,T.jsx)(`span`,{className:`text-faint`,children:S})}),(0,T.jsx)(V,{label:`Ports`,children:x?`${x.httpPort} http · ${x.tcpPort} tcp`:`—`}),(0,T.jsx)(V,{label:`Started`,children:g&&e?.startedAt?f(e.startedAt):`—`}),(0,T.jsx)(V,{label:`Control agent`,title:n,children:n.replace(/^https?:\/\//,``)}),(0,T.jsx)(V,{label:`Launch command`,title:x?.command,children:x?.command??`—`})]})]})}var U=[{key:`size`,label:`Database`,color:`bg-accent`},{key:`walSize`,label:`WAL`,color:`bg-amber-400`},{key:`shmSize`,label:`SHM`,color:`bg-zinc-500`}];function W({db:e}){let n=e.totalSize||0;return(0,T.jsxs)(l,{children:[(0,T.jsxs)(`div`,{className:`mb-1 flex items-baseline justify-between gap-2`,children:[(0,T.jsx)(`h3`,{className:`text-base font-semibold text-fg`,children:`Storage`}),(0,T.jsx)(`span`,{className:`font-mono text-xs text-muted`,children:e.exists?`${_(n)} on disk`:`not created yet`})]}),(0,T.jsxs)(`p`,{className:`mb-4 flex items-center gap-1.5 truncate font-mono text-xs text-faint`,title:e.path,children:[(0,T.jsx)(`span`,{className:`truncate`,children:e.path}),(0,T.jsx)(c,{value:e.path})]}),e.exists&&n>0?(0,T.jsxs)(T.Fragment,{children:[(0,T.jsx)(`div`,{className:`flex h-2.5 overflow-hidden rounded-full bg-surface-2`,children:U.map(r=>{let i=e[r.key];return i?(0,T.jsx)(`div`,{className:t(`h-full`,r.color),style:{width:`${i/n*100}%`},title:`${r.label}: ${_(i)}`},r.key):null})}),(0,T.jsxs)(`div`,{className:`mt-3 flex flex-wrap items-center gap-x-5 gap-y-1.5 font-mono text-[11px] text-faint`,children:[U.map(n=>(0,T.jsxs)(`span`,{className:`flex items-center gap-1.5`,children:[(0,T.jsx)(`span`,{className:t(`size-2 rounded-full`,n.color)}),n.label,` `,(0,T.jsx)(`span`,{className:`text-fg`,children:_(e[n.key])})]},n.key)),e.mtimeMs?(0,T.jsxs)(`span`,{className:`ml-auto`,children:[`written `,v(e.mtimeMs)]}):null]})]}):(0,T.jsx)(`p`,{className:`rounded-lg border border-dashed border-line px-4 py-6 text-center text-sm text-faint`,children:`The database appears here after the first start — SQLite creates the file at the configured data path.`})]})}function G(){let{data:e,error:t,refetch:n}=i(()=>h.control.status(),[]),[r,o]=(0,w.useState)(null),[s,c]=(0,w.useState)(null),u=e?.status===`running`,{data:d}=i(()=>u?h.health():Promise.resolve(null),[u]),f=u?d??null:null,p=f?.connections?` This drops ${f.connections.tcp??0} TCP / ${f.connections.ws??0} WS connections; in-flight jobs are interrupted.`:` In-flight jobs are interrupted.`,g=async(e,t,r)=>{if(!(r&&!window.confirm(r))){o(e),c(null);try{await t(),await n()}catch(e){c(e.message)}finally{o(null)}}};if(t&&!e)return(0,T.jsxs)(`div`,{children:[(0,T.jsx)(m,{title:`Server`,description:`Start, stop and restart the bunqueue server.`}),(0,T.jsx)(b,{message:`Control agent unreachable — server lifecycle controls are unavailable.`,onRetry:n}),(0,T.jsxs)(l,{children:[(0,T.jsx)(a,{title:`Control agent not running`}),(0,T.jsxs)(`p`,{className:`text-sm text-muted`,children:[`The local control agent is unreachable at`,` `,(0,T.jsx)(`code`,{className:`rounded bg-surface-2 px-1.5 py-0.5 text-xs`,children:h.agentBase}),`. It manages the bunqueue server process (start / stop / restart). Start it with:`]}),(0,T.jsxs)(`pre`,{className:`mt-3 overflow-x-auto rounded-lg border border-line bg-surface-2 px-3 py-2 text-xs`,children:[`bun start`,` `,`# agent + dashboard together (recommended)`,`
3
3
  `,`bun run agent`,` `,`# agent only, if the dashboard is already running`]}),(0,T.jsx)(`p`,{className:`mt-3 text-xs text-faint`,children:`This page reconnects automatically once the agent is up — no reload needed.`})]})]});let _=e?.status??`stopped`,v=_===`running`,y=_===`starting`||_===`stopping`||r!=null,x=t!=null&&e!=null;return(0,T.jsxs)(`div`,{children:[(0,T.jsx)(m,{title:`Server`,description:`Supervise the bunqueue server process — lifecycle, configuration, storage and logs.`}),s&&(0,T.jsx)(`div`,{role:`status`,className:`mb-4 rounded-lg border border-red-500/20 bg-red-500/5 px-4 py-2 text-sm text-danger`,children:s}),x&&(0,T.jsx)(`div`,{className:`mb-4 rounded-lg border border-amber-500/20 bg-amber-500/5 px-4 py-2 text-sm text-warning`,children:`Control agent unreachable — showing last known state. Lifecycle actions are disabled until it responds again.`}),(0,T.jsx)(H,{status:e,agentBase:h.agentBase,stale:x,vitals:f,transitioning:y,busy:r,onStart:()=>g(`starting`,()=>h.control.start()),onStop:()=>g(`stopping`,()=>h.control.stop(),`Stop the bunqueue server?${p}`),onRestart:()=>g(`restarting`,()=>h.control.restart(),`Restart the bunqueue server?${p}`)}),(0,T.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,T.jsx)(K,{status:e,onSaved:n,running:v,transitioning:y}),(0,T.jsxs)(`div`,{className:`flex flex-col gap-6`,children:[e?.db&&(0,T.jsx)(W,{db:e.db}),(0,T.jsx)(I,{})]})]}),(0,T.jsx)(`div`,{className:`mt-6`,children:(0,T.jsx)(D,{agentBase:h.agentBase})})]})}function K({status:e,onSaved:t,running:n,transitioning:r}){let[i,o]=(0,w.useState)(null),[c,u]=(0,w.useState)(!1),[d,f]=(0,w.useState)(!1),[p,m]=(0,w.useState)(null);(0,w.useEffect)(()=>{e?.config&&!i&&o(e.config)},[e,i]);let g=i??e?.config??null;if(!g)return(0,T.jsx)(l,{children:`Loading…`});let _=e=>o({...g,...e}),v=e?.runningConfig??null,b=(e={})=>JSON.stringify(Object.keys(e).sort().map(t=>[t,e[t]])),x=[];v!=null&&(v.command!==g.command&&x.push(`command`),v.httpPort!==g.httpPort&&x.push(`HTTP port`),v.tcpPort!==g.tcpPort&&x.push(`TCP port`),v.dataPath!==g.dataPath&&x.push(`data path`),b(v.extraEnv)!==b(g.extraEnv)&&x.push(`environment variables`));let E=n&&x.length>0,D=r||d,O=()=>{u(!0),setTimeout(()=>u(!1),2e3)},k=()=>{let e=e=>Number.isInteger(e)&&e>=1&&e<=65535;return e(g.httpPort)?e(g.tcpPort)?g.httpPort===g.tcpPort?`HTTP and TCP ports must differ`:null:`TCP port must be an integer between 1 and 65535`:`HTTP port must be an integer between 1 and 65535`},A=async()=>{let e=k();if(e){m(e);return}m(null);try{await h.control.setConfig(g),O(),t()}catch(e){m(e.message)}};return(0,T.jsxs)(l,{children:[(0,T.jsx)(a,{title:`Configuration`}),(0,T.jsx)(`p`,{className:`mb-3 text-xs text-muted`,children:n?`Ports and data path apply on the next restart — edit freely, then restart.`:`Edit and save; the config is used the next time the server starts.`}),(0,T.jsxs)(`form`,{className:`flex flex-col gap-3`,onSubmit:e=>{e.preventDefault(),A()},children:[(0,T.jsx)(C,{label:`Command`,hint:`The exact command the agent runs to launch bunqueue. It receives HTTP_PORT, TCP_PORT and BUNQUEUE_DATA_PATH in its environment. The default needs a global 'bunqueue' binary — or point it at a local entry, e.g. bun run /path/to/bunqueue/src/main.ts.`,children:(0,T.jsx)(S,{value:g.command,disabled:D,onChange:e=>_({command:e.target.value}),placeholder:`bunqueue start`})}),(0,T.jsxs)(`div`,{className:`grid grid-cols-2 gap-3`,children:[(0,T.jsx)(C,{label:`HTTP port`,hint:`Dashboard API + SSE.`,children:(0,T.jsx)(S,{type:`number`,min:1,max:65535,value:g.httpPort,disabled:D,onChange:e=>_({httpPort:Number(e.target.value)})})}),(0,T.jsx)(C,{label:`TCP port`,hint:`Binary protocol. Must differ from HTTP.`,children:(0,T.jsx)(S,{type:`number`,min:1,max:65535,value:g.tcpPort,disabled:D,onChange:e=>_({tcpPort:Number(e.target.value)})})})]}),(0,T.jsx)(C,{label:`Data path`,hint:`SQLite database file, relative to the agent's working directory. The parent folder must already exist — SQLite creates the file, not the directory.`,children:(0,T.jsx)(S,{value:g.dataPath,disabled:D,onChange:e=>_({dataPath:e.target.value})})}),(0,T.jsx)(C,{label:`Environment variables`,hint:`Injected into the server process on start, on top of the ports + data path. Applies on the next restart.`,children:(0,T.jsx)(M,{value:g.extraEnv??{},onChange:e=>_({extraEnv:e}),disabled:D})}),(0,T.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,T.jsx)(y,{type:`submit`,variant:`accent`,size:`sm`,disabled:D,children:`Save config`}),n&&(0,T.jsxs)(y,{variant:`warning`,size:`sm`,disabled:D,onClick:async()=>{let e=k();if(e){m(e);return}let n=x.length>0?` Changed: ${x.join(`, `)}.`:``;if(window.confirm(`Save configuration and restart the server to apply it?${n}`)){m(null),f(!0);try{await h.control.setConfig(g),await h.control.restart(),O(),t()}catch(e){m(e.message)}finally{f(!1)}}},children:[(0,T.jsx)(s,{className:`size-3.5`}),` Save & restart`]}),E&&!c&&(0,T.jsx)(`span`,{className:`text-xs text-warning`,children:`Restart to apply changes`}),c&&(0,T.jsx)(`span`,{role:`status`,className:`text-xs text-success`,children:`Saved`}),p&&(0,T.jsx)(`span`,{role:`status`,className:`text-xs text-danger`,children:p})]})]})]})}export{G as ServerControl};
@@ -1 +1 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-B68RYDeC.js";import{i as r}from"./connectionStore-B-hNUqwK.js";import{B as i,C as a,S as o,T as s,Z as c,h as l,w as u}from"./index-BjRjwWwc.js";import{a as d,n as f,t as p}from"./form-C-zZyKfB.js";var m=e(t(),1),h=n(),g=[[`1000`,`1 second`],[`2000`,`2 seconds`],[`3000`,`3 seconds`],[`5000`,`5 seconds`],[`10000`,`10 seconds`]];function _(e){if(e.startsWith(`/`))return!0;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function v(){let{baseUrl:e,token:t,agentToken:n,refreshMs:v,setBaseUrl:y,setToken:b,setAgentToken:x,setRefreshMs:S}=r(),{theme:C,setTheme:w}=c(),[T,E]=(0,m.useState)(!1),[D,O]=(0,m.useState)(null),[k,A]=(0,m.useState)(e),[j,M]=(0,m.useState)(t),[N,P]=(0,m.useState)(n),[F,I]=(0,m.useState)(!1),[L,R]=(0,m.useState)(!1),[z,B]=(0,m.useState)(null),[V,H]=(0,m.useState)(!1);return(0,h.jsxs)(`div`,{children:[(0,h.jsx)(l,{title:`Settings`,description:`Connection and appearance.`}),(0,h.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,h.jsxs)(o,{children:[(0,h.jsx)(a,{title:`Connection`}),(0,h.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,h.jsx)(p,{label:`Server URL`,children:(0,h.jsx)(f,{value:k,onChange:e=>{A(e.target.value),B(null)},placeholder:`/api or https://queue.example.com`})}),z&&(0,h.jsx)(`p`,{className:`-mt-2 text-xs text-danger`,children:z}),(0,h.jsxs)(`p`,{className:`-mt-2 text-xs text-faint`,children:[`Use `,(0,h.jsx)(`code`,{className:`font-mono`,children:`/api`}),` in dev (proxied to localhost:6790), or the server origin in production.`]}),(0,h.jsx)(p,{label:`Bearer token (optional)`,hint:`Kept in memory only — re-enter after reload, or set VITE_BUNQUEUE_TOKEN.`,children:(0,h.jsxs)(`div`,{className:`relative`,children:[(0,h.jsx)(f,{type:F?`text`:`password`,value:j,onChange:e=>M(e.target.value),placeholder:`only if AUTH_TOKENS is set`,className:`pr-10`}),(0,h.jsx)(s,{"aria-label":F?`Hide token`:`Show token`,className:`absolute right-0.5 top-1/2 -translate-y-1/2`,onClick:()=>I(e=>!e),children:(0,h.jsx)(i,{className:`size-4`})})]})}),(0,h.jsx)(p,{label:`Agent token (optional)`,hint:`Only if the control agent runs with AGENT_TOKEN. Memory only — or set VITE_BUNQUEUE_AGENT_TOKEN.`,children:(0,h.jsxs)(`div`,{className:`relative`,children:[(0,h.jsx)(f,{type:L?`text`:`password`,value:N,onChange:e=>P(e.target.value),placeholder:`only if AGENT_TOKEN is set`,className:`pr-10`}),(0,h.jsx)(s,{"aria-label":L?`Hide agent token`:`Show agent token`,className:`absolute right-0.5 top-1/2 -translate-y-1/2`,onClick:()=>R(e=>!e),children:(0,h.jsx)(i,{className:`size-4`})})]})}),(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,h.jsx)(u,{variant:`accent`,onClick:()=>{let e=k.trim();if(!_(e)){B(`Must be an http(s) URL or a path starting with '/'.`);return}B(null),y(e),b(j),x(N),H(!0),setTimeout(()=>H(!1),2e3)},children:`Save`}),(0,h.jsx)(u,{onClick:async()=>{let e=k.trim().replace(/\/+$/,``);if(!_(e||`/`)){O({ok:!1,msg:`Must be an http(s) URL or a path starting with '/'.`});return}E(!0),O(null);let t=performance.now();try{let n=await fetch(`${e}/health`,{headers:j.trim()?{Authorization:`Bearer ${j.trim()}`}:void 0});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json(),i=Math.round(performance.now()-t);O({ok:r.ok!==!1,msg:`Connected in ${i}ms${r.version?` · bunqueue v${r.version}`:``}`})}catch(e){O({ok:!1,msg:e.message})}finally{E(!1)}},disabled:T,children:T?`Testing…`:`Test connection`}),V&&(0,h.jsx)(`span`,{className:`text-sm text-success`,children:`Saved ✓`}),D&&(0,h.jsx)(`span`,{className:D.ok?`text-sm text-success`:`text-sm text-danger`,children:D.msg})]}),(0,h.jsx)(`p`,{className:`-mt-1 text-xs text-faint`,children:`Test checks the values above as typed. Saving repoints every page at the new server immediately.`})]})]}),(0,h.jsxs)(o,{children:[(0,h.jsx)(a,{title:`Appearance & refresh`}),(0,h.jsxs)(`div`,{className:`grid grid-cols-2 gap-4`,children:[(0,h.jsx)(p,{label:`Theme`,children:(0,h.jsxs)(d,{value:C,onChange:e=>w(e.target.value),children:[(0,h.jsx)(`option`,{value:`dark`,children:`Dark`}),(0,h.jsx)(`option`,{value:`light`,children:`Light`})]})}),(0,h.jsx)(p,{label:`Refresh interval`,children:(0,h.jsx)(d,{value:String(v),onChange:e=>S(Number(e.target.value)),children:g.map(([e,t])=>(0,h.jsx)(`option`,{value:e,children:t},e))})})]})]})]})]})}export{v as Settings};
1
+ import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-BcouBxpZ.js";import{i as r}from"./connectionStore-Ci04lJmR.js";import{B as i,C as a,S as o,T as s,Z as c,h as l,w as u}from"./index-BOcegTHa.js";import{a as d,n as f,t as p}from"./form-DGinTEEb.js";var m=e(t(),1),h=n(),g=[[`1000`,`1 second`],[`2000`,`2 seconds`],[`3000`,`3 seconds`],[`5000`,`5 seconds`],[`10000`,`10 seconds`]];function _(e){if(e.startsWith(`/`))return!0;try{let t=new URL(e);return t.protocol===`http:`||t.protocol===`https:`}catch{return!1}}function v(){let{baseUrl:e,token:t,agentToken:n,refreshMs:v,setBaseUrl:y,setToken:b,setAgentToken:x,setRefreshMs:S}=r(),{theme:C,setTheme:w}=c(),[T,E]=(0,m.useState)(!1),[D,O]=(0,m.useState)(null),[k,A]=(0,m.useState)(e),[j,M]=(0,m.useState)(t),[N,P]=(0,m.useState)(n),[F,I]=(0,m.useState)(!1),[L,R]=(0,m.useState)(!1),[z,B]=(0,m.useState)(null),[V,H]=(0,m.useState)(!1);return(0,h.jsxs)(`div`,{children:[(0,h.jsx)(l,{title:`Settings`,description:`Connection and appearance.`}),(0,h.jsxs)(`div`,{className:`grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,h.jsxs)(o,{children:[(0,h.jsx)(a,{title:`Connection`}),(0,h.jsxs)(`div`,{className:`flex flex-col gap-4`,children:[(0,h.jsx)(p,{label:`Server URL`,children:(0,h.jsx)(f,{value:k,onChange:e=>{A(e.target.value),B(null)},placeholder:`/api or https://queue.example.com`})}),z&&(0,h.jsx)(`p`,{className:`-mt-2 text-xs text-danger`,children:z}),(0,h.jsxs)(`p`,{className:`-mt-2 text-xs text-faint`,children:[`Use `,(0,h.jsx)(`code`,{className:`font-mono`,children:`/api`}),` in dev (proxied to localhost:6790), or the server origin in production.`]}),(0,h.jsx)(p,{label:`Bearer token (optional)`,hint:`Kept in memory only — re-enter after reload, or set VITE_BUNQUEUE_TOKEN.`,children:(0,h.jsxs)(`div`,{className:`relative`,children:[(0,h.jsx)(f,{type:F?`text`:`password`,value:j,onChange:e=>M(e.target.value),placeholder:`only if AUTH_TOKENS is set`,className:`pr-10`}),(0,h.jsx)(s,{"aria-label":F?`Hide token`:`Show token`,className:`absolute right-0.5 top-1/2 -translate-y-1/2`,onClick:()=>I(e=>!e),children:(0,h.jsx)(i,{className:`size-4`})})]})}),(0,h.jsx)(p,{label:`Agent token (optional)`,hint:`Only if the control agent runs with AGENT_TOKEN. Memory only — or set VITE_BUNQUEUE_AGENT_TOKEN.`,children:(0,h.jsxs)(`div`,{className:`relative`,children:[(0,h.jsx)(f,{type:L?`text`:`password`,value:N,onChange:e=>P(e.target.value),placeholder:`only if AGENT_TOKEN is set`,className:`pr-10`}),(0,h.jsx)(s,{"aria-label":L?`Hide agent token`:`Show agent token`,className:`absolute right-0.5 top-1/2 -translate-y-1/2`,onClick:()=>R(e=>!e),children:(0,h.jsx)(i,{className:`size-4`})})]})}),(0,h.jsxs)(`div`,{className:`flex flex-wrap items-center gap-3`,children:[(0,h.jsx)(u,{variant:`accent`,onClick:()=>{let e=k.trim();if(!_(e)){B(`Must be an http(s) URL or a path starting with '/'.`);return}B(null),y(e),b(j),x(N),H(!0),setTimeout(()=>H(!1),2e3)},children:`Save`}),(0,h.jsx)(u,{onClick:async()=>{let e=k.trim().replace(/\/+$/,``);if(!_(e||`/`)){O({ok:!1,msg:`Must be an http(s) URL or a path starting with '/'.`});return}E(!0),O(null);let t=performance.now();try{let n=await fetch(`${e}/health`,{headers:j.trim()?{Authorization:`Bearer ${j.trim()}`}:void 0});if(!n.ok)throw Error(`HTTP ${n.status}`);let r=await n.json(),i=Math.round(performance.now()-t);O({ok:r.ok!==!1,msg:`Connected in ${i}ms${r.version?` · bunqueue v${r.version}`:``}`})}catch(e){O({ok:!1,msg:e.message})}finally{E(!1)}},disabled:T,children:T?`Testing…`:`Test connection`}),V&&(0,h.jsx)(`span`,{className:`text-sm text-success`,children:`Saved ✓`}),D&&(0,h.jsx)(`span`,{className:D.ok?`text-sm text-success`:`text-sm text-danger`,children:D.msg})]}),(0,h.jsx)(`p`,{className:`-mt-1 text-xs text-faint`,children:`Test checks the values above as typed. Saving repoints every page at the new server immediately.`})]})]}),(0,h.jsxs)(o,{children:[(0,h.jsx)(a,{title:`Appearance & refresh`}),(0,h.jsxs)(`div`,{className:`grid grid-cols-2 gap-4`,children:[(0,h.jsx)(p,{label:`Theme`,children:(0,h.jsxs)(d,{value:C,onChange:e=>w(e.target.value),children:[(0,h.jsx)(`option`,{value:`dark`,children:`Dark`}),(0,h.jsx)(`option`,{value:`light`,children:`Light`})]})}),(0,h.jsx)(p,{label:`Refresh interval`,children:(0,h.jsx)(d,{value:String(v),onChange:e=>S(Number(e.target.value)),children:g.map(([e,t])=>(0,h.jsx)(`option`,{value:e,children:t},e))})})]})]})]})]})}export{v as Settings};
@@ -0,0 +1 @@
1
+ import{t as e}from"./react-vendor-BcouBxpZ.js";import{A as t,C as n,S as r,b as i,c as a,d as o,h as s,j as c,m as l,r as u,u as d,x as f}from"./index-BOcegTHa.js";var p=e(),m={stats:{waiting:0,active:0,delayed:0,completed:0,dlq:0,totalPushed:0,totalPulled:0,totalCompleted:0,totalFailed:0,uptime:0},memory:{heapUsed:0,heapTotal:0,rss:0},workers:{total:0,active:0},crons:{total:0},storage:{}};function h(){let{data:e,error:h,loading:_,refetch:v}=t(()=>c.overview(),[]);if(_&&!e&&!h)return(0,p.jsx)(i,{label:`Loading usage…`});let{stats:y,memory:b,workers:x,crons:S,storage:C}=e??m;return(0,p.jsxs)(`div`,{children:[(0,p.jsx)(s,{title:`Usage`,description:`Cumulative resource usage on the connected server.`,live:!0}),h&&(0,p.jsx)(f,{onRetry:v}),(0,p.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,p.jsx)(l,{label:`Jobs Pushed`,value:a(y.totalPushed)}),(0,p.jsx)(l,{label:`Jobs Completed`,value:a(y.totalCompleted),tone:`green`}),(0,p.jsx)(l,{label:`Jobs Failed`,value:a(y.totalFailed),tone:y.totalFailed?`red`:`default`}),(0,p.jsx)(l,{label:`Jobs Pulled`,value:a(y.totalPulled),tone:`blue`})]}),(0,p.jsxs)(`div`,{className:`mt-6 grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,p.jsxs)(r,{children:[(0,p.jsx)(n,{title:`Runtime`}),(0,p.jsxs)(`dl`,{className:`divide-y divide-line text-sm`,children:[(0,p.jsx)(g,{label:`Uptime`,value:o(y.uptime/1e3)}),(0,p.jsx)(g,{label:`Heap used`,value:u(b.heapUsed*1024*1024)}),(0,p.jsx)(g,{label:`RSS`,value:u(b.rss*1024*1024)}),(0,p.jsx)(g,{label:`Workers`,value:`${x.active} active / ${x.total}`}),(0,p.jsx)(g,{label:`Cron jobs`,value:String(S.total)})]})]}),(0,p.jsxs)(r,{children:[(0,p.jsx)(n,{title:`Storage`}),(0,p.jsxs)(`dl`,{className:`divide-y divide-line text-sm`,children:[(0,p.jsx)(g,{label:`Status`,value:C.diskFull?`Disk full`:`Healthy`}),(0,p.jsx)(g,{label:`Disk full since`,value:C.diskFull?d(C.since):`—`}),C.error?(0,p.jsx)(g,{label:`Error`,value:String(C.error)}):null]})]})]})]})}function g({label:e,value:t,mono:n}){return(0,p.jsxs)(`div`,{className:`flex items-center justify-between py-2.5`,children:[(0,p.jsx)(`dt`,{className:`text-muted`,children:e}),(0,p.jsx)(`dd`,{className:n?`font-mono text-xs text-fg`:`font-medium text-fg`,children:t})]})}export{h as Usage};
@@ -1 +1 @@
1
- import{t as e}from"./react-vendor-B68RYDeC.js";import{A as t,C as n,S as r,b as i,c as a,d as o,h as s,l as c,m as l,n as u,nt as d,r as f,u as p,x as m}from"./index-BjRjwWwc.js";var h=e(),g={overview:{stats:{waiting:0,active:0,delayed:0,completed:0,dlq:0,totalPushed:0,totalPulled:0,totalCompleted:0,totalFailed:0,uptime:0},memory:{heapUsed:0,heapTotal:0,rss:0},crons:{total:0}},storage:{},failedTotal:0};function _(){let{data:e,error:_,loading:y,refetch:b}=t(async()=>{let[e,t,n]=await Promise.all([d.overview(),d.storage(),d.queuesSummary()]),r=n.reduce((e,t)=>e+(t.counts?.failed??0),0);return{overview:e,storage:t.data??{},failedTotal:r}},[]);if(y&&!e&&!_)return(0,h.jsx)(i,{label:`Loading usage…`});let x=e??g,{stats:S,memory:C,crons:w}=x.overview,{storage:T,failedTotal:E}=x,D=u(S.completed,E),O=S.uptime?o(S.uptime/1e3):`—`;return(0,h.jsxs)(`div`,{children:[(0,h.jsx)(s,{title:`Usage`,description:`Cumulative resource usage on the connected server.`,live:!0}),_&&(0,h.jsx)(m,{onRetry:b}),(0,h.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-6`,children:[(0,h.jsx)(l,{label:`Completed`,value:a(S.completed),tone:`green`}),(0,h.jsx)(l,{label:`Failed`,value:a(E),tone:E?`red`:`default`}),(0,h.jsx)(l,{label:`Waiting`,value:a(S.waiting),tone:`amber`}),(0,h.jsx)(l,{label:`Active`,value:a(S.active),tone:`blue`}),(0,h.jsx)(l,{label:`Error Rate`,value:D==null?`—`:c(D),tone:D==null?`default`:D>.05?`red`:`green`}),(0,h.jsx)(l,{label:`Uptime`,value:O})]}),(0,h.jsxs)(`div`,{className:`mt-6 grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,h.jsxs)(r,{children:[(0,h.jsx)(n,{title:`Runtime`}),(0,h.jsxs)(`dl`,{className:`divide-y divide-line text-sm`,children:[(0,h.jsx)(v,{label:`Jobs pushed (since restart)`,value:a(S.totalPushed)}),(0,h.jsx)(v,{label:`Jobs pulled (since restart)`,value:a(S.totalPulled)}),(0,h.jsx)(v,{label:`Heap used`,value:f(C.heapUsed*1024*1024)}),(0,h.jsx)(v,{label:`RSS`,value:f(C.rss*1024*1024)}),(0,h.jsx)(v,{label:`Cron jobs`,value:String(w.total)})]})]}),(0,h.jsxs)(r,{children:[(0,h.jsx)(n,{title:`Storage`}),T.diskFull?(0,h.jsxs)(`div`,{className:`rounded-lg border border-red-500/25 bg-red-500/[0.06] px-4 py-3`,children:[(0,h.jsx)(`div`,{className:`font-semibold text-danger`,children:`Disk full — writes suspended`}),T.error&&(0,h.jsx)(`div`,{className:`mt-1 text-xs text-muted`,children:T.error}),T.since!=null&&(0,h.jsxs)(`div`,{className:`mt-1 text-xs text-faint`,children:[`since `,p(T.since)]})]}):(0,h.jsxs)(`div`,{className:`rounded-lg border border-emerald-500/25 bg-emerald-500/[0.06] px-4 py-3`,children:[(0,h.jsx)(`div`,{className:`font-semibold text-success`,children:`Healthy`}),(0,h.jsx)(`div`,{className:`mt-1 text-xs text-faint`,children:`Disk writes are being accepted.`})]})]})]})]})}function v({label:e,value:t}){return(0,h.jsxs)(`div`,{className:`flex items-center justify-between py-2.5`,children:[(0,h.jsx)(`dt`,{className:`text-muted`,children:e}),(0,h.jsx)(`dd`,{className:`font-medium text-fg`,children:t})]})}export{_ as UsagePro};
1
+ import{t as e}from"./react-vendor-BcouBxpZ.js";import{A as t,C as n,S as r,b as i,c as a,d as o,h as s,l as c,m as l,n as u,nt as d,r as f,u as p,x as m}from"./index-BOcegTHa.js";var h=e(),g={overview:{stats:{waiting:0,active:0,delayed:0,completed:0,dlq:0,totalPushed:0,totalPulled:0,totalCompleted:0,totalFailed:0,uptime:0},memory:{heapUsed:0,heapTotal:0,rss:0},crons:{total:0}},storage:{},failedTotal:0};function _(){let{data:e,error:_,loading:y,refetch:b}=t(async()=>{let[e,t,n]=await Promise.all([d.overview(),d.storage(),d.queuesSummary()]),r=n.reduce((e,t)=>e+(t.counts?.failed??0),0);return{overview:e,storage:t.data??{},failedTotal:r}},[]);if(y&&!e&&!_)return(0,h.jsx)(i,{label:`Loading usage…`});let x=e??g,{stats:S,memory:C,crons:w}=x.overview,{storage:T,failedTotal:E}=x,D=u(S.completed,E),O=S.uptime?o(S.uptime/1e3):`—`;return(0,h.jsxs)(`div`,{children:[(0,h.jsx)(s,{title:`Usage`,description:`Cumulative resource usage on the connected server.`,live:!0}),_&&(0,h.jsx)(m,{onRetry:b}),(0,h.jsxs)(`div`,{className:`grid grid-cols-2 gap-4 md:grid-cols-3 xl:grid-cols-6`,children:[(0,h.jsx)(l,{label:`Completed`,value:a(S.completed),tone:`green`}),(0,h.jsx)(l,{label:`Failed`,value:a(E),tone:E?`red`:`default`}),(0,h.jsx)(l,{label:`Waiting`,value:a(S.waiting),tone:`amber`}),(0,h.jsx)(l,{label:`Active`,value:a(S.active),tone:`blue`}),(0,h.jsx)(l,{label:`Error Rate`,value:D==null?`—`:c(D),tone:D==null?`default`:D>.05?`red`:`green`}),(0,h.jsx)(l,{label:`Uptime`,value:O})]}),(0,h.jsxs)(`div`,{className:`mt-6 grid grid-cols-1 gap-6 lg:grid-cols-2`,children:[(0,h.jsxs)(r,{children:[(0,h.jsx)(n,{title:`Runtime`}),(0,h.jsxs)(`dl`,{className:`divide-y divide-line text-sm`,children:[(0,h.jsx)(v,{label:`Jobs pushed (since restart)`,value:a(S.totalPushed)}),(0,h.jsx)(v,{label:`Jobs pulled (since restart)`,value:a(S.totalPulled)}),(0,h.jsx)(v,{label:`Heap used`,value:f(C.heapUsed*1024*1024)}),(0,h.jsx)(v,{label:`RSS`,value:f(C.rss*1024*1024)}),(0,h.jsx)(v,{label:`Cron jobs`,value:String(w.total)})]})]}),(0,h.jsxs)(r,{children:[(0,h.jsx)(n,{title:`Storage`}),T.diskFull?(0,h.jsxs)(`div`,{className:`rounded-lg border border-red-500/25 bg-red-500/[0.06] px-4 py-3`,children:[(0,h.jsx)(`div`,{className:`font-semibold text-danger`,children:`Disk full — writes suspended`}),T.error&&(0,h.jsx)(`div`,{className:`mt-1 text-xs text-muted`,children:T.error}),T.since!=null&&(0,h.jsxs)(`div`,{className:`mt-1 text-xs text-faint`,children:[`since `,p(T.since)]})]}):(0,h.jsxs)(`div`,{className:`rounded-lg border border-emerald-500/25 bg-emerald-500/[0.06] px-4 py-3`,children:[(0,h.jsx)(`div`,{className:`font-semibold text-success`,children:`Healthy`}),(0,h.jsx)(`div`,{className:`mt-1 text-xs text-faint`,children:`Disk writes are being accepted.`})]})]})]})]})}function v({label:e,value:t}){return(0,h.jsxs)(`div`,{className:`flex items-center justify-between py-2.5`,children:[(0,h.jsx)(`dt`,{className:`text-muted`,children:e}),(0,h.jsx)(`dd`,{className:`font-medium text-fg`,children:t})]})}export{_ as UsagePro};
@@ -1 +1 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-B68RYDeC.js";import{A as r,C as i,S as a,T as o,V as s,Y as c,b as l,c as u,h as d,nt as f,rt as p,tt as m,u as h,v as g,w as _,x as v}from"./index-BjRjwWwc.js";import{n as y,o as b,t as x}from"./form-C-zZyKfB.js";import{t as S}from"./Pagination-BQg6KGW1.js";var C=e(t(),1),w=n();function T(){let{data:e,error:t,loading:n,refetch:m}=r(()=>f.webhooks(),[]),_=e?.data?.webhooks??[],[y,x]=(0,C.useState)(0),T=Math.max(1,Math.ceil(_.length/15)),D=Math.min(y,T-1),[O,k]=(0,C.useState)(null),A=async e=>{k(null);try{await e(),m()}catch(e){k(e.message)}},[j,M]=(0,C.useState)({}),N=async(e,t)=>{M(n=>({...n,[e]:t}));try{await f.setWebhookEnabled(e,t),await m()}catch(e){p.error(`Webhook toggle failed`,e.message)}finally{M(t=>{let{[e]:n,...r}=t;return r})}};return(0,w.jsxs)(`div`,{children:[(0,w.jsx)(d,{title:`Webhooks`,description:`HTTP callbacks fired on job events.`,live:!0}),t&&(0,w.jsx)(v,{onRetry:m}),O&&(0,w.jsx)(`div`,{role:`status`,className:`mb-4 rounded-lg border border-red-500/20 bg-red-500/5 px-4 py-2 text-sm text-danger`,children:O}),(0,w.jsxs)(a,{className:`mb-6`,children:[(0,w.jsx)(i,{title:`Add webhook`}),(0,w.jsx)(E,{onAdd:async e=>{await f.addWebhook(e),m()}})]}),n&&!e&&!t?(0,w.jsx)(l,{label:`Loading webhooks…`}):_.length===0?(0,w.jsx)(g,{icon:(0,w.jsx)(s,{}),title:`No webhooks`,hint:`Add one above to receive job-event callbacks.`}):(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,w.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,w.jsx)(`thead`,{children:(0,w.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,w.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`URL`}),(0,w.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Events`}),(0,w.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Queue`}),(0,w.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Success / Fail`}),(0,w.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Last`}),(0,w.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Enabled`}),(0,w.jsx)(`th`,{className:`w-12 px-5 py-3`})]})}),(0,w.jsx)(`tbody`,{children:_.slice(D*15,D*15+15).map(e=>(0,w.jsxs)(`tr`,{className:`border-b border-line last:border-0 align-top hover:bg-surface-2/40`,children:[(0,w.jsx)(`td`,{className:`max-w-xs truncate px-5 py-3 font-mono text-xs text-fg`,children:e.url}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-xs text-muted`,children:e.events.join(`, `)}),(0,w.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.queue??`all`}),(0,w.jsxs)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:[(0,w.jsx)(`span`,{className:`text-success`,children:u(e.successCount)}),` / `,(0,w.jsx)(`span`,{className:e.failureCount?`text-danger`:``,children:u(e.failureCount)})]}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right text-faint`,children:h(e.lastTriggered)}),(0,w.jsx)(`td`,{className:`px-5 py-3`,children:(0,w.jsx)(b,{checked:j[e.id]??e.enabled,label:`${j[e.id]??e.enabled?`Disable`:`Enable`} webhook`,onChange:t=>N(e.id,t)})}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right`,children:(0,w.jsx)(o,{"aria-label":`Remove webhook`,onClick:()=>window.confirm(`Remove webhook for ${e.url}?`)&&A(()=>f.removeWebhook(e.id)),children:(0,w.jsx)(c,{className:`size-3.5`})})})]},e.id))})]})}),(0,w.jsx)(S,{page:D,pageSize:15,total:_.length,onPageChange:x,label:`webhooks`})]})]})}function E({onAdd:e}){let[t,n]=(0,C.useState)(``),[r,i]=(0,C.useState)(``),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)([`job.completed`,`job.failed`]),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(!1),p=e=>c(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),h=async()=>{if(d)return;u(null);let i=t.trim();if(!i||s.length===0){u(`URL and at least one event are required`);return}if(!(()=>{try{return/^https?:$/.test(new URL(i).protocol)}catch{return!1}})()){u(`URL must be a valid http:// or https:// address`);return}f(!0);try{await e({url:t,events:s,queue:r.trim()||void 0,secret:a.trim()||void 0}),n(``),o(``)}catch(e){u(e.message)}finally{f(!1)}};return(0,w.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),h()},children:[(0,w.jsxs)(`div`,{className:`grid grid-cols-1 gap-4 md:grid-cols-3`,children:[(0,w.jsx)(`div`,{className:`md:col-span-1`,children:(0,w.jsx)(x,{label:`URL`,children:(0,w.jsx)(y,{value:t,onChange:e=>n(e.target.value),placeholder:`https://example.com/hook`})})}),(0,w.jsx)(x,{label:`Queue (optional)`,children:(0,w.jsx)(y,{value:r,onChange:e=>i(e.target.value),placeholder:`all queues`})}),(0,w.jsx)(x,{label:`Secret (optional)`,children:(0,w.jsx)(y,{type:`password`,autoComplete:`new-password`,value:a,onChange:e=>o(e.target.value),placeholder:`HMAC signing secret`})})]}),(0,w.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:m.map(e=>(0,w.jsx)(`button`,{type:`button`,"aria-pressed":s.includes(e),onClick:()=>p(e),className:s.includes(e)?`rounded-full bg-accent/15 px-3 py-1 text-xs font-medium text-accent`:`rounded-full border border-line px-3 py-1 text-xs font-medium text-muted hover:text-fg`,children:e},e))}),(0,w.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,w.jsx)(_,{type:`submit`,variant:`accent`,size:`sm`,disabled:d,children:d?`Adding…`:`Add webhook`}),l&&(0,w.jsx)(`span`,{className:`text-xs text-danger`,children:l})]})]})}export{T as Webhooks};
1
+ import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-BcouBxpZ.js";import{A as r,C as i,S as a,T as o,V as s,Y as c,b as l,c as u,h as d,nt as f,rt as p,tt as m,u as h,v as g,w as _,x as v}from"./index-BOcegTHa.js";import{n as y,o as b,t as x}from"./form-DGinTEEb.js";import{t as S}from"./Pagination-D4ki-pGz.js";var C=e(t(),1),w=n();function T(){let{data:e,error:t,loading:n,refetch:m}=r(()=>f.webhooks(),[]),_=e?.data?.webhooks??[],[y,x]=(0,C.useState)(0),T=Math.max(1,Math.ceil(_.length/15)),D=Math.min(y,T-1),[O,k]=(0,C.useState)(null),A=async e=>{k(null);try{await e(),m()}catch(e){k(e.message)}},[j,M]=(0,C.useState)({}),N=async(e,t)=>{M(n=>({...n,[e]:t}));try{await f.setWebhookEnabled(e,t),await m()}catch(e){p.error(`Webhook toggle failed`,e.message)}finally{M(t=>{let{[e]:n,...r}=t;return r})}};return(0,w.jsxs)(`div`,{children:[(0,w.jsx)(d,{title:`Webhooks`,description:`HTTP callbacks fired on job events.`,live:!0}),t&&(0,w.jsx)(v,{onRetry:m}),O&&(0,w.jsx)(`div`,{role:`status`,className:`mb-4 rounded-lg border border-red-500/20 bg-red-500/5 px-4 py-2 text-sm text-danger`,children:O}),(0,w.jsxs)(a,{className:`mb-6`,children:[(0,w.jsx)(i,{title:`Add webhook`}),(0,w.jsx)(E,{onAdd:async e=>{await f.addWebhook(e),m()}})]}),n&&!e&&!t?(0,w.jsx)(l,{label:`Loading webhooks…`}):_.length===0?(0,w.jsx)(g,{icon:(0,w.jsx)(s,{}),title:`No webhooks`,hint:`Add one above to receive job-event callbacks.`}):(0,w.jsxs)(w.Fragment,{children:[(0,w.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,w.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,w.jsx)(`thead`,{children:(0,w.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,w.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`URL`}),(0,w.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Events`}),(0,w.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Queue`}),(0,w.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Success / Fail`}),(0,w.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Last`}),(0,w.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Enabled`}),(0,w.jsx)(`th`,{className:`w-12 px-5 py-3`})]})}),(0,w.jsx)(`tbody`,{children:_.slice(D*15,D*15+15).map(e=>(0,w.jsxs)(`tr`,{className:`border-b border-line last:border-0 align-top hover:bg-surface-2/40`,children:[(0,w.jsx)(`td`,{className:`max-w-xs truncate px-5 py-3 font-mono text-xs text-fg`,children:e.url}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-xs text-muted`,children:e.events.join(`, `)}),(0,w.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.queue??`all`}),(0,w.jsxs)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:[(0,w.jsx)(`span`,{className:`text-success`,children:u(e.successCount)}),` / `,(0,w.jsx)(`span`,{className:e.failureCount?`text-danger`:``,children:u(e.failureCount)})]}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right text-faint`,children:h(e.lastTriggered)}),(0,w.jsx)(`td`,{className:`px-5 py-3`,children:(0,w.jsx)(b,{checked:j[e.id]??e.enabled,label:`${j[e.id]??e.enabled?`Disable`:`Enable`} webhook`,onChange:t=>N(e.id,t)})}),(0,w.jsx)(`td`,{className:`px-5 py-3 text-right`,children:(0,w.jsx)(o,{"aria-label":`Remove webhook`,onClick:()=>window.confirm(`Remove webhook for ${e.url}?`)&&A(()=>f.removeWebhook(e.id)),children:(0,w.jsx)(c,{className:`size-3.5`})})})]},e.id))})]})}),(0,w.jsx)(S,{page:D,pageSize:15,total:_.length,onPageChange:x,label:`webhooks`})]})]})}function E({onAdd:e}){let[t,n]=(0,C.useState)(``),[r,i]=(0,C.useState)(``),[a,o]=(0,C.useState)(``),[s,c]=(0,C.useState)([`job.completed`,`job.failed`]),[l,u]=(0,C.useState)(null),[d,f]=(0,C.useState)(!1),p=e=>c(t=>t.includes(e)?t.filter(t=>t!==e):[...t,e]),h=async()=>{if(d)return;u(null);let i=t.trim();if(!i||s.length===0){u(`URL and at least one event are required`);return}if(!(()=>{try{return/^https?:$/.test(new URL(i).protocol)}catch{return!1}})()){u(`URL must be a valid http:// or https:// address`);return}f(!0);try{await e({url:t,events:s,queue:r.trim()||void 0,secret:a.trim()||void 0}),n(``),o(``)}catch(e){u(e.message)}finally{f(!1)}};return(0,w.jsxs)(`form`,{className:`flex flex-col gap-4`,onSubmit:e=>{e.preventDefault(),h()},children:[(0,w.jsxs)(`div`,{className:`grid grid-cols-1 gap-4 md:grid-cols-3`,children:[(0,w.jsx)(`div`,{className:`md:col-span-1`,children:(0,w.jsx)(x,{label:`URL`,children:(0,w.jsx)(y,{value:t,onChange:e=>n(e.target.value),placeholder:`https://example.com/hook`})})}),(0,w.jsx)(x,{label:`Queue (optional)`,children:(0,w.jsx)(y,{value:r,onChange:e=>i(e.target.value),placeholder:`all queues`})}),(0,w.jsx)(x,{label:`Secret (optional)`,children:(0,w.jsx)(y,{type:`password`,autoComplete:`new-password`,value:a,onChange:e=>o(e.target.value),placeholder:`HMAC signing secret`})})]}),(0,w.jsx)(`div`,{className:`flex flex-wrap gap-2`,children:m.map(e=>(0,w.jsx)(`button`,{type:`button`,"aria-pressed":s.includes(e),onClick:()=>p(e),className:s.includes(e)?`rounded-full bg-accent/15 px-3 py-1 text-xs font-medium text-accent`:`rounded-full border border-line px-3 py-1 text-xs font-medium text-muted hover:text-fg`,children:e},e))}),(0,w.jsxs)(`div`,{className:`flex items-center gap-3`,children:[(0,w.jsx)(_,{type:`submit`,variant:`accent`,size:`sm`,disabled:d,children:d?`Adding…`:`Add webhook`}),l&&(0,w.jsx)(`span`,{className:`text-xs text-danger`,children:l})]})]})}export{T as Webhooks};
@@ -1 +1 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-B68RYDeC.js";import{A as r,X as i,b as a,c as o,h as s,j as c,m as l,u,v as d,x as f}from"./index-BjRjwWwc.js";import{t as p}from"./Pagination-BQg6KGW1.js";var m=e(t(),1),h=n(),g=20,_={workers:{total:0,active:0,list:[],truncated:!1}};function v(){let{data:e,error:t,loading:n,refetch:v}=r(()=>c.overview(),[]),[y,b]=(0,m.useState)(0);if(n&&!e&&!t)return(0,h.jsx)(a,{label:`Loading workers…`});let{workers:x}=e??_,S=Math.max(1,Math.ceil(x.list.length/g)),C=Math.min(y,S-1),w=x.list.slice(C*g,C*g+g);return(0,h.jsxs)(`div`,{children:[t&&(0,h.jsx)(f,{onRetry:v}),(0,h.jsx)(s,{title:`Workers`,description:`Registered workers and their throughput.`,live:!0}),(0,h.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,h.jsx)(l,{label:`Total`,value:o(x.total),compact:!0}),(0,h.jsx)(l,{label:`Active`,value:o(x.active),tone:`green`,compact:!0})]}),x.list.length===0?(0,h.jsx)(d,{icon:(0,h.jsx)(i,{}),title:`No workers registered`,hint:`Workers appear here once they connect and register with the server.`}):(0,h.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,h.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,h.jsx)(`thead`,{children:(0,h.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,h.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Worker`}),(0,h.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Queues`}),(0,h.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Active`}),(0,h.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Processed`}),(0,h.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Failed`}),(0,h.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Last Seen`})]})}),(0,h.jsx)(`tbody`,{children:w.map(e=>(0,h.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,h.jsxs)(`td`,{className:`px-5 py-3`,children:[(0,h.jsx)(`div`,{className:`font-medium text-fg`,children:e.name||`worker`}),(0,h.jsx)(`div`,{className:`font-mono text-[11px] text-faint`,children:e.id})]}),(0,h.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.queues.join(`, `)||`—`}),(0,h.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-blue-400`,children:o(e.activeJobs)}),(0,h.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:o(e.processedJobs)}),(0,h.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:o(e.failedJobs)}),(0,h.jsx)(`td`,{className:`px-5 py-3 text-right text-faint`,children:u(e.lastSeen)})]},e.id))})]})}),x.truncated&&(0,h.jsxs)(`p`,{className:`mt-3 text-xs text-amber-400`,children:[`Showing first `,o(x.list.length),` of `,o(x.total),` `,`workers.`]}),(0,h.jsx)(p,{page:C,pageSize:g,total:x.list.length,onPageChange:b,label:`workers`})]})}export{v as Workers};
1
+ import{r as e}from"./cn-CMFYpumL.js";import{h as t,t as n}from"./react-vendor-BcouBxpZ.js";import{A as r,X as i,b as a,c as o,h as s,j as c,m as l,u,v as d,x as f}from"./index-BOcegTHa.js";import{t as p}from"./Pagination-D4ki-pGz.js";var m=e(t(),1),h=n(),g=20,_={workers:{total:0,active:0,list:[],truncated:!1}};function v(){let{data:e,error:t,loading:n,refetch:v}=r(()=>c.overview(),[]),[y,b]=(0,m.useState)(0);if(n&&!e&&!t)return(0,h.jsx)(a,{label:`Loading workers…`});let{workers:x}=e??_,S=Math.max(1,Math.ceil(x.list.length/g)),C=Math.min(y,S-1),w=x.list.slice(C*g,C*g+g);return(0,h.jsxs)(`div`,{children:[t&&(0,h.jsx)(f,{onRetry:v}),(0,h.jsx)(s,{title:`Workers`,description:`Registered workers and their throughput.`,live:!0}),(0,h.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,h.jsx)(l,{label:`Total`,value:o(x.total),compact:!0}),(0,h.jsx)(l,{label:`Active`,value:o(x.active),tone:`green`,compact:!0})]}),x.list.length===0?(0,h.jsx)(d,{icon:(0,h.jsx)(i,{}),title:`No workers registered`,hint:`Workers appear here once they connect and register with the server.`}):(0,h.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,h.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,h.jsx)(`thead`,{children:(0,h.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,h.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Worker`}),(0,h.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Queues`}),(0,h.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Active`}),(0,h.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Processed`}),(0,h.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Failed`}),(0,h.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Last Seen`})]})}),(0,h.jsx)(`tbody`,{children:w.map(e=>(0,h.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,h.jsxs)(`td`,{className:`px-5 py-3`,children:[(0,h.jsx)(`div`,{className:`font-medium text-fg`,children:e.name||`worker`}),(0,h.jsx)(`div`,{className:`font-mono text-[11px] text-faint`,children:e.id})]}),(0,h.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.queues.join(`, `)||`—`}),(0,h.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-blue-400`,children:o(e.activeJobs)}),(0,h.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:o(e.processedJobs)}),(0,h.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:o(e.failedJobs)}),(0,h.jsx)(`td`,{className:`px-5 py-3 text-right text-faint`,children:u(e.lastSeen)})]},e.id))})]})}),x.truncated&&(0,h.jsxs)(`p`,{className:`mt-3 text-xs text-amber-400`,children:[`Showing first `,o(x.list.length),` of `,o(x.total),` `,`workers.`]}),(0,h.jsx)(p,{page:C,pageSize:g,total:x.list.length,onPageChange:b,label:`workers`})]})}export{v as Workers};
@@ -1 +1 @@
1
- import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,t as r}from"./react-vendor-B68RYDeC.js";import{A as i,T as a,X as o,Y as s,b as c,c as l,h as u,m as d,nt as f,u as p,v as m,x as h}from"./index-BjRjwWwc.js";var g=e(n(),1),_=r(),v=100,y=`No heartbeat recently — derived from lastSeen`;function b(){let{data:e,error:n,loading:r,refetch:b}=i(async()=>(await f.workers()).data?.workers??[],[]),[S,C]=(0,g.useState)(new Set),[w,T]=(0,g.useState)(null),[E,D]=(0,g.useState)(null);if(r&&!e&&!n)return(0,_.jsx)(c,{label:`Loading workers…`});let O=e??[],k=(E?[...O].sort((e,t)=>{let n=E.key===`failed`?e.failedJobs??0:e.lastSeen??0,r=E.key===`failed`?t.failedJobs??0:t.lastSeen??0;return E.dir===`asc`?n-r:r-n}):O).slice(0,v),A=e=>D(t=>t?.key===e?{key:e,dir:t.dir===`desc`?`asc`:`desc`}:{key:e,dir:`desc`}),j=O.filter(e=>e.status===`active`).length,M=O.length-j,N=O.reduce((e,t)=>e+(t.activeJobs??0),0),P=async e=>{if(window.confirm(`Unregister worker "${e.id}"? It can re-register on its next heartbeat.`)){C(t=>new Set(t).add(e.id)),T(null);try{await f.unregisterWorker(e.id),T({ok:!0,text:`Unregistered ${e.id} ✓`})}catch(e){T({ok:!1,text:`Unregister failed: ${e.message}`})}finally{C(t=>{let n=new Set(t);return n.delete(e.id),n}),b()}}};return(0,_.jsxs)(`div`,{children:[(0,_.jsx)(u,{title:`Workers`,description:`Registered workers and their throughput.`,live:!n}),n&&(0,_.jsx)(h,{onRetry:b}),(0,_.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,_.jsx)(d,{label:`Total`,value:l(O.length),compact:!0}),(0,_.jsx)(d,{label:`Active`,value:l(j),tone:`green`,compact:!0}),(0,_.jsx)(`div`,{title:y,children:(0,_.jsx)(d,{label:`Stale`,value:l(M),tone:M?`amber`:`default`,compact:!0})}),(0,_.jsx)(d,{label:`Active Jobs`,value:l(N),tone:`blue`,compact:!0})]}),w&&(0,_.jsx)(`div`,{className:t(`mb-3 text-sm`,w.ok?`text-success`:`text-danger`),children:w.text}),O.length===0?(0,_.jsx)(m,{icon:(0,_.jsx)(o,{}),title:`No workers registered`,hint:`Workers appear here once they connect and register with the server.`}):(0,_.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,_.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,_.jsx)(`thead`,{children:(0,_.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,_.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Worker`}),(0,_.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Queues`}),(0,_.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Status`}),(0,_.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Active`}),(0,_.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Processed`}),(0,_.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:(0,_.jsx)(x,{label:`Failed`,active:E?.key===`failed`?E.dir:null,onClick:()=>A(`failed`)})}),(0,_.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:(0,_.jsx)(x,{label:`Last Seen`,active:E?.key===`lastSeen`?E.dir:null,onClick:()=>A(`lastSeen`)})}),(0,_.jsx)(`th`,{className:`w-16 px-5 py-3 text-right font-medium`,children:`Actions`})]})}),(0,_.jsx)(`tbody`,{children:k.map(e=>(0,_.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,_.jsxs)(`td`,{className:`px-5 py-3`,children:[(0,_.jsx)(`div`,{className:`font-medium text-fg`,children:e.name||`worker`}),(0,_.jsx)(`div`,{className:`font-mono text-[11px] text-faint`,children:e.id})]}),(0,_.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.queues.join(`, `)||`—`}),(0,_.jsx)(`td`,{className:`px-5 py-3`,children:(0,_.jsx)(`span`,{title:e.status===`active`?void 0:y,className:t(`rounded-full px-2 py-0.5 text-[11px] font-medium`,e.status===`active`?`bg-emerald-500/10 text-success`:`bg-amber-500/10 text-warning`),children:e.status})}),(0,_.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-blue-400`,children:l(e.activeJobs)}),(0,_.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:l(e.processedJobs)}),(0,_.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:l(e.failedJobs)}),(0,_.jsx)(`td`,{className:`px-5 py-3 text-right text-faint`,children:p(e.lastSeen)}),(0,_.jsx)(`td`,{className:`px-5 py-3`,children:(0,_.jsx)(`div`,{className:`flex justify-end`,children:(0,_.jsx)(a,{"aria-label":`Unregister worker ${e.id}`,disabled:S.has(e.id),onClick:()=>P(e),children:(0,_.jsx)(s,{className:`size-3.5`})})})})]},e.id))})]})}),O.length>v&&(0,_.jsxs)(`p`,{className:`mt-3 text-xs text-warning`,children:[`Showing first `,l(v),` of `,l(O.length),` workers.`]})]})}function x({label:e,active:n,onClick:r}){return(0,_.jsxs)(`button`,{type:`button`,onClick:r,title:`Sort by ${e}`,className:t(`inline-flex items-center gap-1 uppercase tracking-wider transition-colors hover:text-fg`,n?`text-fg`:`text-faint`),children:[e,(0,_.jsx)(`span`,{"aria-hidden":`true`,children:n===`desc`?`↓`:n===`asc`?`↑`:``})]})}export{b as WorkersPro};
1
+ import{r as e,t}from"./cn-CMFYpumL.js";import{h as n,t as r}from"./react-vendor-BcouBxpZ.js";import{A as i,T as a,X as o,Y as s,b as c,c as l,h as u,m as d,nt as f,u as p,v as m,x as h}from"./index-BOcegTHa.js";var g=e(n(),1),_=r(),v=100,y=`No heartbeat recently — derived from lastSeen`;function b(){let{data:e,error:n,loading:r,refetch:b}=i(async()=>(await f.workers()).data?.workers??[],[]),[S,C]=(0,g.useState)(new Set),[w,T]=(0,g.useState)(null),[E,D]=(0,g.useState)(null);if(r&&!e&&!n)return(0,_.jsx)(c,{label:`Loading workers…`});let O=e??[],k=(E?[...O].sort((e,t)=>{let n=E.key===`failed`?e.failedJobs??0:e.lastSeen??0,r=E.key===`failed`?t.failedJobs??0:t.lastSeen??0;return E.dir===`asc`?n-r:r-n}):O).slice(0,v),A=e=>D(t=>t?.key===e?{key:e,dir:t.dir===`desc`?`asc`:`desc`}:{key:e,dir:`desc`}),j=O.filter(e=>e.status===`active`).length,M=O.length-j,N=O.reduce((e,t)=>e+(t.activeJobs??0),0),P=async e=>{if(window.confirm(`Unregister worker "${e.id}"? It can re-register on its next heartbeat.`)){C(t=>new Set(t).add(e.id)),T(null);try{await f.unregisterWorker(e.id),T({ok:!0,text:`Unregistered ${e.id} ✓`})}catch(e){T({ok:!1,text:`Unregister failed: ${e.message}`})}finally{C(t=>{let n=new Set(t);return n.delete(e.id),n}),b()}}};return(0,_.jsxs)(`div`,{children:[(0,_.jsx)(u,{title:`Workers`,description:`Registered workers and their throughput.`,live:!n}),n&&(0,_.jsx)(h,{onRetry:b}),(0,_.jsxs)(`div`,{className:`mb-6 grid grid-cols-2 gap-4 md:grid-cols-4`,children:[(0,_.jsx)(d,{label:`Total`,value:l(O.length),compact:!0}),(0,_.jsx)(d,{label:`Active`,value:l(j),tone:`green`,compact:!0}),(0,_.jsx)(`div`,{title:y,children:(0,_.jsx)(d,{label:`Stale`,value:l(M),tone:M?`amber`:`default`,compact:!0})}),(0,_.jsx)(d,{label:`Active Jobs`,value:l(N),tone:`blue`,compact:!0})]}),w&&(0,_.jsx)(`div`,{className:t(`mb-3 text-sm`,w.ok?`text-success`:`text-danger`),children:w.text}),O.length===0?(0,_.jsx)(m,{icon:(0,_.jsx)(o,{}),title:`No workers registered`,hint:`Workers appear here once they connect and register with the server.`}):(0,_.jsx)(`div`,{className:`overflow-x-auto rounded-xl border border-line bg-surface`,children:(0,_.jsxs)(`table`,{className:`w-full text-sm`,children:[(0,_.jsx)(`thead`,{children:(0,_.jsxs)(`tr`,{className:`border-b border-line text-left text-[11px] uppercase tracking-wider text-faint`,children:[(0,_.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Worker`}),(0,_.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Queues`}),(0,_.jsx)(`th`,{className:`px-5 py-3 font-medium`,children:`Status`}),(0,_.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Active`}),(0,_.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:`Processed`}),(0,_.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:(0,_.jsx)(x,{label:`Failed`,active:E?.key===`failed`?E.dir:null,onClick:()=>A(`failed`)})}),(0,_.jsx)(`th`,{className:`px-5 py-3 text-right font-medium`,children:(0,_.jsx)(x,{label:`Last Seen`,active:E?.key===`lastSeen`?E.dir:null,onClick:()=>A(`lastSeen`)})}),(0,_.jsx)(`th`,{className:`w-16 px-5 py-3 text-right font-medium`,children:`Actions`})]})}),(0,_.jsx)(`tbody`,{children:k.map(e=>(0,_.jsxs)(`tr`,{className:`border-b border-line last:border-0 hover:bg-surface-2/40`,children:[(0,_.jsxs)(`td`,{className:`px-5 py-3`,children:[(0,_.jsx)(`div`,{className:`font-medium text-fg`,children:e.name||`worker`}),(0,_.jsx)(`div`,{className:`font-mono text-[11px] text-faint`,children:e.id})]}),(0,_.jsx)(`td`,{className:`px-5 py-3 font-mono text-xs text-muted`,children:e.queues.join(`, `)||`—`}),(0,_.jsx)(`td`,{className:`px-5 py-3`,children:(0,_.jsx)(`span`,{title:e.status===`active`?void 0:y,className:t(`rounded-full px-2 py-0.5 text-[11px] font-medium`,e.status===`active`?`bg-emerald-500/10 text-success`:`bg-amber-500/10 text-warning`),children:e.status})}),(0,_.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-blue-400`,children:l(e.activeJobs)}),(0,_.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:l(e.processedJobs)}),(0,_.jsx)(`td`,{className:`px-5 py-3 text-right tnum text-muted`,children:l(e.failedJobs)}),(0,_.jsx)(`td`,{className:`px-5 py-3 text-right text-faint`,children:p(e.lastSeen)}),(0,_.jsx)(`td`,{className:`px-5 py-3`,children:(0,_.jsx)(`div`,{className:`flex justify-end`,children:(0,_.jsx)(a,{"aria-label":`Unregister worker ${e.id}`,disabled:S.has(e.id),onClick:()=>P(e),children:(0,_.jsx)(s,{className:`size-3.5`})})})})]},e.id))})]})}),O.length>v&&(0,_.jsxs)(`p`,{className:`mt-3 text-xs text-warning`,children:[`Showing first `,l(v),` of `,l(O.length),` workers.`]})]})}function x({label:e,active:n,onClick:r}){return(0,_.jsxs)(`button`,{type:`button`,onClick:r,title:`Sort by ${e}`,className:t(`inline-flex items-center gap-1 uppercase tracking-wider transition-colors hover:text-fg`,n?`text-fg`:`text-faint`),children:[e,(0,_.jsx)(`span`,{"aria-hidden":`true`,children:n===`desc`?`↓`:n===`asc`?`↑`:``})]})}export{b as WorkersPro};
@@ -1 +1 @@
1
- import{r as e}from"./cn-CMFYpumL.js";import{h as t}from"./react-vendor-B68RYDeC.js";var n=e(t(),1),r=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},i=(e=>e?r(e):r),a=e=>e;function o(e,t=a){let r=n.useSyncExternalStore(e.subscribe,n.useCallback(()=>t(e.getState()),[e,t]),n.useCallback(()=>t(e.getInitialState()),[e,t]));return n.useDebugValue(r),r}var s=e=>{let t=i(e),n=e=>o(t,e);return Object.assign(n,t),n},c=(e=>e?s(e):s);function l(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var u=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return u(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return u(t)(e)}}}},d=(e,t)=>(n,r,i)=>{let a={storage:l(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,d=new Set,f=a.storage;if(!f)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let p=()=>{let e=a.partialize({...r()});return f.setItem(a.name,{state:e,version:a.version})},m=i.setState;i.setState=(e,t)=>(m(e,t),p());let h=e((...e)=>(n(...e),p()),r,i);i.getInitialState=()=>h;let g,_=()=>{if(!f)return;let e=++s;o=!1,c.forEach(e=>e(r()??h));let t=a.onRehydrateStorage?.call(a,r()??h)||void 0;return u(f.getItem.bind(f))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(g=a.merge(o,r()??h),n(g,!0),i)return p()}).then(()=>{e===s&&(t?.(r(),void 0),g=r(),o=!0,d.forEach(e=>e(g)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(f=e.storage)},clearStorage:()=>{f?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>_(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(d.add(e),()=>{d.delete(e)})},a.skipHydration||_(),g||h};function f(e){return{baseUrl:e.baseUrl,refreshMs:e.refreshMs}}var p=c()(d(e=>({baseUrl:`/api`,token:``,agentToken:``,refreshMs:3e3,setBaseUrl:t=>e({baseUrl:t.replace(/\/$/,``)}),setToken:t=>e({token:t}),setAgentToken:t=>e({agentToken:t}),setRefreshMs:t=>e({refreshMs:Math.max(500,t)})}),{name:`bq-dash-connection`,version:1,partialize:f,migrate:e=>f(e)}));function m(){return p.getState().baseUrl||`/api`}function h(){let{token:e}=p.getState();return e?{Authorization:`Bearer ${e}`}:{}}function g(){let{agentToken:e}=p.getState();return e?{Authorization:`Bearer ${e}`}:{}}export{d as a,p as i,h as n,c as o,m as r,g as t};
1
+ import{r as e}from"./cn-CMFYpumL.js";import{h as t}from"./react-vendor-BcouBxpZ.js";var n=e(t(),1),r=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a},i=(e=>e?r(e):r),a=e=>e;function o(e,t=a){let r=n.useSyncExternalStore(e.subscribe,n.useCallback(()=>t(e.getState()),[e,t]),n.useCallback(()=>t(e.getInitialState()),[e,t]));return n.useDebugValue(r),r}var s=e=>{let t=i(e),n=e=>o(t,e);return Object.assign(n,t),n},c=(e=>e?s(e):s);function l(e,t){let n;try{n=e()}catch{return}return{getItem:e=>{let r=e=>e===null?null:JSON.parse(e,t?.reviver),i=n.getItem(e)??null;return i instanceof Promise?i.then(r):r(i)},setItem:(e,r)=>n.setItem(e,JSON.stringify(r,t?.replacer)),removeItem:e=>n.removeItem(e)}}var u=e=>t=>{try{let n=e(t);return n instanceof Promise?n:{then(e){return u(e)(n)},catch(e){return this}}}catch(e){return{then(e){return this},catch(t){return u(t)(e)}}}},d=(e,t)=>(n,r,i)=>{let a={storage:l(()=>window.localStorage),partialize:e=>e,version:0,merge:(e,t)=>({...t,...e}),...t},o=!1,s=0,c=new Set,d=new Set,f=a.storage;if(!f)return e((...e)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),n(...e)},r,i);let p=()=>{let e=a.partialize({...r()});return f.setItem(a.name,{state:e,version:a.version})},m=i.setState;i.setState=(e,t)=>(m(e,t),p());let h=e((...e)=>(n(...e),p()),r,i);i.getInitialState=()=>h;let g,_=()=>{if(!f)return;let e=++s;o=!1,c.forEach(e=>e(r()??h));let t=a.onRehydrateStorage?.call(a,r()??h)||void 0;return u(f.getItem.bind(f))(a.name).then(e=>{if(e)if(typeof e.version==`number`&&e.version!==a.version){if(a.migrate){let t=a.migrate(e.state,e.version);return t instanceof Promise?t.then(e=>[!0,e]):[!0,t]}console.error(`State loaded from storage couldn't be migrated since no migrate function was provided`)}else return[!1,e.state];return[!1,void 0]}).then(t=>{if(e!==s)return;let[i,o]=t;if(g=a.merge(o,r()??h),n(g,!0),i)return p()}).then(()=>{e===s&&(t?.(r(),void 0),g=r(),o=!0,d.forEach(e=>e(g)))}).catch(n=>{e===s&&t?.(void 0,n)})};return i.persist={setOptions:e=>{a={...a,...e},e.storage&&(f=e.storage)},clearStorage:()=>{f?.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>_(),hasHydrated:()=>o,onHydrate:e=>(c.add(e),()=>{c.delete(e)}),onFinishHydration:e=>(d.add(e),()=>{d.delete(e)})},a.skipHydration||_(),g||h};function f(e){return{baseUrl:e.baseUrl,refreshMs:e.refreshMs}}var p=c()(d(e=>({baseUrl:`/api`,token:``,agentToken:``,refreshMs:3e3,setBaseUrl:t=>e({baseUrl:t.replace(/\/$/,``)}),setToken:t=>e({token:t}),setAgentToken:t=>e({agentToken:t}),setRefreshMs:t=>e({refreshMs:Math.max(500,t)})}),{name:`bq-dash-connection`,version:1,partialize:f,migrate:e=>f(e)}));function m(){return p.getState().baseUrl||`/api`}function h(){let{token:e}=p.getState();return e?{Authorization:`Bearer ${e}`}:{}}function g(){let{agentToken:e}=p.getState();return e?{Authorization:`Bearer ${e}`}:{}}export{d as a,p as i,h as n,c as o,m as r,g as t};
@@ -0,0 +1,11 @@
1
+ import{$ as e,Ct as t,Dt as n,Et as r,Ft as i,G as a,Gt as o,I as s,J as c,Lt as l,M as u,Mt as d,N as f,Nt as p,Ot as m,Q as h,Rt as g,S as _,St as v,T as y,U as b,Ut as x,Vt as S,W as C,Y as w,Z as T,_ as E,_t as D,b as O,c as k,d as A,f as j,ft as M,gt as N,h as P,ht as F,i as I,it as L,jt as R,k as z,l as B,lt as V,m as ee,mt as te,ot as ne,pt as re,qt as H,rt as U,tt as ie,u as ae,ut as oe,v as W,vt as se,wt as G,x as K,xt as ce,y as le,yt as q,z as ue,zt as de}from"./dist-DZL8soAh.js";function fe(e){return de(se,e)}var J=d({error:d({message:i(),type:i().nullish(),param:v().nullish(),code:l([i(),R()]).nullish()})}),Y=E({errorSchema:J,errorToMessage:e=>e.error.message});function pe(e){let t=e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),n=e.startsWith(`gpt-4`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-nano`)&&!e.startsWith(`gpt-5-chat`)&&!e.startsWith(`gpt-5.4-nano`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`),r=e.startsWith(`o1`)||e.startsWith(`o3`)||e.startsWith(`o4-mini`)||e.startsWith(`gpt-5`)&&!e.startsWith(`gpt-5-chat`),i=e.startsWith(`gpt-5.1`)||e.startsWith(`gpt-5.2`)||e.startsWith(`gpt-5.3`)||e.startsWith(`gpt-5.4`)||e.startsWith(`gpt-5.5`);return{supportsFlexProcessing:t,supportsPriorityProcessing:n,isReasoningModel:r,systemMessageMode:r?`developer`:`system`,supportsNonReasoningParameters:i}}async function X({stream:e,getError:t,isOutputChunk:n,url:r,requestBodyValues:i,responseHeaders:a}){let[o,s]=e.tee(),c=o.getReader();try{for(;;){let e=await c.read();if(e.done)return s;let o=e.value;if(!o.success)return s;let l=t(o.value);if(l!=null)throw s.cancel().catch(()=>{}),me({frame:l,url:r,requestBodyValues:i,responseHeaders:a});if(n(o.value))return s}}finally{c.cancel().catch(()=>{}),c.releaseLock()}}function me({frame:e,url:t,requestBodyValues:n,responseHeaders:r}){let i=he(e);return new S({message:i?.message??`OpenAI stream failed before any output was generated`,url:t,requestBodyValues:n,statusCode:i==null?500:ge(i),responseHeaders:r,responseBody:JSON.stringify(e),data:e})}function he(e){let t=Z(e);if(t==null)return;if(t.type===`response.failed`){let n=Z(Z(t.response)?.error);return typeof n?.message==`string`?{message:n.message,code:_e(n.code),type:`response.failed`,frame:e}:void 0}let n=Z(t.error)??t;return typeof n.message==`string`&&(Z(t.error)!=null||typeof n.type==`string`||`code`in n||`param`in n)?{message:n.message,code:_e(n.code),type:typeof n.type==`string`?n.type:void 0,frame:e}:void 0}function ge(e){if(typeof e.code==`number`&&ve(e.code))return e.code;if(typeof e.code==`string`&&/^\d{3}$/.test(e.code)){let t=Number(e.code);if(ve(t))return t}let t=[e.code,e.type].filter(e=>typeof e==`string`||typeof e==`number`).join(` `).toLowerCase();return[`insufficient_quota`,`rate_limit`].some(e=>t.includes(e))?429:t.includes(`authentication`)?401:t.includes(`permission`)?403:t.includes(`not_found`)?404:[`invalid`,`bad_request`,`context_length`].some(e=>t.includes(e))?400:t.includes(`overload`)?503:t.includes(`timeout`)?504:500}function Z(e){return typeof e==`object`&&e?e:void 0}function _e(e){return typeof e==`string`||typeof e==`number`?e:void 0}function ve(e){return Number.isInteger(e)&&e>=400&&e<=599}function ye(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.prompt_tokens??0,n=e.completion_tokens??0,r=e.prompt_tokens_details?.cached_tokens??0,i=e.completion_tokens_details?.reasoning_tokens??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n,text:n-i,reasoning:i},raw:e}}function be(e){return JSON.stringify(e===void 0?{}:e)}function xe({prompt:e,systemMessageMode:t=`system`}){let n=[],r=[];for(let{role:i,content:a}of e)switch(i){case`system`:switch(t){case`system`:n.push({role:`system`,content:a});break;case`developer`:n.push({role:`developer`,content:a});break;case`remove`:r.push({type:`other`,message:`system messages are removed for this model`});break;default:throw Error(`Unsupported system message mode: ${t}`)}break;case`user`:if(a.length===1&&a[0].type===`text`){n.push({role:`user`,content:a[0].text});break}n.push({role:`user`,content:a.map((e,t)=>{switch(e.type){case`text`:return{type:`text`,text:e.text};case`file`:switch(e.data.type){case`reference`:return{type:`file`,file:{file_id:L({reference:e.data.reference,provider:`openai`})}};case`text`:throw new H({functionality:`text file parts`});case`url`:case`data`:{let n=u(e.mediaType);if(n===`image`)return{type:`image_url`,image_url:{url:e.data.type===`url`?e.data.url.toString():A(e.data.data),detail:e.providerOptions?.openai?.imageDetail}};if(n===`audio`){if(e.data.type===`url`)throw new H({functionality:`audio file parts with URLs`});let t=U({part:e});switch(t){case`audio/wav`:return{type:`input_audio`,input_audio:{data:A(e.data.data),format:`wav`}};case`audio/mp3`:case`audio/mpeg`:return{type:`input_audio`,input_audio:{data:A(e.data.data),format:`mp3`}};default:throw new H({functionality:`audio content parts with media type ${t}`})}}{let n=U({part:e});if(n!==`application/pdf`)throw new H({functionality:`file part media type ${n}`});if(e.data.type===`url`)throw new H({functionality:`PDF file parts with URLs`});return{type:`file`,file:{filename:e.filename??`part-${t}.pdf`,file_data:`data:application/pdf;base64,${A(e.data.data)}`}}}}}}})});break;case`assistant`:{let e=``,t=[];for(let n of a)switch(n.type){case`text`:e+=n.text;break;case`tool-call`:t.push({id:n.toolCallId,type:`function`,function:{name:n.toolName,arguments:be(n.input)}});break}n.push({role:`assistant`,content:t.length>0?e||null:e,tool_calls:t.length>0?t:void 0});break}case`tool`:for(let e of a){if(e.type===`tool-approval-response`)continue;let t=e.output,r;switch(t.type){case`text`:case`error-text`:r=t.value;break;case`execution-denied`:r=t.reason??`Tool call execution denied.`;break;case`content`:case`json`:case`error-json`:r=JSON.stringify(t.value);break}n.push({role:`tool`,tool_call_id:e.toolCallId,content:r})}break;default:throw Error(`Unsupported role: ${i}`)}return{messages:n,warnings:r}}function Se({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n?new Date(n*1e3):void 0}}function Ce(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`other`}}var we=b(()=>F(d({id:i().nullish(),created:R().nullish(),model:i().nullish(),choices:t(d({message:d({role:m(`assistant`).nullish(),content:i().nullish(),tool_calls:t(d({id:i().nullish(),type:m(`function`),function:d({name:i(),arguments:i()})})).nullish(),annotations:t(d({type:m(`url_citation`),url_citation:d({start_index:R(),end_index:R(),url:i(),title:i()})})).nullish()}),index:R(),logprobs:d({content:t(d({token:i(),logprob:R(),top_logprobs:t(d({token:i(),logprob:R()}))})).nullish()}).nullish(),finish_reason:i().nullish()})),usage:d({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:d({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:d({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish()}))),Te=b(()=>F(l([d({id:i().nullish(),created:R().nullish(),model:i().nullish(),choices:t(d({delta:d({role:q([`assistant`]).nullish(),content:i().nullish(),tool_calls:t(d({index:R(),id:i().nullish(),type:m(`function`).nullish(),function:d({name:i().nullish(),arguments:i().nullish()})})).nullish(),annotations:t(d({type:m(`url_citation`),url_citation:d({start_index:R(),end_index:R(),url:i(),title:i()})})).nullish()}).nullish(),logprobs:d({content:t(d({token:i(),logprob:R(),top_logprobs:t(d({token:i(),logprob:R()}))})).nullish()}).nullish(),finish_reason:i().nullish(),index:R()})),usage:d({prompt_tokens:R().nullish(),completion_tokens:R().nullish(),total_tokens:R().nullish(),prompt_tokens_details:d({cached_tokens:R().nullish()}).nullish(),completion_tokens_details:d({reasoning_tokens:R().nullish(),accepted_prediction_tokens:R().nullish(),rejected_prediction_tokens:R().nullish()}).nullish()}).nullish()}),J]))),Ee=b(()=>F(d({logitBias:p(fe(),R()).optional(),logprobs:l([G(),R()]).optional(),parallelToolCalls:G().optional(),user:i().optional(),reasoningEffort:q([`none`,`minimal`,`low`,`medium`,`high`,`xhigh`]).optional(),maxCompletionTokens:R().optional(),store:G().optional(),metadata:p(i().max(64),i().max(512)).optional(),prediction:p(i(),v()).optional(),serviceTier:q([`auto`,`flex`,`priority`,`default`]).optional(),strictJsonSchema:G().optional(),textVerbosity:q([`low`,`medium`,`high`]).optional(),promptCacheKey:i().optional(),promptCacheRetention:q([`in_memory`,`24h`]).optional(),safetyIdentifier:i().optional(),systemMessageMode:q([`system`,`developer`,`remove`]).optional(),forceReasoning:G().optional()})));function De({tools:e,toolChoice:t}){e=e?.length?e:void 0;let n=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:n};let r=[];for(let t of e)switch(t.type){case`function`:r.push({type:`function`,function:{name:t.name,description:t.description,parameters:t.inputSchema,...t.strict==null?{}:{strict:t.strict}}});break;default:n.push({type:`unsupported`,feature:`tool type: ${t.type}`});break}if(t==null)return{tools:r,toolChoice:void 0,toolWarnings:n};let i=t.type;switch(i){case`auto`:case`none`:case`required`:return{tools:r,toolChoice:i,toolWarnings:n};case`tool`:return{tools:r,toolChoice:{type:`function`,function:{name:t.toolName}},toolWarnings:n};default:throw new H({functionality:`tool choice type: ${i}`})}}var Oe=class t{constructor(e,t){this.specificationVersion=`v4`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}static[D](e){return V({modelId:e.modelId,config:e.config})}static[N](e){return new t(e.modelId,e.config)}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:c,responseFormat:l,seed:u,tools:d,toolChoice:f,reasoning:p,providerOptions:m}){let h=[],g=await T({provider:`openai`,providerOptions:m,schema:Ee})??{},_=pe(this.modelId),v=g.reasoningEffort??(s(p)?p:void 0),y=g.forceReasoning??_.isReasoningModel;i!=null&&h.push({type:`unsupported`,feature:`topK`});let{messages:b,warnings:x}=xe({prompt:e,systemMessageMode:g.systemMessageMode??(y?`developer`:_.systemMessageMode)});h.push(...x);let S=g.strictJsonSchema??!0,C={model:this.modelId,logit_bias:g.logitBias,logprobs:g.logprobs===!0||typeof g.logprobs==`number`||void 0,top_logprobs:typeof g.logprobs==`number`?g.logprobs:typeof g.logprobs==`boolean`&&g.logprobs?0:void 0,user:g.user,parallel_tool_calls:g.parallelToolCalls,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,response_format:l?.type===`json`?l.schema==null?{type:`json_object`}:{type:`json_schema`,json_schema:{schema:l.schema,strict:S,name:l.name??`response`,description:l.description}}:void 0,stop:c,seed:u,verbosity:g.textVerbosity,max_completion_tokens:g.maxCompletionTokens,store:g.store,metadata:g.metadata,prediction:g.prediction,reasoning_effort:v,service_tier:g.serviceTier,prompt_cache_key:g.promptCacheKey,prompt_cache_retention:g.promptCacheRetention,safety_identifier:g.safetyIdentifier,messages:b};y?((v!==`none`||!_.supportsNonReasoningParameters)&&(C.temperature!=null&&(C.temperature=void 0,h.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for reasoning models`})),C.top_p!=null&&(C.top_p=void 0,h.push({type:`unsupported`,feature:`topP`,details:`topP is not supported for reasoning models`})),C.logprobs!=null&&(C.logprobs=void 0,h.push({type:`other`,message:`logprobs is not supported for reasoning models`}))),C.frequency_penalty!=null&&(C.frequency_penalty=void 0,h.push({type:`unsupported`,feature:`frequencyPenalty`,details:`frequencyPenalty is not supported for reasoning models`})),C.presence_penalty!=null&&(C.presence_penalty=void 0,h.push({type:`unsupported`,feature:`presencePenalty`,details:`presencePenalty is not supported for reasoning models`})),C.logit_bias!=null&&(C.logit_bias=void 0,h.push({type:`other`,message:`logitBias is not supported for reasoning models`})),C.top_logprobs!=null&&(C.top_logprobs=void 0,h.push({type:`other`,message:`topLogprobs is not supported for reasoning models`})),C.max_tokens!=null&&(C.max_completion_tokens??=C.max_tokens,C.max_tokens=void 0)):(this.modelId.startsWith(`gpt-4o-search-preview`)||this.modelId.startsWith(`gpt-4o-mini-search-preview`))&&C.temperature!=null&&(C.temperature=void 0,h.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for the search preview models and has been removed.`})),g.serviceTier===`flex`&&!_.supportsFlexProcessing&&(h.push({type:`unsupported`,feature:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),C.service_tier=void 0),g.serviceTier===`priority`&&!_.supportsPriorityProcessing&&(h.push({type:`unsupported`,feature:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),C.service_tier=void 0);let{tools:w,toolChoice:E,toolWarnings:D}=De({tools:d,toolChoice:f});return{args:{...C,tools:w,tool_choice:E},warnings:[...h,...D]}}async doGenerate(t){var n;let{args:r,warnings:i}=await this.getArgs(t),{responseHeaders:a,value:o,rawValue:s}=await e({url:this.config.url({path:`/chat/completions`,modelId:this.modelId}),headers:k((n=this.config).headers?.call(n),t.headers),body:r,failedResponseHandler:Y,successfulResponseHandler:W(we),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=o.choices[0],l=[],u=c.message.content;u!=null&&u.length>0&&l.push({type:`text`,text:u});for(let e of c.message.tool_calls??[])l.push({type:`tool-call`,toolCallId:e.id??z(),toolName:e.function.name,input:e.function.arguments});for(let e of c.message.annotations??[])l.push({type:`source`,sourceType:`url`,id:z(),url:e.url_citation.url,title:e.url_citation.title});let d=o.usage?.completion_tokens_details,f={openai:{}};return d?.accepted_prediction_tokens!=null&&(f.openai.acceptedPredictionTokens=d?.accepted_prediction_tokens),d?.rejected_prediction_tokens!=null&&(f.openai.rejectedPredictionTokens=d?.rejected_prediction_tokens),c.logprobs?.content!=null&&(f.openai.logprobs=c.logprobs.content),{content:l,finishReason:{unified:Ce(c.finish_reason),raw:c.finish_reason??void 0},usage:ye(o.usage),request:{body:r},response:{...Se(o),headers:a,body:s},warnings:i,providerMetadata:f}}async doStream(t){var n;let{args:r,warnings:i}=await this.getArgs(t),a={...r,stream:!0,stream_options:{include_usage:!0}},o=this.config.url({path:`/chat/completions`,modelId:this.modelId}),{responseHeaders:s,value:c}=await e({url:o,headers:k((n=this.config).headers?.call(n),t.headers),body:a,failedResponseHandler:Y,successfulResponseHandler:P(Te),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=await X({stream:c,getError:e=>`error`in e?e.error:void 0,isOutputChunk:ke,url:o,requestBodyValues:a,responseHeaders:s}),u,d={unified:`other`,raw:void 0},f,p=!1,m=!1,h={openai:{}};return{stream:l.pipeThrough(new TransformStream({start(e){u=new I(e,{generateId:z,typeValidation:`if-present`}),e.enqueue({type:`stream-start`,warnings:i})},transform(e,n){if(t.includeRawChunks&&n.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){d={unified:`error`,raw:void 0},n.enqueue({type:`error`,error:e.error});return}let r=e.value;if(`error`in r){d={unified:`error`,raw:void 0},n.enqueue({type:`error`,error:r.error});return}if(!p){let e=Se(r);Object.values(e).some(Boolean)&&(p=!0,n.enqueue({type:`response-metadata`,...Se(r)}))}r.usage!=null&&(f=r.usage,r.usage.completion_tokens_details?.accepted_prediction_tokens!=null&&(h.openai.acceptedPredictionTokens=r.usage.completion_tokens_details?.accepted_prediction_tokens),r.usage.completion_tokens_details?.rejected_prediction_tokens!=null&&(h.openai.rejectedPredictionTokens=r.usage.completion_tokens_details?.rejected_prediction_tokens));let i=r.choices[0];if(i?.finish_reason!=null&&(d={unified:Ce(i.finish_reason),raw:i.finish_reason}),i?.logprobs?.content!=null&&(h.openai.logprobs=i.logprobs.content),i?.delta==null)return;let a=i.delta;if(a.content!=null&&(m||=(n.enqueue({type:`text-start`,id:`0`}),!0),n.enqueue({type:`text-delta`,id:`0`,delta:a.content})),a.tool_calls!=null)for(let e of a.tool_calls)u.processDelta(e);if(a.annotations!=null)for(let e of a.annotations)n.enqueue({type:`source`,sourceType:`url`,id:z(),url:e.url_citation.url,title:e.url_citation.title})},flush(e){m&&e.enqueue({type:`text-end`,id:`0`}),u.flush(),e.enqueue({type:`finish`,finishReason:d,usage:ye(f),...h==null?{}:{providerMetadata:h}})}})),request:{body:a},response:{headers:s}}}};function ke(e){return`error`in e?!1:e.choices.some(e=>{let t=e.delta;return t?.content!=null&&t.content.length>0||t?.tool_calls!=null&&t.tool_calls.length>0||t?.annotations!=null&&t.annotations.length>0})}function Ae(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.prompt_tokens??0,n=e.completion_tokens??0;return{inputTokens:{total:e.prompt_tokens??void 0,noCache:t,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:e.completion_tokens??void 0,text:n,reasoning:void 0},raw:e}}function je({prompt:e,user:t=`user`,assistant:n=`assistant`}){let r=``;e[0].role===`system`&&(r+=`${e[0].content}
2
+
3
+ `,e=e.slice(1));for(let{role:i,content:a}of e)switch(i){case`system`:throw new x({message:"Unexpected system message in prompt: ${content}",prompt:e});case`user`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text}}).filter(Boolean).join(``);r+=`${t}:
4
+ ${e}
5
+
6
+ `;break}case`assistant`:{let e=a.map(e=>{switch(e.type){case`text`:return e.text;case`tool-call`:throw new H({functionality:`tool-call messages`})}}).join(``);r+=`${n}:
7
+ ${e}
8
+
9
+ `;break}case`tool`:throw new H({functionality:`tool messages`});default:throw Error(`Unsupported role: ${i}`)}return r+=`${n}:
10
+ `,{prompt:r,stopSequences:[`
11
+ ${t}:`]}}function Me({id:e,model:t,created:n}){return{id:e??void 0,modelId:t??void 0,timestamp:n==null?void 0:new Date(n*1e3)}}function Ne(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`content_filter`:return`content-filter`;case`function_call`:case`tool_calls`:return`tool-calls`;default:return`other`}}var Pe=b(()=>F(d({id:i().nullish(),created:R().nullish(),model:i().nullish(),choices:t(d({text:i(),finish_reason:i(),logprobs:d({tokens:t(i()),token_logprobs:t(R()),top_logprobs:t(p(i(),R())).nullish()}).nullish()})),usage:d({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()}).nullish()}))),Fe=b(()=>F(l([d({id:i().nullish(),created:R().nullish(),model:i().nullish(),choices:t(d({text:i(),finish_reason:i().nullish(),index:R(),logprobs:d({tokens:t(i()),token_logprobs:t(R()),top_logprobs:t(p(i(),R())).nullish()}).nullish()})),usage:d({prompt_tokens:R(),completion_tokens:R(),total_tokens:R()}).nullish()}),J]))),Ie=b(()=>F(d({echo:G().optional(),logitBias:p(i(),R()).optional(),suffix:i().optional(),user:i().optional(),logprobs:l([G(),R()]).optional()}))),Le=class t{constructor(e,t){this.specificationVersion=`v4`,this.supportedUrls={},this.modelId=e,this.config=t}get providerOptionsName(){return this.config.provider.split(`.`)[0].trim()}static[D](e){return V({modelId:e.modelId,config:e.config})}static[N](e){return new t(e.modelId,e.config)}get provider(){return this.config.provider}async getArgs({prompt:e,maxOutputTokens:t,temperature:n,topP:r,topK:i,frequencyPenalty:a,presencePenalty:o,stopSequences:s,responseFormat:c,tools:l,toolChoice:u,seed:d,providerOptions:f}){let p=[],m={...await T({provider:`openai`,providerOptions:f,schema:Ie}),...await T({provider:this.providerOptionsName,providerOptions:f,schema:Ie})};i!=null&&p.push({type:`unsupported`,feature:`topK`}),l?.length&&p.push({type:`unsupported`,feature:`tools`}),u!=null&&p.push({type:`unsupported`,feature:`toolChoice`}),c!=null&&c.type!==`text`&&p.push({type:`unsupported`,feature:`responseFormat`,details:`JSON response format is not supported.`});let{prompt:h,stopSequences:g}=je({prompt:e}),_=[...g??[],...s??[]];return{args:{model:this.modelId,echo:m.echo,logit_bias:m.logitBias,logprobs:m?.logprobs===!0?0:m?.logprobs===!1?void 0:m?.logprobs,suffix:m.suffix,user:m.user,max_tokens:t,temperature:n,top_p:r,frequency_penalty:a,presence_penalty:o,seed:d,prompt:h,stop:_.length>0?_:void 0},warnings:p}}async doGenerate(t){var n;let{args:r,warnings:i}=await this.getArgs(t),{responseHeaders:a,value:o,rawValue:s}=await e({url:this.config.url({path:`/completions`,modelId:this.modelId}),headers:k((n=this.config).headers?.call(n),t.headers),body:r,failedResponseHandler:Y,successfulResponseHandler:W(Pe),abortSignal:t.abortSignal,fetch:this.config.fetch}),c=o.choices[0],l={openai:{}};return c.logprobs!=null&&(l.openai.logprobs=c.logprobs),{content:[{type:`text`,text:c.text}],usage:Ae(o.usage),finishReason:{unified:Ne(c.finish_reason),raw:c.finish_reason??void 0},request:{body:r},response:{...Me(o),headers:a,body:s},providerMetadata:l,warnings:i}}async doStream(t){var n;let{args:r,warnings:i}=await this.getArgs(t),a={...r,stream:!0,stream_options:{include_usage:!0}},o=this.config.url({path:`/completions`,modelId:this.modelId}),{responseHeaders:s,value:c}=await e({url:o,headers:k((n=this.config).headers?.call(n),t.headers),body:a,failedResponseHandler:Y,successfulResponseHandler:P(Fe),abortSignal:t.abortSignal,fetch:this.config.fetch}),l=await X({stream:c,getError:e=>`error`in e?e.error:void 0,isOutputChunk:Re,url:o,requestBodyValues:a,responseHeaders:s}),u={unified:`other`,raw:void 0},d={openai:{}},f,p=!0;return{stream:l.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:i})},transform(e,n){if(t.includeRawChunks&&n.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){u={unified:`error`,raw:void 0},n.enqueue({type:`error`,error:e.error});return}let r=e.value;if(`error`in r){u={unified:`error`,raw:void 0},n.enqueue({type:`error`,error:r.error});return}p&&(p=!1,n.enqueue({type:`response-metadata`,...Me(r)}),n.enqueue({type:`text-start`,id:`0`})),r.usage!=null&&(f=r.usage);let i=r.choices[0];i?.finish_reason!=null&&(u={unified:Ne(i.finish_reason),raw:i.finish_reason}),i?.logprobs!=null&&(d.openai.logprobs=i.logprobs),i?.text!=null&&i.text.length>0&&n.enqueue({type:`text-delta`,id:`0`,delta:i.text})},flush(e){p||e.enqueue({type:`text-end`,id:`0`}),e.enqueue({type:`finish`,finishReason:u,providerMetadata:d,usage:Ae(f)})}})),request:{body:a},response:{headers:s}}}};function Re(e){return!(`error`in e)&&e.choices.some(e=>e.text.length>0)}var ze=b(()=>F(d({dimensions:R().optional(),user:i().optional()}))),Be=b(()=>F(d({data:t(d({embedding:t(R())})),usage:d({prompt_tokens:R()}).nullish()}))),Ve=class t{constructor(e,t){this.specificationVersion=`v4`,this.maxEmbeddingsPerCall=2048,this.supportsParallelCalls=!0,this.modelId=e,this.config=t}static[D](e){return V({modelId:e.modelId,config:e.config})}static[N](e){return new t(e.modelId,e.config)}get provider(){return this.config.provider}async doEmbed({values:t,headers:n,abortSignal:r,providerOptions:i}){var a;if(t.length>this.maxEmbeddingsPerCall)throw new o({provider:this.provider,modelId:this.modelId,maxEmbeddingsPerCall:this.maxEmbeddingsPerCall,values:t});let s=await T({provider:`openai`,providerOptions:i,schema:ze})??{},{responseHeaders:c,value:l,rawValue:u}=await e({url:this.config.url({path:`/embeddings`,modelId:this.modelId}),headers:k((a=this.config).headers?.call(a),n),body:{model:this.modelId,input:t,encoding_format:`float`,dimensions:s.dimensions,user:s.user},failedResponseHandler:Y,successfulResponseHandler:W(Be),abortSignal:r,fetch:this.config.fetch});return{warnings:[],embeddings:l.data.map(e=>e.embedding),usage:l.usage?{tokens:l.usage.prompt_tokens}:void 0,response:{headers:c,body:u}}}},He=b(()=>F(d({id:i(),object:i().nullish(),bytes:R().nullish(),created_at:R().nullish(),filename:i().nullish(),purpose:i().nullish(),status:i().nullish(),expires_at:R().nullish()}))),Ue=b(()=>F(d({purpose:i().optional(),expiresAfter:R().optional()}))),We=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadFile({data:e,mediaType:t,filename:n,providerOptions:r}){let i=await T({provider:`openai`,providerOptions:r,schema:Ue}),a=ae(e),o=new Blob([a],{type:t}),s=new FormData;n==null?s.append(`file`,o):s.append(`file`,o,n),s.append(`purpose`,i?.purpose??`assistants`),i?.expiresAfter!=null&&s.append(`expires_after`,String(i.expiresAfter));let{value:c}=await h({url:`${this.config.baseURL}/files`,headers:k(this.config.headers()),formData:s,failedResponseHandler:Y,successfulResponseHandler:W(He),fetch:this.config.fetch});return{warnings:[],providerReference:{openai:c.id},...c.filename??n?{filename:c.filename??n}:{},...t==null?{}:{mediaType:t},providerMetadata:{openai:{...c.filename==null?{}:{filename:c.filename},...c.purpose==null?{}:{purpose:c.purpose},...c.bytes==null?{}:{bytes:c.bytes},...c.created_at==null?{}:{createdAt:c.created_at},...c.status==null?{}:{status:c.status},...c.expires_at==null?{}:{expiresAt:c.expires_at}}}}}},Ge=b(()=>F(d({created:R().nullish(),data:t(d({b64_json:i(),revised_prompt:i().nullish()})),background:i().nullish(),output_format:i().nullish(),size:i().nullish(),quality:i().nullish(),usage:d({input_tokens:R().nullish(),output_tokens:R().nullish(),total_tokens:R().nullish(),input_tokens_details:d({image_tokens:R().nullish(),text_tokens:R().nullish()}).nullish()}).nullish()}))),Ke={"dall-e-3":1,"dall-e-2":10,"gpt-image-1":10,"gpt-image-1-mini":10,"gpt-image-1.5":10,"gpt-image-2":10,"chatgpt-image-latest":10},qe=[`chatgpt-image-`,`gpt-image-1-mini`,`gpt-image-1.5`,`gpt-image-1`,`gpt-image-2`];function Je(e){return qe.some(t=>e.startsWith(t))}var Ye=d({quality:q([`standard`,`hd`,`low`,`medium`,`high`,`auto`]).optional(),background:q([`transparent`,`opaque`,`auto`]).optional(),outputFormat:q([`png`,`jpeg`,`webp`]).optional(),outputCompression:R().int().min(0).max(100).optional(),user:i().optional()});b(()=>F(Ye));var Xe=b(()=>F(Ye.extend({style:q([`vivid`,`natural`]).optional(),moderation:q([`auto`,`low`]).optional()}))),Ze=b(()=>F(Ye.extend({inputFidelity:q([`high`,`low`]).optional()}))),Qe=class t{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}static[D](e){return V({modelId:e.modelId,config:e.config})}static[N](e){return new t(e.modelId,e.config)}get maxImagesPerCall(){return Ke[this.modelId]??1}get provider(){return this.config.provider}async doGenerate({prompt:t,files:n,mask:r,n:i,size:a,aspectRatio:o,seed:s,providerOptions:c,headers:l,abortSignal:u}){var d,f,p;let m=[];o!=null&&m.push({type:`unsupported`,feature:`aspectRatio`,details:"This model does not support aspect ratio. Use `size` instead."}),s!=null&&m.push({type:`unsupported`,feature:`seed`});let g=((d=this.config._internal)?.currentDate)?.call(d)??new Date;if(n!=null){let e=await T({provider:`openai`,providerOptions:c,schema:Ze})??{},{value:o,responseHeaders:s}=await h({url:this.config.url({path:`/images/edits`,modelId:this.modelId}),headers:k((f=this.config).headers?.call(f),l),formData:j({model:this.modelId,prompt:t,image:await Promise.all(n.map(e=>e.type===`file`?new Blob([e.data instanceof Uint8Array?new Blob([e.data],{type:e.mediaType}):new Blob([B(e.data)],{type:e.mediaType})],{type:e.mediaType}):y(e.url))),mask:r==null?void 0:await et(r),n:i,size:a,quality:e.quality,background:e.background,output_format:e.outputFormat,output_compression:e.outputCompression,input_fidelity:e.inputFidelity,user:e.user}),failedResponseHandler:Y,successfulResponseHandler:W(Ge),abortSignal:u,fetch:this.config.fetch});return{images:o.data.map(e=>e.b64_json),warnings:m,usage:o.usage==null?void 0:{inputTokens:o.usage.input_tokens??void 0,outputTokens:o.usage.output_tokens??void 0,totalTokens:o.usage.total_tokens??void 0},response:{timestamp:g,modelId:this.modelId,headers:s},providerMetadata:{openai:{images:o.data.map((e,t)=>({...e.revised_prompt?{revisedPrompt:e.revised_prompt}:{},created:o.created??void 0,size:o.size??void 0,quality:o.quality??void 0,background:o.background??void 0,outputFormat:o.output_format??void 0,...$e(o.usage?.input_tokens_details,t,o.data.length)}))}}}}let _=await T({provider:`openai`,providerOptions:c,schema:Xe})??{},{value:v,responseHeaders:b}=await e({url:this.config.url({path:`/images/generations`,modelId:this.modelId}),headers:k((p=this.config).headers?.call(p),l),body:{model:this.modelId,prompt:t,n:i,size:a,quality:_.quality,style:_.style,background:_.background,moderation:_.moderation,output_format:_.outputFormat,output_compression:_.outputCompression,user:_.user,...Je(this.modelId)?{}:{response_format:`b64_json`}},failedResponseHandler:Y,successfulResponseHandler:W(Ge),abortSignal:u,fetch:this.config.fetch});return{images:v.data.map(e=>e.b64_json),warnings:m,usage:v.usage==null?void 0:{inputTokens:v.usage.input_tokens??void 0,outputTokens:v.usage.output_tokens??void 0,totalTokens:v.usage.total_tokens??void 0},response:{timestamp:g,modelId:this.modelId,headers:b},providerMetadata:{openai:{images:v.data.map((e,t)=>({...e.revised_prompt?{revisedPrompt:e.revised_prompt}:{},created:v.created??void 0,size:v.size??void 0,quality:v.quality??void 0,background:v.background??void 0,outputFormat:v.output_format??void 0,...$e(v.usage?.input_tokens_details,t,v.data.length)}))}}}}};function $e(e,t,n){if(e==null)return{};let r={};if(e.image_tokens!=null){let i=Math.floor(e.image_tokens/n),a=e.image_tokens-i*(n-1);r.imageTokens=t===n-1?a:i}if(e.text_tokens!=null){let i=Math.floor(e.text_tokens/n),a=e.text_tokens-i*(n-1);r.textTokens=t===n-1?a:i}return r}async function et(e){if(!e)return;if(e.type===`url`)return y(e.url);let t=e.data instanceof Uint8Array?e.data:B(e.data);return new Blob([t],{type:e.mediaType})}var tt=b(()=>F(d({callId:i(),operation:r(`type`,[d({type:m(`create_file`),path:i(),diff:i()}),d({type:m(`delete_file`),path:i()}),d({type:m(`update_file`),path:i(),diff:i()})])}))),nt=b(()=>F(d({status:q([`completed`,`failed`]),output:i().optional()})));b(()=>F(d({})));var rt=O({id:`openai.apply_patch`,inputSchema:tt,outputSchema:nt}),it=b(()=>F(d({code:i().nullish(),containerId:i()}))),at=b(()=>F(d({outputs:t(r(`type`,[d({type:m(`logs`),logs:i()}),d({type:m(`image`),url:i()})])).nullish()}))),ot=b(()=>F(d({container:l([i(),d({fileIds:t(i()).optional()})]).optional()}))),st=K({id:`openai.code_interpreter`,inputSchema:it,outputSchema:at}),ct=(e={})=>st(e),lt=b(()=>F(d({description:i().optional(),format:l([d({type:m(`grammar`),syntax:q([`regex`,`lark`]),definition:i()}),d({type:m(`text`)})]).optional()}))),ut=le({id:`openai.custom`,inputSchema:b(()=>F(i()))}),dt=e=>ut(e),ft=d({key:i(),type:q([`eq`,`ne`,`gt`,`gte`,`lt`,`lte`,`in`,`nin`]),value:l([i(),R(),G(),t(i())])}),pt=d({type:q([`and`,`or`]),filters:t(l([ft,n(()=>pt)]))}),mt=b(()=>F(d({vectorStoreIds:t(i()),maxNumResults:R().optional(),ranking:d({ranker:i().optional(),scoreThreshold:R().optional()}).optional(),filters:l([ft,pt]).optional()}))),ht=b(()=>F(d({queries:t(i()),results:t(d({attributes:p(i(),g()),fileId:i(),filename:i(),score:R(),text:i()})).nullable()}))),gt=K({id:`openai.file_search`,inputSchema:d({}),outputSchema:ht}),_t=b(()=>F(d({background:q([`auto`,`opaque`,`transparent`]).optional(),inputFidelity:q([`low`,`high`]).optional(),inputImageMask:d({fileId:i().optional(),imageUrl:i().optional()}).optional(),model:i().optional(),moderation:q([`auto`]).optional(),outputCompression:R().int().min(0).max(100).optional(),outputFormat:q([`png`,`jpeg`,`webp`]).optional(),partialImages:R().int().min(0).max(3).optional(),quality:q([`auto`,`low`,`medium`,`high`]).optional(),size:q([`1024x1024`,`1024x1536`,`1536x1024`,`auto`]).optional()}).strict())),vt=K({id:`openai.image_generation`,inputSchema:b(()=>F(d({}))),outputSchema:b(()=>F(d({result:i()})))}),yt=(e={})=>vt(e),bt=b(()=>F(d({action:d({type:m(`exec`),command:t(i()),timeoutMs:R().optional(),user:i().optional(),workingDirectory:i().optional(),env:p(i(),i()).optional()})}))),xt=b(()=>F(d({output:i()}))),St=O({id:`openai.local_shell`,inputSchema:bt,outputSchema:xt}),Ct=b(()=>F(d({action:d({commands:t(i()),timeoutMs:R().optional(),maxOutputLength:R().optional()})}))),wt=b(()=>F(d({output:t(d({stdout:i(),stderr:i(),outcome:r(`type`,[d({type:m(`timeout`)}),d({type:m(`exit`),exitCode:R()})])}))}))),Tt=t(r(`type`,[d({type:m(`skillReference`),providerReference:p(i(),i()),version:i().optional()}),d({type:m(`inline`),name:i(),description:i(),source:d({type:m(`base64`),mediaType:m(`application/zip`),data:i()})})])).optional(),Et=b(()=>F(d({environment:l([d({type:m(`containerAuto`),fileIds:t(i()).optional(),memoryLimit:q([`1g`,`4g`,`16g`,`64g`]).optional(),networkPolicy:r(`type`,[d({type:m(`disabled`)}),d({type:m(`allowlist`),allowedDomains:t(i()),domainSecrets:t(d({domain:i(),name:i(),value:i()})).optional()})]).optional(),skills:Tt}),d({type:m(`containerReference`),containerId:i()}),d({type:m(`local`).optional(),skills:t(d({name:i(),description:i(),path:i()})).optional()})]).optional()}))),Dt=O({id:`openai.shell`,inputSchema:Ct,outputSchema:wt}),Ot=b(()=>F(d({execution:q([`server`,`client`]).optional(),description:i().optional(),parameters:p(i(),g()).optional()}))),kt=b(()=>F(d({arguments:g().optional(),call_id:i().nullish()}))),At=b(()=>F(d({tools:t(p(i(),g()))}))),jt=O({id:`openai.tool_search`,inputSchema:kt,outputSchema:At}),Mt=(e={})=>jt(e),Nt=b(()=>F(d({externalWebAccess:G().optional(),filters:d({allowedDomains:t(i()).optional()}).optional(),searchContextSize:q([`low`,`medium`,`high`]).optional(),userLocation:d({type:m(`approximate`),country:i().optional(),city:i().optional(),region:i().optional(),timezone:i().optional()}).optional()}))),Pt=K({id:`openai.web_search`,inputSchema:b(()=>F(d({}))),outputSchema:b(()=>F(d({action:r(`type`,[d({type:m(`search`),query:i().optional(),queries:t(i()).optional()}),d({type:m(`openPage`),url:i().nullish()}),d({type:m(`findInPage`),url:i().nullish(),pattern:i().nullish()})]).optional(),sources:t(r(`type`,[d({type:m(`url`),url:i()}),d({type:m(`api`),name:i()})])).optional()})))}),Ft=(e={})=>Pt(e),It=b(()=>F(d({searchContextSize:q([`low`,`medium`,`high`]).optional(),userLocation:d({type:m(`approximate`),country:i().optional(),city:i().optional(),region:i().optional(),timezone:i().optional()}).optional()}))),Lt=K({id:`openai.web_search_preview`,inputSchema:b(()=>F(d({}))),outputSchema:b(()=>F(d({action:r(`type`,[d({type:m(`search`),query:i().optional()}),d({type:m(`openPage`),url:i().nullish()}),d({type:m(`findInPage`),url:i().nullish(),pattern:i().nullish()})]).optional()})))}),Rt=n(()=>l([i(),R(),G(),ce(),t(Rt),p(i(),Rt)])),zt=b(()=>F(d({serverLabel:i(),allowedTools:l([t(i()),d({readOnly:G().optional(),toolNames:t(i()).optional()})]).optional(),authorization:i().optional(),connectorId:i().optional(),headers:p(i(),i()).optional(),requireApproval:l([q([`always`,`never`]),d({never:d({toolNames:t(i()).optional()}).optional()})]).optional(),serverDescription:i().optional(),serverUrl:i().optional()}).refine(e=>e.serverUrl!=null||e.connectorId!=null,`One of serverUrl or connectorId must be provided.`))),Bt=K({id:`openai.mcp`,inputSchema:b(()=>F(d({}))),outputSchema:b(()=>F(d({type:m(`call`),serverLabel:i(),name:i(),arguments:i(),output:i().nullish(),error:l([i(),Rt]).optional()})))}),Vt={applyPatch:rt,customTool:dt,codeInterpreter:ct,fileSearch:gt,imageGeneration:yt,localShell:St,shell:Dt,webSearchPreview:Lt,webSearch:Ft,mcp:e=>Bt(e),toolSearch:Mt};function Ht(e){let t=e,n=t.type;switch(n){case`session.created`:return{type:`session-created`,sessionId:t.session?.id,raw:e};case`session.updated`:return{type:`session-updated`,raw:e};case`input_audio_buffer.speech_started`:return{type:`speech-started`,itemId:t.item_id,raw:e};case`input_audio_buffer.speech_stopped`:return{type:`speech-stopped`,itemId:t.item_id,raw:e};case`input_audio_buffer.committed`:return{type:`audio-committed`,itemId:t.item_id,previousItemId:t.previous_item_id,raw:e};case`conversation.item.added`:return{type:`conversation-item-added`,itemId:t.item?.id??t.item_id,item:t.item,raw:e};case`conversation.item.input_audio_transcription.completed`:return{type:`input-transcription-completed`,itemId:t.item_id,transcript:t.transcript??``,raw:e};case`response.created`:return{type:`response-created`,responseId:t.response?.id??t.response_id,raw:e};case`response.done`:return{type:`response-done`,responseId:t.response?.id??t.response_id,status:t.response?.status??`completed`,raw:e};case`response.output_item.added`:return{type:`output-item-added`,responseId:t.response_id,itemId:t.item?.id??t.item_id,raw:e};case`response.output_item.done`:return{type:`output-item-done`,responseId:t.response_id,itemId:t.item?.id??t.item_id,raw:e};case`response.content_part.added`:return{type:`content-part-added`,responseId:t.response_id,itemId:t.item_id,raw:e};case`response.content_part.done`:return{type:`content-part-done`,responseId:t.response_id,itemId:t.item_id,raw:e};case`response.output_audio.delta`:return{type:`audio-delta`,responseId:t.response_id,itemId:t.item_id,delta:t.delta,raw:e};case`response.output_audio.done`:return{type:`audio-done`,responseId:t.response_id,itemId:t.item_id,raw:e};case`response.output_audio_transcript.delta`:return{type:`audio-transcript-delta`,responseId:t.response_id,itemId:t.item_id,delta:t.delta,raw:e};case`response.output_audio_transcript.done`:return{type:`audio-transcript-done`,responseId:t.response_id,itemId:t.item_id,transcript:t.transcript,raw:e};case`response.output_text.delta`:return{type:`text-delta`,responseId:t.response_id,itemId:t.item_id,delta:t.delta,raw:e};case`response.output_text.done`:return{type:`text-done`,responseId:t.response_id,itemId:t.item_id,text:t.text,raw:e};case`response.function_call_arguments.delta`:return{type:`function-call-arguments-delta`,responseId:t.response_id,itemId:t.item_id,callId:t.call_id,delta:t.delta,raw:e};case`response.function_call_arguments.done`:return{type:`function-call-arguments-done`,responseId:t.response_id,itemId:t.item_id,callId:t.call_id,name:t.name,arguments:t.arguments,raw:e};case`error`:return{type:`error`,message:t.error?.message??t.message??`Unknown error`,code:t.error?.code??t.code,raw:e};default:return{type:`custom`,rawType:n,raw:e}}}function Ut(e,t){switch(e.type){case`session-update`:return{type:`session.update`,session:Wt(e.config,t)};case`input-audio-append`:return{type:`input_audio_buffer.append`,audio:e.audio};case`input-audio-commit`:return{type:`input_audio_buffer.commit`};case`input-audio-clear`:return{type:`input_audio_buffer.clear`};case`conversation-item-create`:{let t=e.item;switch(t.type){case`text-message`:return{type:`conversation.item.create`,item:{type:`message`,role:t.role,content:[{type:`input_text`,text:t.text}]}};case`audio-message`:return{type:`conversation.item.create`,item:{type:`message`,role:t.role,content:[{type:`input_audio`,audio:t.audio}]}};case`function-call-output`:return{type:`conversation.item.create`,item:{type:`function_call_output`,call_id:t.callId,output:t.output}}}break}case`conversation-item-truncate`:return{type:`conversation.item.truncate`,item_id:e.itemId,content_index:e.contentIndex,audio_end_ms:e.audioEndMs};case`response-create`:return{type:`response.create`,...e.options==null?{}:{response:{...e.options.modalities==null?{}:{output_modalities:e.options.modalities},...e.options.instructions==null?{}:{instructions:e.options.instructions},...e.options.metadata==null?{}:{metadata:e.options.metadata}}}};case`response-cancel`:return{type:`response.cancel`}}}function Wt(e,t){let n={type:`realtime`,model:t};e.instructions!=null&&(n.instructions=e.instructions),e.outputModalities!=null&&(n.output_modalities=e.outputModalities);let r={};if(e.inputAudioFormat!=null||e.inputAudioTranscription!=null||e.turnDetection!=null){let t={};if(e.inputAudioFormat!=null&&(t.format={type:e.inputAudioFormat.type,...e.inputAudioFormat.rate==null?{}:{rate:e.inputAudioFormat.rate}}),e.turnDetection!=null)if(e.turnDetection.type===`disabled`)t.turn_detection=null;else{let n={type:e.turnDetection.type===`server-vad`?`server_vad`:`semantic_vad`};e.turnDetection.threshold!=null&&(n.threshold=e.turnDetection.threshold),e.turnDetection.silenceDurationMs!=null&&(n.silence_duration_ms=e.turnDetection.silenceDurationMs),e.turnDetection.prefixPaddingMs!=null&&(n.prefix_padding_ms=e.turnDetection.prefixPaddingMs),t.turn_detection=n}e.inputAudioTranscription!=null&&(t.transcription={model:e.inputAudioTranscription.model??`gpt-realtime-whisper`,...e.inputAudioTranscription.language==null?{}:{language:e.inputAudioTranscription.language},...e.inputAudioTranscription.prompt==null?{}:{prompt:e.inputAudioTranscription.prompt}}),r.input=t}if(e.outputAudioFormat!=null||e.voice!=null){let t={};e.outputAudioFormat!=null&&(t.format={type:e.outputAudioFormat.type,...e.outputAudioFormat.rate==null?{}:{rate:e.outputAudioFormat.rate}}),e.voice!=null&&(t.voice=e.voice),r.output=t}return Object.keys(r).length>0&&(n.audio=r),e.tools!=null&&e.tools.length>0&&(n.tools=e.tools.map(e=>({type:e.type,name:e.name,description:e.description,parameters:e.parameters})),n.tool_choice=`auto`),e.providerOptions!=null&&Object.assign(n,e.providerOptions),n}var Gt=class{constructor(e,t){this.specificationVersion=`v4`,this.modelId=e,this.provider=t.provider,this.config=t}async doCreateClientSecret(e){let t=this.config.fetch??fetch,n=`${this.config.baseURL}/realtime/client_secrets`,r=e.sessionConfig==null?{type:`realtime`,model:this.modelId}:Wt(e.sessionConfig,this.modelId),i=await t(n,{method:`POST`,headers:{...this.config.headers(),"Content-Type":`application/json`},body:JSON.stringify({session:r,...e.expiresAfterSeconds==null?{}:{expires_after:{anchor:`created_at`,seconds:e.expiresAfterSeconds}}})});if(!i.ok){let e=await i.text();throw Error(`OpenAI realtime client secret request failed: ${i.status} ${e}`)}let a=await i.json();return{token:a.value,url:`wss://${new URL(this.config.baseURL).host}/v1/realtime?model=${encodeURIComponent(this.modelId)}`,expiresAt:a.expires_at}}getWebSocketConfig(e){return{url:e.url,protocols:[`realtime`,`openai-insecure-api-key.${e.token}`]}}parseServerEvent(e){return Ht(e)}serializeClientEvent(e){return Ut(e,this.modelId)}buildSessionConfig(e){return Wt(e,this.modelId)}};function Kt(e){if(e==null)return{inputTokens:{total:void 0,noCache:void 0,cacheRead:void 0,cacheWrite:void 0},outputTokens:{total:void 0,text:void 0,reasoning:void 0},raw:void 0};let t=e.input_tokens,n=e.output_tokens,r=e.input_tokens_details?.cached_tokens??0,i=e.output_tokens_details?.reasoning_tokens??0;return{inputTokens:{total:t,noCache:t-r,cacheRead:r,cacheWrite:void 0},outputTokens:{total:n,text:n-i,reasoning:i},raw:e}}function qt(e){return JSON.stringify(e===void 0?{}:e)}function Jt(e,t){return t?t.some(t=>e.startsWith(t)):!1}async function Yt({prompt:e,toolNameMapping:t,systemMessageMode:n,providerOptionsName:r,fileIdPrefixes:i,passThroughUnsupportedFiles:a=!1,store:o,hasConversation:s=!1,hasPreviousResponseId:c=!1,hasLocalShellTool:l=!1,hasShellTool:d=!1,hasApplyPatchTool:f=!1,customProviderToolNames:p}){let m=[],h=[],g=new Set;for(let{role:_,content:v}of e)switch(_){case`system`:switch(n){case`system`:m.push({role:`system`,content:v});break;case`developer`:m.push({role:`developer`,content:v});break;case`remove`:h.push({type:`other`,message:`system messages are removed for this model`});break;default:throw Error(`Unsupported system message mode: ${n}`)}break;case`user`:m.push({role:`user`,content:v.map((e,t)=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:switch(e.data.type){case`reference`:{let t=L({reference:e.data.reference,provider:r});return u(e.mediaType)===`image`?{type:`input_image`,file_id:t,detail:e.providerOptions?.[r]?.imageDetail}:{type:`input_file`,file_id:t}}case`text`:throw new H({functionality:`text file parts`});case`url`:case`data`:if(u(e.mediaType)===`image`)return{type:`input_image`,...e.data.type===`url`?{image_url:e.data.url.toString()}:typeof e.data.data==`string`&&Jt(e.data.data,i)?{file_id:e.data.data}:{image_url:`data:${U({part:e})};base64,${A(e.data.data)}`},detail:e.providerOptions?.[r]?.imageDetail};{if(e.data.type===`url`)return{type:`input_file`,file_url:e.data.url.toString()};let n=U({part:e});if(n!==`application/pdf`&&!a)throw new H({functionality:`file part media type ${n}`});return{type:`input_file`,...typeof e.data.data==`string`&&Jt(e.data.data,i)?{file_id:e.data.data}:{filename:e.filename??(n===`application/pdf`?`part-${t}.pdf`:`part-${t}`),file_data:`data:${n};base64,${A(e.data.data)}`}}}}}})});break;case`assistant`:{let e={};for(let n of v)switch(n.type){case`text`:{let e=n.providerOptions?.[r],t=e?.itemId,i=e?.phase;if(s&&t!=null)break;if(o&&t!=null){m.push({type:`item_reference`,id:t});break}m.push({role:`assistant`,content:[{type:`output_text`,text:n.text}],id:t,...i!=null&&{phase:i}});break}case`tool-call`:{let e=n.providerOptions?.[r]?.itemId??n.providerMetadata?.[r]?.itemId,i=n.providerOptions?.[r]?.namespace??n.providerMetadata?.[r]?.namespace;if(s&&e!=null)break;let a=t.toProviderToolName(n.toolName);if(a===`tool_search`){if(o&&e!=null){m.push({type:`item_reference`,id:e});break}let t=typeof n.input==`string`?await w({text:n.input,schema:kt}):await M({value:n.input,schema:kt}),r=t.call_id==null?`server`:`client`;m.push({type:`tool_search_call`,id:e??n.toolCallId,execution:r,call_id:t.call_id??null,status:`completed`,arguments:t.arguments});break}if(n.providerExecuted){o&&e!=null&&m.push({type:`item_reference`,id:e});break}if(c&&o&&e!=null)break;let u=l&&a===`local_shell`||d&&a===`shell`||f&&a===`apply_patch`||(p?.has(a)??!1);if(o&&e!=null&&u){m.push({type:`item_reference`,id:e});break}if(l&&a===`local_shell`){let t=await M({value:n.input,schema:bt});m.push({type:`local_shell_call`,call_id:n.toolCallId,id:e,action:{type:`exec`,command:t.action.command,timeout_ms:t.action.timeoutMs,user:t.action.user,working_directory:t.action.workingDirectory,env:t.action.env}});break}if(d&&a===`shell`){let t=await M({value:n.input,schema:Ct});m.push({type:`shell_call`,call_id:n.toolCallId,id:e,status:`completed`,action:{commands:t.action.commands,timeout_ms:t.action.timeoutMs,max_output_length:t.action.maxOutputLength}});break}if(f&&a===`apply_patch`){let t=await M({value:n.input,schema:tt});m.push({type:`apply_patch_call`,call_id:t.callId,id:e,status:`completed`,operation:t.operation});break}if(p?.has(a)){m.push({type:`custom_tool_call`,call_id:n.toolCallId,name:a,input:typeof n.input==`string`?n.input:JSON.stringify(n.input),id:e});break}m.push({type:`function_call`,call_id:n.toolCallId,name:a,arguments:qt(n.input),...i!=null&&{namespace:i}});break}case`tool-result`:{if(n.output.type===`execution-denied`||n.output.type===`json`&&typeof n.output.value==`object`&&n.output.value!=null&&`type`in n.output.value&&n.output.value.type===`execution-denied`||s)break;let e=t.toProviderToolName(n.toolName);if(e===`tool_search`){let e=n.providerOptions?.[r]?.itemId??n.toolCallId;if(o)m.push({type:`item_reference`,id:e});else if(n.output.type===`json`){let t=await M({value:n.output.value,schema:At});m.push({type:`tool_search_output`,id:e,execution:`server`,call_id:null,status:`completed`,tools:t.tools})}break}if(d&&e===`shell`){if(n.output.type===`json`){let e=await M({value:n.output.value,schema:wt});m.push({type:`shell_call_output`,call_id:n.toolCallId,output:e.output.map(e=>({stdout:e.stdout,stderr:e.stderr,outcome:e.outcome.type===`timeout`?{type:`timeout`}:{type:`exit`,exit_code:e.outcome.exitCode}}))})}break}if(o){let e=n.providerOptions?.[r]?.itemId??n.toolCallId;m.push({type:`item_reference`,id:e})}else h.push({type:`other`,message:`Results for OpenAI tool ${n.toolName} are not sent to the API when store is false`});break}case`reasoning`:{let t=await T({provider:r,providerOptions:n.providerOptions,schema:Xt}),i=t?.itemId;if((s||c)&&i!=null)break;if(i!=null){let r=e[i];if(o)r===void 0&&(m.push({type:`item_reference`,id:i}),e[i]={type:`reasoning`,id:i,summary:[]});else{let a=[];n.text.length>0?a.push({type:`summary_text`,text:n.text}):r!==void 0&&h.push({type:`other`,message:`Cannot append empty reasoning part to existing reasoning sequence. Skipping reasoning part: ${JSON.stringify(n)}.`}),r===void 0?(e[i]={type:`reasoning`,id:i,encrypted_content:t?.reasoningEncryptedContent,summary:a},m.push(e[i])):(r.summary.push(...a),t?.reasoningEncryptedContent!=null&&(r.encrypted_content=t.reasoningEncryptedContent))}}else{let e=t?.reasoningEncryptedContent;if(e!=null){let t=[];n.text.length>0&&t.push({type:`summary_text`,text:n.text}),m.push({type:`reasoning`,encrypted_content:e,summary:t})}else h.push({type:`other`,message:`Non-OpenAI reasoning parts are not supported. Skipping reasoning part: ${JSON.stringify(n)}.`})}break}case`custom`:if(n.kind===`openai.compaction`){let e=n.providerOptions?.[r],t=e?.itemId;if(s&&t!=null)break;if(o&&t!=null){m.push({type:`item_reference`,id:t});break}let i=e?.encryptedContent;t!=null&&m.push({type:`compaction`,id:t,encrypted_content:i})}break}break}case`tool`:for(let e of v){if(e.type===`tool-approval-response`){let t=e;if(g.has(t.approvalId))continue;g.add(t.approvalId),o&&m.push({type:`item_reference`,id:t.approvalId}),m.push({type:`mcp_approval_response`,approval_request_id:t.approvalId,approve:t.approved});continue}let n=e.output;if(n.type===`execution-denied`&&n.providerOptions?.openai?.approvalId)continue;let i=t.toProviderToolName(e.toolName);if(i===`tool_search`&&n.type===`json`){let t=await M({value:n.value,schema:At});m.push({type:`tool_search_output`,execution:`client`,call_id:e.toolCallId,status:`completed`,tools:t.tools});continue}if(l&&i===`local_shell`&&n.type===`json`){let t=await M({value:n.value,schema:xt});m.push({type:`local_shell_call_output`,call_id:e.toolCallId,output:t.output});continue}if(d&&i===`shell`&&n.type===`json`){let t=await M({value:n.value,schema:wt});m.push({type:`shell_call_output`,call_id:e.toolCallId,output:t.output.map(e=>({stdout:e.stdout,stderr:e.stderr,outcome:e.outcome.type===`timeout`?{type:`timeout`}:{type:`exit`,exit_code:e.outcome.exitCode}}))});continue}if(f&&e.toolName===`apply_patch`&&n.type===`json`){let t=await M({value:n.value,schema:nt});m.push({type:`apply_patch_call_output`,call_id:e.toolCallId,status:t.status,output:t.output});continue}if(p?.has(i)){let t;switch(n.type){case`text`:case`error-text`:t=n.value;break;case`execution-denied`:t=n.reason??`Tool call execution denied.`;break;case`json`:case`error-json`:t=JSON.stringify(n.value);break;case`content`:t=n.value.map(e=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:{let t=u(e.mediaType),n=e.providerOptions?.[r]?.imageDetail;if(e.data.type===`data`){let r=U({part:e});return t===`image`?{type:`input_image`,image_url:`data:${r};base64,${A(e.data.data)}`,detail:n}:{type:`input_file`,filename:e.filename??`data`,file_data:`data:${r};base64,${A(e.data.data)}`}}if(e.data.type===`url`)return t===`image`?{type:`input_image`,image_url:e.data.url.toString(),detail:n}:{type:`input_file`,file_url:e.data.url.toString()};h.push({type:`other`,message:`unsupported custom tool content part type: ${e.type} with data type: ${e.data.type}`});return}default:h.push({type:`other`,message:`unsupported custom tool content part type: ${e.type}`});return}}).filter(ue);break;default:t=``}m.push({type:`custom_tool_call_output`,call_id:e.toolCallId,output:t});continue}let a;switch(n.type){case`text`:case`error-text`:a=n.value;break;case`execution-denied`:a=n.reason??`Tool call execution denied.`;break;case`json`:case`error-json`:a=JSON.stringify(n.value);break;case`content`:a=n.value.map(e=>{switch(e.type){case`text`:return{type:`input_text`,text:e.text};case`file`:{let t=u(e.mediaType),n=e.providerOptions?.[r]?.imageDetail;if(e.data.type===`data`){let r=U({part:e});return t===`image`?{type:`input_image`,image_url:`data:${r};base64,${A(e.data.data)}`,detail:n}:{type:`input_file`,filename:e.filename??`data`,file_data:`data:${r};base64,${A(e.data.data)}`}}if(e.data.type===`url`)return t===`image`?{type:`input_image`,image_url:e.data.url.toString(),detail:n}:{type:`input_file`,file_url:e.data.url.toString()};h.push({type:`other`,message:`unsupported tool content part type: ${e.type} with data type: ${e.data.type}`});return}default:h.push({type:`other`,message:`unsupported tool content part type: ${e.type}`});return}}).filter(ue);break}m.push({type:`function_call_output`,call_id:e.toolCallId,output:a})}break;default:throw Error(`Unsupported role: ${_}`)}return!o&&m.some(e=>`type`in e&&e.type===`reasoning`&&e.encrypted_content==null)&&(h.push({type:`other`,message:`Reasoning parts without encrypted content are not supported when store is false. Skipping reasoning parts.`}),m=m.filter(e=>!(`type`in e)||e.type!==`reasoning`||e.encrypted_content!=null)),{input:m,warnings:h}}var Xt=d({itemId:i().nullish(),reasoningEncryptedContent:i().nullish()});function Zt({finishReason:e,hasFunctionCall:t}){switch(e){case void 0:case null:return t?`tool-calls`:`stop`;case`max_output_tokens`:return`length`;case`content_filter`:return`content-filter`;default:return t?`tool-calls`:`other`}}var Q=n(()=>l([i(),R(),G(),ce(),t(Q),p(i(),Q.optional())])),Qt=d({type:m(`error`),sequence_number:R(),error:d({type:i(),code:i(),message:i(),param:i().nullish()})}),$t=d({type:m(`error`),sequence_number:R(),code:i().nullish(),message:i(),param:i().nullish()}),en=b(()=>F(l([d({type:m(`response.output_text.delta`),item_id:i(),delta:i(),logprobs:t(d({token:i(),logprob:R(),top_logprobs:t(d({token:i(),logprob:R()}))})).nullish()}),d({type:q([`response.completed`,`response.incomplete`]),response:d({incomplete_details:d({reason:i()}).nullish(),usage:d({input_tokens:R(),input_tokens_details:d({cached_tokens:R().nullish(),orchestration_input_tokens:R().nullish(),orchestration_input_cached_tokens:R().nullish()}).nullish(),output_tokens:R(),output_tokens_details:d({reasoning_tokens:R().nullish(),orchestration_output_tokens:R().nullish()}).nullish()}),service_tier:i().nullish()})}),d({type:m(`response.failed`),sequence_number:R(),response:d({error:d({code:i().nullish(),message:i()}).nullish(),incomplete_details:d({reason:i()}).nullish(),usage:d({input_tokens:R(),input_tokens_details:d({cached_tokens:R().nullish(),orchestration_input_tokens:R().nullish(),orchestration_input_cached_tokens:R().nullish()}).nullish(),output_tokens:R(),output_tokens_details:d({reasoning_tokens:R().nullish(),orchestration_output_tokens:R().nullish()}).nullish()}).nullish(),service_tier:i().nullish()})}),d({type:m(`response.created`),response:d({id:i(),created_at:R(),model:i(),service_tier:i().nullish()})}),d({type:m(`response.output_item.added`),output_index:R(),item:r(`type`,[d({type:m(`message`),id:i(),phase:q([`commentary`,`final_answer`]).nullish()}),d({type:m(`reasoning`),id:i(),encrypted_content:i().nullish()}),d({type:m(`function_call`),id:i(),call_id:i(),name:i(),arguments:i(),namespace:i().nullish()}),d({type:m(`web_search_call`),id:i(),status:i()}),d({type:m(`computer_call`),id:i(),status:i()}),d({type:m(`file_search_call`),id:i()}),d({type:m(`image_generation_call`),id:i()}),d({type:m(`code_interpreter_call`),id:i(),container_id:i(),code:i().nullable(),outputs:t(r(`type`,[d({type:m(`logs`),logs:i()}),d({type:m(`image`),url:i()})])).nullable(),status:i()}),d({type:m(`mcp_call`),id:i(),status:i(),approval_request_id:i().nullish()}),d({type:m(`mcp_list_tools`),id:i()}),d({type:m(`mcp_approval_request`),id:i()}),d({type:m(`apply_patch_call`),id:i(),call_id:i(),status:q([`in_progress`,`completed`]),operation:r(`type`,[d({type:m(`create_file`),path:i(),diff:i()}),d({type:m(`delete_file`),path:i()}),d({type:m(`update_file`),path:i(),diff:i()})])}),d({type:m(`custom_tool_call`),id:i(),call_id:i(),name:i(),input:i()}),d({type:m(`shell_call`),id:i(),call_id:i(),status:q([`in_progress`,`completed`,`incomplete`]),action:d({commands:t(i())})}),d({type:m(`compaction`),id:i(),encrypted_content:i().nullish()}),d({type:m(`shell_call_output`),id:i(),call_id:i(),status:q([`in_progress`,`completed`,`incomplete`]),output:t(d({stdout:i(),stderr:i(),outcome:r(`type`,[d({type:m(`timeout`)}),d({type:m(`exit`),exit_code:R()})])}))}),d({type:m(`tool_search_call`),id:i(),execution:q([`server`,`client`]),call_id:i().nullable(),status:q([`in_progress`,`completed`,`incomplete`]),arguments:g()}),d({type:m(`tool_search_output`),id:i(),execution:q([`server`,`client`]),call_id:i().nullable(),status:q([`in_progress`,`completed`,`incomplete`]),tools:t(p(i(),Q.optional()))})])}),d({type:m(`response.output_item.done`),output_index:R(),item:r(`type`,[d({type:m(`message`),id:i(),phase:q([`commentary`,`final_answer`]).nullish()}),d({type:m(`reasoning`),id:i(),encrypted_content:i().nullish()}),d({type:m(`function_call`),id:i(),call_id:i(),name:i(),arguments:i(),status:m(`completed`),namespace:i().nullish()}),d({type:m(`custom_tool_call`),id:i(),call_id:i(),name:i(),input:i(),status:m(`completed`)}),d({type:m(`code_interpreter_call`),id:i(),code:i().nullable(),container_id:i(),outputs:t(r(`type`,[d({type:m(`logs`),logs:i()}),d({type:m(`image`),url:i()})])).nullable()}),d({type:m(`image_generation_call`),id:i(),result:i()}),d({type:m(`web_search_call`),id:i(),status:i(),action:r(`type`,[d({type:m(`search`),query:i().nullish(),queries:t(i()).nullish(),sources:t(r(`type`,[d({type:m(`url`),url:i()}),d({type:m(`api`),name:i()})])).nullish()}),d({type:m(`open_page`),url:i().nullish()}),d({type:m(`find_in_page`),url:i().nullish(),pattern:i().nullish()})]).nullish()}),d({type:m(`file_search_call`),id:i(),queries:t(i()),results:t(d({attributes:p(i(),l([i(),R(),G()])),file_id:i(),filename:i(),score:R(),text:i()})).nullish()}),d({type:m(`local_shell_call`),id:i(),call_id:i(),action:d({type:m(`exec`),command:t(i()),timeout_ms:R().optional(),user:i().optional(),working_directory:i().optional(),env:p(i(),i()).optional()})}),d({type:m(`computer_call`),id:i(),status:m(`completed`)}),d({type:m(`mcp_call`),id:i(),status:i(),arguments:i(),name:i(),server_label:i(),output:i().nullish(),error:l([i(),d({type:i().optional(),code:l([R(),i()]).optional(),message:i().optional()}).loose()]).nullish(),approval_request_id:i().nullish()}),d({type:m(`mcp_list_tools`),id:i(),server_label:i(),tools:t(d({name:i(),description:i().optional(),input_schema:v(),annotations:p(i(),g()).optional()})),error:l([i(),d({type:i().optional(),code:l([R(),i()]).optional(),message:i().optional()}).loose()]).optional()}),d({type:m(`mcp_approval_request`),id:i(),server_label:i(),name:i(),arguments:i(),approval_request_id:i().optional()}),d({type:m(`apply_patch_call`),id:i(),call_id:i(),status:q([`in_progress`,`completed`]),operation:r(`type`,[d({type:m(`create_file`),path:i(),diff:i()}),d({type:m(`delete_file`),path:i()}),d({type:m(`update_file`),path:i(),diff:i()})])}),d({type:m(`shell_call`),id:i(),call_id:i(),status:q([`in_progress`,`completed`,`incomplete`]),action:d({commands:t(i())})}),d({type:m(`compaction`),id:i(),encrypted_content:i()}),d({type:m(`shell_call_output`),id:i(),call_id:i(),status:q([`in_progress`,`completed`,`incomplete`]),output:t(d({stdout:i(),stderr:i(),outcome:r(`type`,[d({type:m(`timeout`)}),d({type:m(`exit`),exit_code:R()})])}))}),d({type:m(`tool_search_call`),id:i(),execution:q([`server`,`client`]),call_id:i().nullable(),status:q([`in_progress`,`completed`,`incomplete`]),arguments:g()}),d({type:m(`tool_search_output`),id:i(),execution:q([`server`,`client`]),call_id:i().nullable(),status:q([`in_progress`,`completed`,`incomplete`]),tools:t(p(i(),Q.optional()))})])}),d({type:m(`response.function_call_arguments.delta`),item_id:i(),output_index:R(),delta:i()}),d({type:m(`response.custom_tool_call_input.delta`),item_id:i(),output_index:R(),delta:i()}),d({type:m(`response.image_generation_call.partial_image`),item_id:i(),output_index:R(),partial_image_b64:i()}),d({type:m(`response.code_interpreter_call_code.delta`),item_id:i(),output_index:R(),delta:i()}),d({type:m(`response.code_interpreter_call_code.done`),item_id:i(),output_index:R(),code:i()}),d({type:m(`response.output_text.annotation.added`),annotation:r(`type`,[d({type:m(`url_citation`),start_index:R(),end_index:R(),url:i(),title:i()}),d({type:m(`file_citation`),file_id:i(),filename:i(),index:R()}),d({type:m(`container_file_citation`),container_id:i(),file_id:i(),filename:i(),start_index:R(),end_index:R()}),d({type:m(`file_path`),file_id:i(),index:R()})])}),d({type:m(`response.reasoning_summary_part.added`),item_id:i(),summary_index:R()}),d({type:m(`response.reasoning_summary_text.delta`),item_id:i(),summary_index:R(),delta:i()}),d({type:m(`response.reasoning_summary_part.done`),item_id:i(),summary_index:R()}),d({type:m(`response.apply_patch_call_operation_diff.delta`),item_id:i(),output_index:R(),delta:i(),obfuscation:i().nullish()}),d({type:m(`response.apply_patch_call_operation_diff.done`),item_id:i(),output_index:R(),diff:i()}),Qt,$t,d({type:i()}).loose().transform(e=>({type:`unknown_chunk`,message:e.type}))]))),tn=b(()=>F(d({id:i().optional(),created_at:R().optional(),error:d({message:i(),type:i(),param:i().nullish(),code:i()}).nullish(),model:i().optional(),output:t(r(`type`,[d({type:m(`message`),role:m(`assistant`),id:i(),phase:q([`commentary`,`final_answer`]).nullish(),content:t(d({type:m(`output_text`),text:i(),logprobs:t(d({token:i(),logprob:R(),top_logprobs:t(d({token:i(),logprob:R()}))})).nullish(),annotations:t(r(`type`,[d({type:m(`url_citation`),start_index:R(),end_index:R(),url:i(),title:i()}),d({type:m(`file_citation`),file_id:i(),filename:i(),index:R()}),d({type:m(`container_file_citation`),container_id:i(),file_id:i(),filename:i(),start_index:R(),end_index:R()}),d({type:m(`file_path`),file_id:i(),index:R()})]))}))}),d({type:m(`web_search_call`),id:i(),status:i(),action:r(`type`,[d({type:m(`search`),query:i().nullish(),queries:t(i()).nullish(),sources:t(r(`type`,[d({type:m(`url`),url:i()}),d({type:m(`api`),name:i()})])).nullish()}),d({type:m(`open_page`),url:i().nullish()}),d({type:m(`find_in_page`),url:i().nullish(),pattern:i().nullish()})]).nullish()}),d({type:m(`file_search_call`),id:i(),queries:t(i()),results:t(d({attributes:p(i(),l([i(),R(),G()])),file_id:i(),filename:i(),score:R(),text:i()})).nullish()}),d({type:m(`code_interpreter_call`),id:i(),code:i().nullable(),container_id:i(),outputs:t(r(`type`,[d({type:m(`logs`),logs:i()}),d({type:m(`image`),url:i()})])).nullable()}),d({type:m(`image_generation_call`),id:i(),result:i()}),d({type:m(`local_shell_call`),id:i(),call_id:i(),action:d({type:m(`exec`),command:t(i()),timeout_ms:R().optional(),user:i().optional(),working_directory:i().optional(),env:p(i(),i()).optional()})}),d({type:m(`function_call`),call_id:i(),name:i(),arguments:i(),id:i(),namespace:i().nullish()}),d({type:m(`custom_tool_call`),call_id:i(),name:i(),input:i(),id:i()}),d({type:m(`computer_call`),id:i(),status:i().optional()}),d({type:m(`reasoning`),id:i(),encrypted_content:i().nullish(),summary:t(d({type:m(`summary_text`),text:i()}))}),d({type:m(`mcp_call`),id:i(),status:i(),arguments:i(),name:i(),server_label:i(),output:i().nullish(),error:l([i(),d({type:i().optional(),code:l([R(),i()]).optional(),message:i().optional()}).loose()]).nullish(),approval_request_id:i().nullish()}),d({type:m(`mcp_list_tools`),id:i(),server_label:i(),tools:t(d({name:i(),description:i().optional(),input_schema:v(),annotations:p(i(),g()).optional()})),error:l([i(),d({type:i().optional(),code:l([R(),i()]).optional(),message:i().optional()}).loose()]).optional()}),d({type:m(`mcp_approval_request`),id:i(),server_label:i(),name:i(),arguments:i(),approval_request_id:i().optional()}),d({type:m(`apply_patch_call`),id:i(),call_id:i(),status:q([`in_progress`,`completed`]),operation:r(`type`,[d({type:m(`create_file`),path:i(),diff:i()}),d({type:m(`delete_file`),path:i()}),d({type:m(`update_file`),path:i(),diff:i()})])}),d({type:m(`shell_call`),id:i(),call_id:i(),status:q([`in_progress`,`completed`,`incomplete`]),action:d({commands:t(i())})}),d({type:m(`compaction`),id:i(),encrypted_content:i()}),d({type:m(`shell_call_output`),id:i(),call_id:i(),status:q([`in_progress`,`completed`,`incomplete`]),output:t(d({stdout:i(),stderr:i(),outcome:r(`type`,[d({type:m(`timeout`)}),d({type:m(`exit`),exit_code:R()})])}))}),d({type:m(`tool_search_call`),id:i(),execution:q([`server`,`client`]),call_id:i().nullable(),status:q([`in_progress`,`completed`,`incomplete`]),arguments:g()}),d({type:m(`tool_search_output`),id:i(),execution:q([`server`,`client`]),call_id:i().nullable(),status:q([`in_progress`,`completed`,`incomplete`]),tools:t(p(i(),Q.optional()))})])).optional(),service_tier:i().nullish(),incomplete_details:d({reason:i()}).nullish(),usage:d({input_tokens:R(),input_tokens_details:d({cached_tokens:R().nullish(),orchestration_input_tokens:R().nullish(),orchestration_input_cached_tokens:R().nullish()}).nullish(),output_tokens:R(),output_tokens_details:d({reasoning_tokens:R().nullish(),orchestration_output_tokens:R().nullish()}).nullish()}).optional()}))),nn=20,rn=b(()=>F(d({conversation:i().nullish(),include:t(q([`reasoning.encrypted_content`,`file_search_call.results`,`web_search_call.results`,`message.output_text.logprobs`])).nullish(),instructions:i().nullish(),logprobs:l([G(),R().min(1).max(nn)]).optional(),maxToolCalls:R().nullish(),metadata:v().nullish(),parallelToolCalls:G().nullish(),previousResponseId:i().nullish(),promptCacheKey:i().nullish(),promptCacheRetention:q([`in_memory`,`24h`]).nullish(),reasoningEffort:i().nullish(),reasoningSummary:i().nullish(),safetyIdentifier:i().nullish(),serviceTier:q([`auto`,`flex`,`priority`,`default`]).nullish(),store:G().nullish(),passThroughUnsupportedFiles:G().optional(),strictJsonSchema:G().nullish(),textVerbosity:q([`low`,`medium`,`high`]).nullish(),truncation:q([`auto`,`disabled`]).nullish(),user:i().nullish(),systemMessageMode:q([`system`,`developer`,`remove`]).optional(),forceReasoning:G().optional(),contextManagement:t(d({type:m(`compaction`),compactThreshold:R()})).nullish(),allowedTools:d({toolNames:t(i()).min(1),mode:q([`auto`,`required`]).optional()}).optional()})));async function an({tools:e,toolChoice:t,allowedTools:n,toolNameMapping:r,customProviderToolNames:i}){e=e?.length?e:void 0;let a=[];if(e==null)return{tools:void 0,toolChoice:void 0,toolWarnings:a};let o=[],s=new Map,c=i??new Set;for(let t of e)switch(t.type){case`function`:{let e=t.providerOptions?.openai,n=on({tool:t,options:e}),r=e?.namespace;if(r==null)o.push(n);else{let e=s.get(r.name);if(e==null)e={type:`namespace`,name:r.name,description:r.description,tools:[]},s.set(r.name,e),o.push(e);else if(e.description!==r.description)throw new H({functionality:`conflicting descriptions for OpenAI tool namespace "${r.name}"`});e.tools.push(n)}break}case`provider`:switch(t.id){case`openai.file_search`:{let e=await M({value:t.args,schema:mt});o.push({type:`file_search`,vector_store_ids:e.vectorStoreIds,max_num_results:e.maxNumResults,ranking_options:e.ranking?{ranker:e.ranking.ranker,score_threshold:e.ranking.scoreThreshold}:void 0,filters:e.filters});break}case`openai.local_shell`:o.push({type:`local_shell`});break;case`openai.shell`:{let e=await M({value:t.args,schema:Et});o.push({type:`shell`,...e.environment&&{environment:sn(e.environment)}});break}case`openai.apply_patch`:o.push({type:`apply_patch`});break;case`openai.web_search_preview`:{let e=await M({value:t.args,schema:It});o.push({type:`web_search_preview`,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.web_search`:{let e=await M({value:t.args,schema:Nt});o.push({type:`web_search`,filters:e.filters==null?void 0:{allowed_domains:e.filters.allowedDomains},external_web_access:e.externalWebAccess,search_context_size:e.searchContextSize,user_location:e.userLocation});break}case`openai.code_interpreter`:{let e=await M({value:t.args,schema:ot});o.push({type:`code_interpreter`,container:e.container==null?{type:`auto`,file_ids:void 0}:typeof e.container==`string`?e.container:{type:`auto`,file_ids:e.container.fileIds}});break}case`openai.image_generation`:{let e=await M({value:t.args,schema:_t});o.push({type:`image_generation`,background:e.background,input_fidelity:e.inputFidelity,input_image_mask:e.inputImageMask?{file_id:e.inputImageMask.fileId,image_url:e.inputImageMask.imageUrl}:void 0,model:e.model,moderation:e.moderation,partial_images:e.partialImages,quality:e.quality,output_compression:e.outputCompression,output_format:e.outputFormat,size:e.size});break}case`openai.mcp`:{let e=await M({value:t.args,schema:zt}),n=e=>({tool_names:e.toolNames}),r=e.requireApproval,i=r==null?void 0:typeof r==`string`?r:r.never==null?void 0:{never:n(r.never)};o.push({type:`mcp`,server_label:e.serverLabel,allowed_tools:Array.isArray(e.allowedTools)?e.allowedTools:e.allowedTools?{read_only:e.allowedTools.readOnly,tool_names:e.allowedTools.toolNames}:void 0,authorization:e.authorization,connector_id:e.connectorId,headers:e.headers,require_approval:i??`never`,server_description:e.serverDescription,server_url:e.serverUrl});break}case`openai.custom`:{let e=await M({value:t.args,schema:lt});o.push({type:`custom`,name:t.name,description:e.description,format:e.format}),c.add(t.name);break}case`openai.tool_search`:{let e=await M({value:t.args,schema:Ot});o.push({type:`tool_search`,...e.execution==null?{}:{execution:e.execution},...e.description==null?{}:{description:e.description},...e.parameters==null?{}:{parameters:e.parameters}});break}}break;default:a.push({type:`unsupported`,feature:`function tool ${t}`});break}if(n!=null)return{tools:o,toolChoice:{type:`allowed_tools`,mode:n.mode??`auto`,tools:n.toolNames.map(e=>({type:`function`,name:r?.toProviderToolName(e)??e}))},toolWarnings:a};if(t==null)return{tools:o,toolChoice:void 0,toolWarnings:a};let l=t.type;switch(l){case`auto`:case`none`:case`required`:return{tools:o,toolChoice:l,toolWarnings:a};case`tool`:{let e=r?.toProviderToolName(t.toolName)??t.toolName;return{tools:o,toolChoice:e===`code_interpreter`||e===`file_search`||e===`image_generation`||e===`web_search_preview`||e===`web_search`||e===`mcp`||e===`apply_patch`?{type:e}:c.has(e)?{type:`custom`,name:e}:{type:`function`,name:e},toolWarnings:a}}default:throw new H({functionality:`tool choice type: ${l}`})}}function on({tool:e,options:t}){let n=t?.deferLoading;return{type:`function`,name:e.name,description:e.description,parameters:e.inputSchema,...e.strict==null?{}:{strict:e.strict},...n==null?{}:{defer_loading:n}}}function sn(e){if(e.type===`containerReference`)return{type:`container_reference`,container_id:e.containerId};if(e.type===`containerAuto`){let t=e;return{type:`container_auto`,file_ids:t.fileIds,memory_limit:t.memoryLimit,network_policy:t.networkPolicy==null?void 0:t.networkPolicy.type===`disabled`?{type:`disabled`}:{type:`allowlist`,allowed_domains:t.networkPolicy.allowedDomains,domain_secrets:t.networkPolicy.domainSecrets},skills:cn(t.skills)}}return{type:`local`,skills:e.skills}}function cn(e){return e?.map(e=>e.type===`skillReference`?{type:`skill_reference`,skill_id:L({reference:e.providerReference??{},provider:`openai`}),version:e.version??`latest`}:{type:`inline`,name:e.name,description:e.description,source:{type:`base64`,media_type:e.source.mediaType,data:e.source.data}})}function ln(e){let t={};for(let n of e)if(n.role===`assistant`)for(let e of n.content){if(e.type!==`tool-call`)continue;let n=e.providerOptions?.openai?.approvalRequestId;n!=null&&(t[n]=e.toolCallId)}return t}var un=class t{constructor(e,t){this.specificationVersion=`v4`,this.supportedUrls={"image/*":[/^https?:\/\/.*$/],"application/pdf":[/^https?:\/\/.*$/]},this.modelId=e,this.config=t}static[D](e){return V({modelId:e.modelId,config:e.config})}static[N](e){return new t(e.modelId,e.config)}get provider(){return this.config.provider}async getArgs({maxOutputTokens:e,temperature:t,stopSequences:n,topP:r,topK:i,presencePenalty:a,frequencyPenalty:o,seed:c,prompt:l,reasoning:u,providerOptions:d,tools:f,toolChoice:p,responseFormat:m}){let h=[],g=pe(this.modelId);i!=null&&h.push({type:`unsupported`,feature:`topK`}),c!=null&&h.push({type:`unsupported`,feature:`seed`}),a!=null&&h.push({type:`unsupported`,feature:`presencePenalty`}),o!=null&&h.push({type:`unsupported`,feature:`frequencyPenalty`}),n!=null&&h.push({type:`unsupported`,feature:`stopSequences`});let v=this.config.provider.includes(`azure`)?`azure`:`openai`,y=await T({provider:v,providerOptions:d,schema:rn});y==null&&v!==`openai`&&(y=await T({provider:`openai`,providerOptions:d,schema:rn}));let b=y?.reasoningEffort??(s(u)?u:void 0),x=y?.reasoningSummary===void 0?b!=null&&b!==`none`?`detailed`:void 0:y.reasoningSummary,S=y?.forceReasoning??g.isReasoningModel;y?.conversation&&y?.previousResponseId&&h.push({type:`unsupported`,feature:`conversation`,details:`conversation and previousResponseId cannot be used together`});let C=_({tools:f,providerToolNames:{"openai.code_interpreter":`code_interpreter`,"openai.file_search":`file_search`,"openai.image_generation":`image_generation`,"openai.local_shell":`local_shell`,"openai.shell":`shell`,"openai.web_search":`web_search`,"openai.web_search_preview":`web_search_preview`,"openai.mcp":`mcp`,"openai.apply_patch":`apply_patch`,"openai.tool_search":`tool_search`}}),w=new Set,{tools:E,toolChoice:D,toolWarnings:O}=await an({tools:f,toolChoice:p,allowedTools:y?.allowedTools??void 0,toolNameMapping:C,customProviderToolNames:w}),{input:k,warnings:A}=await Yt({prompt:l,toolNameMapping:C,systemMessageMode:y?.systemMessageMode??(S?`developer`:g.systemMessageMode),providerOptionsName:v,fileIdPrefixes:this.config.fileIdPrefixes,passThroughUnsupportedFiles:y?.passThroughUnsupportedFiles??!1,store:y?.store??!0,hasConversation:y?.conversation!=null,hasPreviousResponseId:y?.previousResponseId!=null,hasLocalShellTool:P(`openai.local_shell`),hasShellTool:P(`openai.shell`),hasApplyPatchTool:P(`openai.apply_patch`),customProviderToolNames:w.size>0?w:void 0});h.push(...A);let j=y?.strictJsonSchema??!0,M=y?.include;function N(e){M==null?M=[e]:M.includes(e)||(M=[...M,e])}function P(e){return f?.find(t=>t.type===`provider`&&t.id===e)!=null}let F=typeof y?.logprobs==`number`?y?.logprobs:y?.logprobs===!0?nn:void 0;F&&N(`message.output_text.logprobs`);let I=f?.find(e=>e.type===`provider`&&(e.id===`openai.web_search`||e.id===`openai.web_search_preview`))?.name;I&&N(`web_search_call.action.sources`),P(`openai.code_interpreter`)&&N(`code_interpreter_call.outputs`);let L=y?.store;L===!1&&S&&N(`reasoning.encrypted_content`);let R={model:this.modelId,input:k,temperature:t,top_p:r,max_output_tokens:e,...(m?.type===`json`||y?.textVerbosity)&&{text:{...m?.type===`json`&&{format:m.schema==null?{type:`json_object`}:{type:`json_schema`,strict:j,name:m.name??`response`,description:m.description,schema:m.schema}},...y?.textVerbosity&&{verbosity:y.textVerbosity}}},conversation:y?.conversation,max_tool_calls:y?.maxToolCalls,metadata:y?.metadata,parallel_tool_calls:y?.parallelToolCalls,previous_response_id:y?.previousResponseId,store:L,user:y?.user,instructions:y?.instructions,service_tier:y?.serviceTier,include:M,prompt_cache_key:y?.promptCacheKey,prompt_cache_retention:y?.promptCacheRetention,safety_identifier:y?.safetyIdentifier,top_logprobs:F,truncation:y?.truncation,...y?.contextManagement&&{context_management:y.contextManagement.map(e=>({type:e.type,compact_threshold:e.compactThreshold}))},...S&&(b!=null||x!=null)&&{reasoning:{...b!=null&&{effort:b},...x!=null&&{summary:x}}}};S?b===`none`&&g.supportsNonReasoningParameters||(R.temperature!=null&&(R.temperature=void 0,h.push({type:`unsupported`,feature:`temperature`,details:`temperature is not supported for reasoning models`})),R.top_p!=null&&(R.top_p=void 0,h.push({type:`unsupported`,feature:`topP`,details:`topP is not supported for reasoning models`}))):(y?.reasoningEffort!=null&&h.push({type:`unsupported`,feature:`reasoningEffort`,details:`reasoningEffort is not supported for non-reasoning models`}),y?.reasoningSummary!=null&&h.push({type:`unsupported`,feature:`reasoningSummary`,details:`reasoningSummary is not supported for non-reasoning models`})),y?.serviceTier===`flex`&&!g.supportsFlexProcessing&&(h.push({type:`unsupported`,feature:`serviceTier`,details:`flex processing is only available for o3, o4-mini, and gpt-5 models`}),delete R.service_tier),y?.serviceTier===`priority`&&!g.supportsPriorityProcessing&&(h.push({type:`unsupported`,feature:`serviceTier`,details:`priority processing is only available for supported models (gpt-4, gpt-5, gpt-5-mini, o3, o4-mini) and requires Enterprise access. gpt-5-nano is not supported`}),delete R.service_tier);let z=f?.find(e=>e.type===`provider`&&e.id===`openai.shell`)?.args?.environment?.type,B=z===`containerAuto`||z===`containerReference`;return{webSearchToolName:I,args:{...R,tools:E,tool_choice:D},warnings:[...h,...O],store:L,toolNameMapping:C,providerOptionsName:v,isShellProviderExecuted:B}}async doGenerate(t){var n,r,i,a,o,s;let{args:c,warnings:l,webSearchToolName:u,toolNameMapping:d,providerOptionsName:f,isShellProviderExecuted:p}=await this.getArgs(t),m=this.config.url({path:`/responses`,modelId:this.modelId}),h=ln(t.prompt),{responseHeaders:g,value:_,rawValue:v}=await e({url:m,headers:k((n=this.config).headers?.call(n),t.headers),body:c,failedResponseHandler:Y,successfulResponseHandler:W(tn),abortSignal:t.abortSignal,fetch:this.config.fetch});if(_.error)throw new S({message:_.error.message,url:m,requestBodyValues:c,statusCode:400,responseHeaders:g,responseBody:v,isRetryable:!1});let y=[],b=[],x=!1,C=[];for(let e of _.output)switch(e.type){case`reasoning`:e.summary.length===0&&e.summary.push({type:`summary_text`,text:``});for(let t of e.summary)y.push({type:`reasoning`,text:t.text,providerMetadata:{[f]:{itemId:e.id,reasoningEncryptedContent:e.encrypted_content??null}}});break;case`image_generation_call`:y.push({type:`tool-call`,toolCallId:e.id,toolName:d.toCustomToolName(`image_generation`),input:`{}`,providerExecuted:!0}),y.push({type:`tool-result`,toolCallId:e.id,toolName:d.toCustomToolName(`image_generation`),result:{result:e.result}});break;case`tool_search_call`:{let t=e.call_id??e.id,n=e.execution===`server`;n&&C.push(t),y.push({type:`tool-call`,toolCallId:t,toolName:d.toCustomToolName(`tool_search`),input:JSON.stringify({arguments:e.arguments,call_id:e.call_id}),...n?{providerExecuted:!0}:{},providerMetadata:{[f]:{itemId:e.id}}});break}case`tool_search_output`:{let t=e.call_id??C.shift()??e.id;y.push({type:`tool-result`,toolCallId:t,toolName:d.toCustomToolName(`tool_search`),result:{tools:e.tools},providerMetadata:{[f]:{itemId:e.id}}});break}case`local_shell_call`:y.push({type:`tool-call`,toolCallId:e.call_id,toolName:d.toCustomToolName(`local_shell`),input:JSON.stringify({action:e.action}),providerMetadata:{[f]:{itemId:e.id}}});break;case`shell_call`:y.push({type:`tool-call`,toolCallId:e.call_id,toolName:d.toCustomToolName(`shell`),input:JSON.stringify({action:{commands:e.action.commands}}),...p&&{providerExecuted:!0},providerMetadata:{[f]:{itemId:e.id}}});break;case`shell_call_output`:y.push({type:`tool-result`,toolCallId:e.call_id,toolName:d.toCustomToolName(`shell`),result:{output:e.output.map(e=>({stdout:e.stdout,stderr:e.stderr,outcome:e.outcome.type===`exit`?{type:`exit`,exitCode:e.outcome.exit_code}:{type:`timeout`}}))}});break;case`message`:for(let n of e.content){t.providerOptions?.[f]?.logprobs&&n.logprobs&&b.push(n.logprobs);let s={itemId:e.id,...e.phase!=null&&{phase:e.phase},...n.annotations.length>0&&{annotations:n.annotations}};y.push({type:`text`,text:n.text,providerMetadata:{[f]:s}});for(let e of n.annotations)e.type===`url_citation`?y.push({type:`source`,sourceType:`url`,id:(r=this.config).generateId?.call(r)??z(),url:e.url,title:e.title}):e.type===`file_citation`?y.push({type:`source`,sourceType:`document`,id:(i=this.config).generateId?.call(i)??z(),mediaType:`text/plain`,title:e.filename,filename:e.filename,providerMetadata:{[f]:{type:e.type,fileId:e.file_id,index:e.index}}}):e.type===`container_file_citation`?y.push({type:`source`,sourceType:`document`,id:(a=this.config).generateId?.call(a)??z(),mediaType:`text/plain`,title:e.filename,filename:e.filename,providerMetadata:{[f]:{type:e.type,fileId:e.file_id,containerId:e.container_id}}}):e.type===`file_path`&&y.push({type:`source`,sourceType:`document`,id:(o=this.config).generateId?.call(o)??z(),mediaType:`application/octet-stream`,title:e.file_id,filename:e.file_id,providerMetadata:{[f]:{type:e.type,fileId:e.file_id,index:e.index}}})}break;case`function_call`:x=!0,y.push({type:`tool-call`,toolCallId:e.call_id,toolName:e.name,input:e.arguments,providerMetadata:{[f]:{itemId:e.id,...e.namespace!=null&&{namespace:e.namespace}}}});break;case`custom_tool_call`:{x=!0;let t=d.toCustomToolName(e.name);y.push({type:`tool-call`,toolCallId:e.call_id,toolName:t,input:JSON.stringify(e.input),providerMetadata:{[f]:{itemId:e.id}}});break}case`web_search_call`:y.push({type:`tool-call`,toolCallId:e.id,toolName:d.toCustomToolName(u??`web_search`),input:JSON.stringify({}),providerExecuted:!0}),y.push({type:`tool-result`,toolCallId:e.id,toolName:d.toCustomToolName(u??`web_search`),result:An(e.action)});break;case`mcp_call`:{let t=e.approval_request_id==null?e.id:h[e.approval_request_id]??e.id,n=`mcp.${e.name}`;y.push({type:`tool-call`,toolCallId:t,toolName:n,input:e.arguments,providerExecuted:!0,dynamic:!0}),y.push({type:`tool-result`,toolCallId:t,toolName:n,result:{type:`call`,serverLabel:e.server_label,name:e.name,arguments:e.arguments,...e.output==null?{}:{output:e.output},...e.error==null?{}:{error:e.error}},providerMetadata:{[f]:{itemId:e.id}}});break}case`mcp_list_tools`:break;case`mcp_approval_request`:{let t=e.approval_request_id??e.id,n=(s=this.config).generateId?.call(s)??z(),r=`mcp.${e.name}`;y.push({type:`tool-call`,toolCallId:n,toolName:r,input:e.arguments,providerExecuted:!0,dynamic:!0}),y.push({type:`tool-approval-request`,approvalId:t,toolCallId:n});break}case`computer_call`:y.push({type:`tool-call`,toolCallId:e.id,toolName:d.toCustomToolName(`computer_use`),input:``,providerExecuted:!0}),y.push({type:`tool-result`,toolCallId:e.id,toolName:d.toCustomToolName(`computer_use`),result:{type:`computer_use_tool_result`,status:e.status||`completed`}});break;case`file_search_call`:y.push({type:`tool-call`,toolCallId:e.id,toolName:d.toCustomToolName(`file_search`),input:`{}`,providerExecuted:!0}),y.push({type:`tool-result`,toolCallId:e.id,toolName:d.toCustomToolName(`file_search`),result:{queries:e.queries,results:e.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null}});break;case`code_interpreter_call`:y.push({type:`tool-call`,toolCallId:e.id,toolName:d.toCustomToolName(`code_interpreter`),input:JSON.stringify({code:e.code,containerId:e.container_id}),providerExecuted:!0}),y.push({type:`tool-result`,toolCallId:e.id,toolName:d.toCustomToolName(`code_interpreter`),result:{outputs:e.outputs}});break;case`apply_patch_call`:y.push({type:`tool-call`,toolCallId:e.call_id,toolName:d.toCustomToolName(`apply_patch`),input:JSON.stringify({callId:e.call_id,operation:e.operation}),providerMetadata:{[f]:{itemId:e.id}}});break;case`compaction`:y.push({type:`custom`,kind:`openai.compaction`,providerMetadata:{[f]:{type:`compaction`,itemId:e.id,encryptedContent:e.encrypted_content}}});break}let w={[f]:{responseId:_.id,...b.length>0?{logprobs:b}:{},...typeof _.service_tier==`string`?{serviceTier:_.service_tier}:{}}},T=_.usage;return{content:y,finishReason:{unified:Zt({finishReason:_.incomplete_details?.reason,hasFunctionCall:x}),raw:_.incomplete_details?.reason??void 0},usage:Kt(T),request:{body:c},response:{id:_.id,timestamp:new Date(_.created_at*1e3),modelId:_.model,headers:g,body:v},providerMetadata:w,warnings:l}}async doStream(t){var n;let{args:r,warnings:i,webSearchToolName:a,toolNameMapping:o,store:s,providerOptionsName:c,isShellProviderExecuted:l}=await this.getArgs(t),u=this.config.url({path:`/responses`,modelId:this.modelId}),{responseHeaders:d,value:f}=await e({url:u,headers:k((n=this.config).headers?.call(n),t.headers),body:{...r,stream:!0},failedResponseHandler:Y,successfulResponseHandler:P(en),abortSignal:t.abortSignal,fetch:this.config.fetch}),p=await X({stream:f,getError:e=>On(e)||_n(e)&&e.response.error!=null?e:void 0,isOutputChunk:kn,url:u,requestBodyValues:r,responseHeaders:d}),m=this,h=ln(t.prompt),g=new Map,_={unified:`other`,raw:void 0},v,y=[],b=null,x={},S=[],C,w=!1,T={},E,D=[],O=!1;return{stream:p.pipeThrough(new TransformStream({start(e){e.enqueue({type:`stream-start`,warnings:i})},transform(e,n){var i,f,p,k,A;if(t.includeRawChunks&&n.enqueue({type:`raw`,rawValue:e.rawValue}),!e.success){let t=fn(e.rawValue)?pn({value:e.rawValue,cause:e.error,url:u,requestBodyValues:r,responseHeaders:d}):e.error;_={unified:`error`,raw:void 0},n.enqueue({type:`error`,error:t});return}let j=e.value;if(En(j)){if(j.item.type===`function_call`)x[j.output_index]={toolName:j.item.name,toolCallId:j.item.call_id},n.enqueue({type:`tool-input-start`,id:j.item.call_id,toolName:j.item.name});else if(j.item.type===`custom_tool_call`){let e=o.toCustomToolName(j.item.name);x[j.output_index]={toolName:e,toolCallId:j.item.call_id},n.enqueue({type:`tool-input-start`,id:j.item.call_id,toolName:e})}else if(j.item.type===`web_search_call`)x[j.output_index]={toolName:o.toCustomToolName(a??`web_search`),toolCallId:j.item.id},n.enqueue({type:`tool-input-start`,id:j.item.id,toolName:o.toCustomToolName(a??`web_search`),providerExecuted:!0}),n.enqueue({type:`tool-input-end`,id:j.item.id}),n.enqueue({type:`tool-call`,toolCallId:j.item.id,toolName:o.toCustomToolName(a??`web_search`),input:JSON.stringify({}),providerExecuted:!0});else if(j.item.type===`computer_call`)x[j.output_index]={toolName:o.toCustomToolName(`computer_use`),toolCallId:j.item.id},n.enqueue({type:`tool-input-start`,id:j.item.id,toolName:o.toCustomToolName(`computer_use`),providerExecuted:!0});else if(j.item.type===`code_interpreter_call`)x[j.output_index]={toolName:o.toCustomToolName(`code_interpreter`),toolCallId:j.item.id,codeInterpreter:{containerId:j.item.container_id}},n.enqueue({type:`tool-input-start`,id:j.item.id,toolName:o.toCustomToolName(`code_interpreter`),providerExecuted:!0}),n.enqueue({type:`tool-input-delta`,id:j.item.id,delta:`{"containerId":"${j.item.container_id}","code":"`});else if(j.item.type===`file_search_call`)n.enqueue({type:`tool-call`,toolCallId:j.item.id,toolName:o.toCustomToolName(`file_search`),input:`{}`,providerExecuted:!0});else if(j.item.type===`image_generation_call`)n.enqueue({type:`tool-call`,toolCallId:j.item.id,toolName:o.toCustomToolName(`image_generation`),input:`{}`,providerExecuted:!0});else if(j.item.type===`tool_search_call`){let e=j.item.id,t=o.toCustomToolName(`tool_search`),r=j.item.execution===`server`;x[j.output_index]={toolName:t,toolCallId:e,toolSearchExecution:j.item.execution??`server`},r&&n.enqueue({type:`tool-input-start`,id:e,toolName:t,providerExecuted:!0})}else if(j.item.type!==`tool_search_output`&&!(j.item.type===`mcp_call`||j.item.type===`mcp_list_tools`||j.item.type===`mcp_approval_request`))if(j.item.type===`apply_patch_call`){let{call_id:e,operation:t}=j.item;if(x[j.output_index]={toolName:o.toCustomToolName(`apply_patch`),toolCallId:e,applyPatch:{hasDiff:t.type===`delete_file`,endEmitted:t.type===`delete_file`}},n.enqueue({type:`tool-input-start`,id:e,toolName:o.toCustomToolName(`apply_patch`)}),t.type===`delete_file`){let r=JSON.stringify({callId:e,operation:t});n.enqueue({type:`tool-input-delta`,id:e,delta:r}),n.enqueue({type:`tool-input-end`,id:e})}else n.enqueue({type:`tool-input-delta`,id:e,delta:`{"callId":"${$(e)}","operation":{"type":"${$(t.type)}","path":"${$(t.path)}","diff":"`})}else j.item.type===`shell_call`?x[j.output_index]={toolName:o.toCustomToolName(`shell`),toolCallId:j.item.call_id}:j.item.type===`shell_call_output`||(j.item.type===`message`?(S.splice(0,S.length),C=j.item.phase??void 0,n.enqueue({type:`text-start`,id:j.item.id,providerMetadata:{[c]:{itemId:j.item.id,...j.item.phase!=null&&{phase:j.item.phase}}}})):En(j)&&j.item.type===`reasoning`&&(T[j.item.id]={encryptedContent:j.item.encrypted_content,summaryParts:{0:`active`}},n.enqueue({type:`reasoning-start`,id:`${j.item.id}:0`,providerMetadata:{[c]:{itemId:j.item.id,reasoningEncryptedContent:j.item.encrypted_content??null}}})))}else if(hn(j))if(j.item.type===`message`){let e=j.item.phase??C;C=void 0,n.enqueue({type:`text-end`,id:j.item.id,providerMetadata:{[c]:{itemId:j.item.id,...e!=null&&{phase:e},...S.length>0&&{annotations:S}}}})}else if(j.item.type===`function_call`)x[j.output_index]=void 0,w=!0,n.enqueue({type:`tool-input-end`,id:j.item.call_id,...j.item.namespace!=null&&{providerMetadata:{[c]:{namespace:j.item.namespace}}}}),n.enqueue({type:`tool-call`,toolCallId:j.item.call_id,toolName:j.item.name,input:j.item.arguments,providerMetadata:{[c]:{itemId:j.item.id,...j.item.namespace!=null&&{namespace:j.item.namespace}}}});else if(j.item.type===`custom_tool_call`){x[j.output_index]=void 0,w=!0;let e=o.toCustomToolName(j.item.name);n.enqueue({type:`tool-input-end`,id:j.item.call_id}),n.enqueue({type:`tool-call`,toolCallId:j.item.call_id,toolName:e,input:JSON.stringify(j.item.input),providerMetadata:{[c]:{itemId:j.item.id}}})}else if(j.item.type===`web_search_call`)x[j.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:j.item.id,toolName:o.toCustomToolName(a??`web_search`),result:An(j.item.action)});else if(j.item.type===`computer_call`)x[j.output_index]=void 0,n.enqueue({type:`tool-input-end`,id:j.item.id}),n.enqueue({type:`tool-call`,toolCallId:j.item.id,toolName:o.toCustomToolName(`computer_use`),input:``,providerExecuted:!0}),n.enqueue({type:`tool-result`,toolCallId:j.item.id,toolName:o.toCustomToolName(`computer_use`),result:{type:`computer_use_tool_result`,status:j.item.status||`completed`}});else if(j.item.type===`file_search_call`)x[j.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:j.item.id,toolName:o.toCustomToolName(`file_search`),result:{queries:j.item.queries,results:j.item.results?.map(e=>({attributes:e.attributes,fileId:e.file_id,filename:e.filename,score:e.score,text:e.text}))??null}});else if(j.item.type===`code_interpreter_call`)x[j.output_index]=void 0,n.enqueue({type:`tool-result`,toolCallId:j.item.id,toolName:o.toCustomToolName(`code_interpreter`),result:{outputs:j.item.outputs}});else if(j.item.type===`image_generation_call`)n.enqueue({type:`tool-result`,toolCallId:j.item.id,toolName:o.toCustomToolName(`image_generation`),result:{result:j.item.result}});else if(j.item.type===`tool_search_call`){let e=x[j.output_index],t=j.item.execution===`server`;if(e!=null){let r=t?e.toolCallId:j.item.call_id??j.item.id;t?D.push(r):n.enqueue({type:`tool-input-start`,id:r,toolName:e.toolName}),n.enqueue({type:`tool-input-end`,id:r}),n.enqueue({type:`tool-call`,toolCallId:r,toolName:e.toolName,input:JSON.stringify({arguments:j.item.arguments,call_id:t?null:r}),...t?{providerExecuted:!0}:{},providerMetadata:{[c]:{itemId:j.item.id}}})}x[j.output_index]=void 0}else if(j.item.type===`tool_search_output`){let e=j.item.call_id??D.shift()??j.item.id;n.enqueue({type:`tool-result`,toolCallId:e,toolName:o.toCustomToolName(`tool_search`),result:{tools:j.item.tools},providerMetadata:{[c]:{itemId:j.item.id}}})}else if(j.item.type===`mcp_call`){x[j.output_index]=void 0;let e=j.item.approval_request_id??void 0,t=e==null?j.item.id:g.get(e)??h[e]??j.item.id,r=`mcp.${j.item.name}`;n.enqueue({type:`tool-call`,toolCallId:t,toolName:r,input:j.item.arguments,providerExecuted:!0,dynamic:!0}),n.enqueue({type:`tool-result`,toolCallId:t,toolName:r,result:{type:`call`,serverLabel:j.item.server_label,name:j.item.name,arguments:j.item.arguments,...j.item.output==null?{}:{output:j.item.output},...j.item.error==null?{}:{error:j.item.error}},providerMetadata:{[c]:{itemId:j.item.id}}})}else if(j.item.type===`mcp_list_tools`)x[j.output_index]=void 0;else if(j.item.type===`apply_patch_call`){let e=x[j.output_index];e?.applyPatch&&!e.applyPatch.endEmitted&&j.item.operation.type!==`delete_file`&&(e.applyPatch.hasDiff||n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:$(j.item.operation.diff)}),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),e.applyPatch.endEmitted=!0),e&&j.item.status===`completed`&&n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:o.toCustomToolName(`apply_patch`),input:JSON.stringify({callId:j.item.call_id,operation:j.item.operation}),providerMetadata:{[c]:{itemId:j.item.id}}}),x[j.output_index]=void 0}else if(j.item.type===`mcp_approval_request`){x[j.output_index]=void 0;let e=(i=m.config).generateId?.call(i)??z(),t=j.item.approval_request_id??j.item.id;g.set(t,e);let r=`mcp.${j.item.name}`;n.enqueue({type:`tool-call`,toolCallId:e,toolName:r,input:j.item.arguments,providerExecuted:!0,dynamic:!0}),n.enqueue({type:`tool-approval-request`,approvalId:t,toolCallId:e})}else if(j.item.type===`local_shell_call`)x[j.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:j.item.call_id,toolName:o.toCustomToolName(`local_shell`),input:JSON.stringify({action:{type:`exec`,command:j.item.action.command,timeoutMs:j.item.action.timeout_ms,user:j.item.action.user,workingDirectory:j.item.action.working_directory,env:j.item.action.env}}),providerMetadata:{[c]:{itemId:j.item.id}}});else if(j.item.type===`shell_call`)x[j.output_index]=void 0,n.enqueue({type:`tool-call`,toolCallId:j.item.call_id,toolName:o.toCustomToolName(`shell`),input:JSON.stringify({action:{commands:j.item.action.commands}}),...l&&{providerExecuted:!0},providerMetadata:{[c]:{itemId:j.item.id}}});else if(j.item.type===`shell_call_output`)n.enqueue({type:`tool-result`,toolCallId:j.item.call_id,toolName:o.toCustomToolName(`shell`),result:{output:j.item.output.map(e=>({stdout:e.stdout,stderr:e.stderr,outcome:e.outcome.type===`exit`?{type:`exit`,exitCode:e.outcome.exit_code}:{type:`timeout`}}))}});else if(j.item.type===`reasoning`){let e=T[j.item.id],t=Object.entries(e.summaryParts).filter(([e,t])=>t===`active`||t===`can-conclude`).map(([e])=>e);for(let e of t)n.enqueue({type:`reasoning-end`,id:`${j.item.id}:${e}`,providerMetadata:{[c]:{itemId:j.item.id,reasoningEncryptedContent:j.item.encrypted_content??null}}});delete T[j.item.id]}else j.item.type===`compaction`&&n.enqueue({type:`custom`,kind:`openai.compaction`,providerMetadata:{[c]:{type:`compaction`,itemId:j.item.id,encryptedContent:j.item.encrypted_content}}});else if(yn(j)){let e=x[j.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:j.delta})}else if(bn(j)){let e=x[j.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:j.delta})}else if(wn(j)){let e=x[j.output_index];e?.applyPatch&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:$(j.delta)}),e.applyPatch.hasDiff=!0)}else if(Tn(j)){let e=x[j.output_index];e?.applyPatch&&!e.applyPatch.endEmitted&&(e.applyPatch.hasDiff||(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:$(j.diff)}),e.applyPatch.hasDiff=!0),n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),e.applyPatch.endEmitted=!0)}else if(xn(j))n.enqueue({type:`tool-result`,toolCallId:j.item_id,toolName:o.toCustomToolName(`image_generation`),result:{result:j.partial_image_b64},preliminary:!0});else if(Sn(j)){let e=x[j.output_index];e!=null&&n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:$(j.delta)})}else if(Cn(j)){let e=x[j.output_index];e!=null&&(n.enqueue({type:`tool-input-delta`,id:e.toolCallId,delta:`"}`}),n.enqueue({type:`tool-input-end`,id:e.toolCallId}),n.enqueue({type:`tool-call`,toolCallId:e.toolCallId,toolName:o.toCustomToolName(`code_interpreter`),input:JSON.stringify({code:j.code,containerId:e.codeInterpreter.containerId}),providerExecuted:!0}))}else if(vn(j))b=j.response.id,n.enqueue({type:`response-metadata`,id:j.response.id,timestamp:new Date(j.response.created_at*1e3),modelId:j.response.model});else if(dn(j))n.enqueue({type:`text-delta`,id:j.item_id,delta:j.delta}),t.providerOptions?.[c]?.logprobs&&j.logprobs&&y.push(j.logprobs);else if(j.type===`response.reasoning_summary_part.added`){if(j.summary_index>0){let e=T[j.item_id];e.summaryParts[j.summary_index]=`active`;for(let t of Object.keys(e.summaryParts))e.summaryParts[t]===`can-conclude`&&(n.enqueue({type:`reasoning-end`,id:`${j.item_id}:${t}`,providerMetadata:{[c]:{itemId:j.item_id}}}),e.summaryParts[t]=`concluded`);n.enqueue({type:`reasoning-start`,id:`${j.item_id}:${j.summary_index}`,providerMetadata:{[c]:{itemId:j.item_id,reasoningEncryptedContent:T[j.item_id]?.encryptedContent??null}}})}}else if(j.type===`response.reasoning_summary_text.delta`)n.enqueue({type:`reasoning-delta`,id:`${j.item_id}:${j.summary_index}`,delta:j.delta,providerMetadata:{[c]:{itemId:j.item_id}}});else if(j.type===`response.reasoning_summary_part.done`)s?(n.enqueue({type:`reasoning-end`,id:`${j.item_id}:${j.summary_index}`,providerMetadata:{[c]:{itemId:j.item_id}}}),T[j.item_id].summaryParts[j.summary_index]=`concluded`):T[j.item_id].summaryParts[j.summary_index]=`can-conclude`;else if(gn(j))_={unified:Zt({finishReason:j.response.incomplete_details?.reason,hasFunctionCall:w}),raw:j.response.incomplete_details?.reason??void 0},v=j.response.usage,typeof j.response.service_tier==`string`&&(E=j.response.service_tier);else if(_n(j)){let e=j.response.incomplete_details?.reason;_={unified:e?Zt({finishReason:e,hasFunctionCall:w}):`error`,raw:e??`error`},v=j.response.usage??void 0,!O&&j.response.error!=null&&(O=!0,n.enqueue({type:`error`,error:{type:`response.failed`,sequence_number:j.sequence_number,response:{error:j.response.error,incomplete_details:j.response.incomplete_details,service_tier:j.response.service_tier}}}))}else Dn(j)?(S.push(j.annotation),j.annotation.type===`url_citation`?n.enqueue({type:`source`,sourceType:`url`,id:(f=m.config).generateId?.call(f)??z(),url:j.annotation.url,title:j.annotation.title}):j.annotation.type===`file_citation`?n.enqueue({type:`source`,sourceType:`document`,id:(p=m.config).generateId?.call(p)??z(),mediaType:`text/plain`,title:j.annotation.filename,filename:j.annotation.filename,providerMetadata:{[c]:{type:j.annotation.type,fileId:j.annotation.file_id,index:j.annotation.index}}}):j.annotation.type===`container_file_citation`?n.enqueue({type:`source`,sourceType:`document`,id:(k=m.config).generateId?.call(k)??z(),mediaType:`text/plain`,title:j.annotation.filename,filename:j.annotation.filename,providerMetadata:{[c]:{type:j.annotation.type,fileId:j.annotation.file_id,containerId:j.annotation.container_id}}}):j.annotation.type===`file_path`&&n.enqueue({type:`source`,sourceType:`document`,id:(A=m.config).generateId?.call(A)??z(),mediaType:`application/octet-stream`,title:j.annotation.file_id,filename:j.annotation.file_id,providerMetadata:{[c]:{type:j.annotation.type,fileId:j.annotation.file_id,index:j.annotation.index}}})):On(j)&&(O=!0,_={unified:`error`,raw:`error`},n.enqueue({type:`error`,error:j}))},flush(e){let t={[c]:{responseId:b,...y.length>0?{logprobs:y}:{},...E===void 0?{}:{serviceTier:E}}};e.enqueue({type:`finish`,finishReason:_,usage:Kt(v),providerMetadata:t})}})),request:{body:r},response:{headers:d}}}};function dn(e){return e.type===`response.output_text.delta`}function fn(e){let t=mn(e);return t!=null&&Array.isArray(t.choices)&&typeof t.type!=`string`}function pn({value:e,cause:t,url:n,requestBodyValues:r,responseHeaders:i}){return new S({message:`Received a Chat Completions stream while using the OpenAI Responses API. The default OpenAI provider model uses the Responses API. If your custom baseURL targets a Chat Completions-compatible endpoint, use openai.chat('model-id') or createOpenAI(...).chat('model-id') instead. You can also use @ai-sdk/openai-compatible for OpenAI-compatible providers.`,url:n,requestBodyValues:r,responseHeaders:i,responseBody:JSON.stringify(e),cause:t,data:e,isRetryable:!1})}function mn(e){return typeof e==`object`&&e?e:void 0}function hn(e){return e.type===`response.output_item.done`}function gn(e){return e.type===`response.completed`||e.type===`response.incomplete`}function _n(e){return e.type===`response.failed`}function vn(e){return e.type===`response.created`}function yn(e){return e.type===`response.function_call_arguments.delta`}function bn(e){return e.type===`response.custom_tool_call_input.delta`}function xn(e){return e.type===`response.image_generation_call.partial_image`}function Sn(e){return e.type===`response.code_interpreter_call_code.delta`}function Cn(e){return e.type===`response.code_interpreter_call_code.done`}function wn(e){return e.type===`response.apply_patch_call_operation_diff.delta`}function Tn(e){return e.type===`response.apply_patch_call_operation_diff.done`}function En(e){return e.type===`response.output_item.added`}function Dn(e){return e.type===`response.output_text.annotation.added`}function On(e){return e.type===`error`}function kn(e){return!(e.type===`response.created`||e.type===`response.failed`||e.type===`error`||e.type===`unknown_chunk`)}function An(e){if(e==null)return{};switch(e.type){case`search`:return{action:{type:`search`,query:e.query??void 0,...e.queries!=null&&{queries:e.queries}},...e.sources!=null&&{sources:e.sources}};case`open_page`:return{action:{type:`openPage`,url:e.url}};case`find_in_page`:return{action:{type:`findInPage`,url:e.url,pattern:e.pattern}}}}function $(e){return JSON.stringify(e).slice(1,-1)}var jn=b(()=>F(d({instructions:i().nullish(),speed:R().min(.25).max(4).default(1).nullish()}))),Mn=class t{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}static[D](e){return V({modelId:e.modelId,config:e.config})}static[N](e){return new t(e.modelId,e.config)}get provider(){return this.config.provider}async getArgs({text:e,voice:t=`alloy`,outputFormat:n=`mp3`,speed:r,instructions:i,language:a,providerOptions:o}){let s=[],c=await T({provider:`openai`,providerOptions:o,schema:jn}),l={model:this.modelId,input:e,voice:t,response_format:`mp3`,speed:r,instructions:i};if(n&&([`mp3`,`opus`,`aac`,`flac`,`wav`,`pcm`].includes(n)?l.response_format=n:s.push({type:`unsupported`,feature:`outputFormat`,details:`Unsupported output format: ${n}. Using mp3 instead.`})),c){let e={};for(let t in e){let n=e[t];n!==void 0&&(l[t]=n)}}return a&&s.push({type:`unsupported`,feature:`language`,details:`OpenAI speech models do not support language selection. Language parameter "${a}" was ignored.`}),{requestBody:l,warnings:s}}async doGenerate(t){var n,r;let i=((n=this.config._internal)?.currentDate)?.call(n)??new Date,{requestBody:a,warnings:o}=await this.getArgs(t),{value:s,responseHeaders:c,rawValue:l}=await e({url:this.config.url({path:`/audio/speech`,modelId:this.modelId}),headers:k((r=this.config).headers?.call(r),t.headers),body:a,failedResponseHandler:Y,successfulResponseHandler:ee(),abortSignal:t.abortSignal,fetch:this.config.fetch});return{audio:s,warnings:o,request:{body:JSON.stringify(a)},response:{timestamp:i,modelId:this.modelId,headers:c,body:l}}}},Nn=b(()=>F(d({text:i(),language:i().nullish(),duration:R().nullish(),words:t(d({word:i(),start:R(),end:R()})).nullish(),segments:t(d({id:R(),seek:R(),start:R(),end:R(),text:i(),tokens:t(R()),temperature:R(),avg_logprob:R(),compression_ratio:R(),no_speech_prob:R()})).nullish()}))),Pn=b(()=>F(d({include:t(i()).optional(),language:i().optional(),prompt:i().optional(),temperature:R().min(0).max(1).default(0).optional(),timestampGranularities:t(q([`word`,`segment`])).default([`segment`]).optional(),streaming:d({delay:q([`minimal`,`low`,`medium`,`high`,`xhigh`]).optional(),include:t(i()).optional()}).optional()})));function Fn(e){return e===`gpt-realtime-whisper`||e.startsWith(`gpt-realtime-whisper-`)}var In={afrikaans:`af`,arabic:`ar`,armenian:`hy`,azerbaijani:`az`,belarusian:`be`,bosnian:`bs`,bulgarian:`bg`,catalan:`ca`,chinese:`zh`,croatian:`hr`,czech:`cs`,danish:`da`,dutch:`nl`,english:`en`,estonian:`et`,finnish:`fi`,french:`fr`,galician:`gl`,german:`de`,greek:`el`,hebrew:`he`,hindi:`hi`,hungarian:`hu`,icelandic:`is`,indonesian:`id`,italian:`it`,japanese:`ja`,kannada:`kn`,kazakh:`kk`,korean:`ko`,latvian:`lv`,lithuanian:`lt`,macedonian:`mk`,malay:`ms`,marathi:`mr`,maori:`mi`,nepali:`ne`,norwegian:`no`,persian:`fa`,polish:`pl`,portuguese:`pt`,romanian:`ro`,russian:`ru`,serbian:`sr`,slovak:`sk`,slovenian:`sl`,spanish:`es`,swahili:`sw`,swedish:`sv`,tagalog:`tl`,tamil:`ta`,thai:`th`,turkish:`tr`,ukrainian:`uk`,urdu:`ur`,vietnamese:`vi`,welsh:`cy`},Ln=class e{constructor(e,t){this.modelId=e,this.config=t,this.specificationVersion=`v4`}static[D](e){return V({modelId:e.modelId,config:e.config})}static[N](t){return new e(t.modelId,t.config)}get provider(){return this.config.provider}async getArgs({audio:e,mediaType:t,providerOptions:n}){let r=[],i=await T({provider:`openai`,providerOptions:n,schema:Pn}),a=new FormData,o=e instanceof Uint8Array?new Blob([e]):new Blob([B(e)]);a.append(`model`,this.modelId);let s=c(t);if(a.append(`file`,new File([o],`audio`,{type:t}),`audio.${s}`),this.modelId===`whisper-1`&&a.append(`response_format`,`verbose_json`),i){let e=[`gpt-4o-transcribe`,`gpt-4o-mini-transcribe`].includes(this.modelId),t={include:i.include,language:i.language,prompt:i.prompt,...this.modelId!==`whisper-1`&&{response_format:e?`json`:`verbose_json`},temperature:i.temperature,timestamp_granularities:i.timestampGranularities};for(let[e,n]of Object.entries(t))if(n!=null)if(Array.isArray(n))for(let t of n)a.append(`${e}[]`,String(t));else a.append(e,String(n))}return{formData:a,warnings:r}}async doGenerate(e){var t,n;if(Fn(this.modelId))throw new H({functionality:`non-streaming transcription with ${this.modelId}`});let r=((t=this.config._internal)?.currentDate)?.call(t)??new Date,{formData:i,warnings:a}=await this.getArgs(e),{value:o,responseHeaders:s,rawValue:c}=await h({url:this.config.url({path:`/audio/transcriptions`,modelId:this.modelId}),headers:k((n=this.config).headers?.call(n),e.headers),formData:i,failedResponseHandler:Y,successfulResponseHandler:W(Nn),abortSignal:e.abortSignal,fetch:this.config.fetch}),l=o.language!=null&&o.language in In?In[o.language]:void 0;return{text:o.text,segments:o.segments?.map(e=>({text:e.text,startSecond:e.start,endSecond:e.end}))??o.words?.map(e=>({text:e.word,startSecond:e.start,endSecond:e.end}))??[],language:l,durationInSeconds:o.duration??void 0,warnings:a,response:{timestamp:r,modelId:this.modelId,headers:s,body:c}}}async doStream(e){var t,n;if(!Fn(this.modelId))throw new H({functionality:`streaming transcription with ${this.modelId}`});let r=((t=this.config._internal)?.currentDate)?.call(t)??new Date,i=await T({provider:`openai`,providerOptions:e.providerOptions,schema:Pn}),a=[],o=e.providerOptions?.openai??{};for(let e of[`include`,`prompt`,`temperature`,`timestampGranularities`])o[e]!=null&&a.push({type:`unsupported`,feature:`providerOptions.openai.${e}`,details:`OpenAI streaming transcription does not support ${e}.`});let s=k((n=this.config).headers?.call(n),e.headers),c=zn({modelId:this.modelId,inputAudioFormat:e.inputAudioFormat,providerOptions:i});return{request:{body:c},response:{timestamp:r,modelId:this.modelId},stream:Rn({webSocket:this.config.webSocket,url:oe(this.config.url({path:`/realtime?intent=transcription`,modelId:this.modelId})),headers:s,sessionUpdate:c,language:i?.language,warnings:a,audio:e.audio,abortSignal:e.abortSignal,includeRawChunks:e.includeRawChunks})}}};function Rn({webSocket:e,url:t,headers:n,sessionUpdate:r,language:i,warnings:a,audio:o,abortSignal:s,includeRawChunks:c}){let l=!1,u=()=>{};return new ReadableStream({start:d=>{let p=new(f(e))(t,Bn(n),{headers:n}),m;u=e=>{s?.removeEventListener(`abort`,_),m?.cancel().catch(()=>{});try{p.close(e)}catch{}};let h=e=>{l||(l=!0,u(),d.error(e))},g=(e,t)=>{l||(l=!0,t!=null&&d.enqueue({type:`transcript-final`,id:t,text:e}),d.enqueue({type:`finish`,text:e,segments:[],language:i}),d.close(),u(1e3))},_=()=>{h(s?.reason??Error(`Aborted`))};if(s?.aborted){_();return}s?.addEventListener(`abort`,_,{once:!0});let v=async()=>{m=o.getReader();try{for(;;){let{done:e,value:t}=await m.read();if(e||l)break;p.send(JSON.stringify({type:`input_audio_buffer.append`,audio:A(t)}))}}finally{m.releaseLock()}l||p.send(JSON.stringify({type:`input_audio_buffer.commit`}))};p.onopen=()=>{d.enqueue({type:`stream-start`,warnings:a}),p.send(JSON.stringify(r)),v().catch(h)},p.onmessage=e=>{ie(e.data).then(async e=>{let t=await ne({text:e});if(!t.success)return;let n=t.value;switch(c&&d.enqueue({type:`raw`,rawValue:n}),n.type){case`conversation.item.input_audio_transcription.delta`:d.enqueue({type:`transcript-delta`,id:n.item_id,delta:n.delta??``});break;case`conversation.item.input_audio_transcription.completed`:g(n.transcript??``,n.item_id);break;case`error`:h(Error(n.error?.message??`OpenAI realtime error`));break}}).catch(h)},p.onerror=()=>{h(Error(`OpenAI realtime transcription error`))},p.onclose=()=>{l||(l=!0,u(),d.close())}},cancel:()=>{l||(l=!0,u())}})}function zn({modelId:e,inputAudioFormat:t,providerOptions:n}){return{type:`session.update`,session:{type:`transcription`,audio:{input:{format:{type:t.type,...t.rate==null?{}:{rate:t.rate}},transcription:{model:e,...n?.language==null?{}:{language:n.language},...n?.streaming?.delay==null?{}:{delay:n.streaming.delay}},turn_detection:null}},...n?.streaming?.include==null?{}:{include:n.streaming.include}}}}function Bn(e){let t=e.Authorization??e.authorization,n=t?.startsWith(`Bearer `)?t.slice(7):void 0;return n==null?[`realtime`]:[`realtime`,`openai-insecure-api-key.${n}`]}var Vn=b(()=>F(d({id:i(),name:i().nullish(),description:i().nullish(),default_version:i().nullish(),latest_version:i().nullish(),created_at:R(),updated_at:R().nullish()})));b(()=>F(d({id:i(),version:i().nullish(),name:i().nullish(),description:i().nullish()})));var Hn=class{constructor(e){this.config=e,this.specificationVersion=`v4`}get provider(){return this.config.provider}async uploadSkill(e){let t=[];e.displayTitle!=null&&t.push({type:`unsupported`,feature:`displayTitle`});let n=new FormData;for(let t of e.files){let e=ae(t.data);n.append(`files[]`,new Blob([e]),t.path)}let{value:r}=await h({url:this.config.url({path:`/skills`}),headers:k(this.config.headers()),formData:n,failedResponseHandler:Y,successfulResponseHandler:W(Vn),fetch:this.config.fetch});return{providerReference:{openai:r.id},...r.name==null?{}:{name:r.name},...r.description==null?{}:{description:r.description},...r.latest_version==null?{}:{latestVersion:r.latest_version},providerMetadata:{openai:{...r.default_version==null?{}:{defaultVersion:r.default_version},...r.created_at==null?{}:{createdAt:r.created_at},...r.updated_at==null?{}:{updatedAt:r.updated_at}}},warnings:t}}},Un=`4.0.7`;function Wn(e={}){let t=te(a({settingValue:e.baseURL,environmentVariableName:`OPENAI_BASE_URL`}))??`https://api.openai.com/v1`,n=e.name??`openai`,r=()=>re({Authorization:`Bearer ${C({apiKey:e.apiKey,environmentVariableName:`OPENAI_API_KEY`,description:`OpenAI`})}`,"OpenAI-Organization":e.organization,"OpenAI-Project":e.project,...e.headers},`ai-sdk/openai/${Un}`),i=i=>new Oe(i,{provider:`${n}.chat`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),o=i=>new Le(i,{provider:`${n}.completion`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),s=i=>new Ve(i,{provider:`${n}.embedding`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),c=i=>new Qe(i,{provider:`${n}.image`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),l=i=>new Ln(i,{provider:`${n}.transcription`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,webSocket:e.webSocket}),u=i=>new Mn(i,{provider:`${n}.speech`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),d=()=>new We({provider:`${n}.files`,baseURL:t,headers:r,fetch:e.fetch}),f=()=>new Hn({provider:`${n}.skills`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch}),p=e=>{if(new.target)throw Error(`The OpenAI model function cannot be called with the new keyword.`);return m(e)},m=i=>new un(i,{provider:`${n}.responses`,url:({path:e})=>`${t}${e}`,headers:r,fetch:e.fetch,fileIdPrefixes:[`file-`]}),h=i=>new Gt(i,{provider:`${n}.realtime`,baseURL:t,headers:r,fetch:e.fetch}),g=Object.assign(e=>h(e),{getToken:async e=>{let t=await h(e.model).doCreateClientSecret({sessionConfig:e.sessionConfig,expiresAfterSeconds:e.expiresAfterSeconds});return{token:t.token,url:t.url,expiresAt:t.expiresAt}}}),_=function(e){return p(e)};return _.specificationVersion=`v4`,_.languageModel=p,_.chat=i,_.completion=o,_.responses=m,_.embedding=s,_.embeddingModel=s,_.textEmbedding=s,_.textEmbeddingModel=s,_.image=c,_.imageModel=c,_.transcription=l,_.transcriptionModel=l,_.speech=u,_.speechModel=u,_.files=d,_.skills=f,_.experimental_realtime=g,_.tools=Vt,_}Wn();export{Wn as createOpenAI};