@harperfast/harper 5.2.1 → 5.2.2

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 (117) hide show
  1. package/bin/copyDb.ts +19 -7
  2. package/components/deploymentRecorder.ts +102 -11
  3. package/components/operations.js +4 -0
  4. package/config/configUtils.ts +66 -11
  5. package/config/harperConfigEnvVars.ts +114 -17
  6. package/dataLayer/harperBridge/lmdbBridge/lmdbUtility/initializePaths.js +4 -4
  7. package/dist/bin/copyDb.js +20 -7
  8. package/dist/bin/copyDb.js.map +1 -1
  9. package/dist/components/deploymentRecorder.d.ts +6 -0
  10. package/dist/components/deploymentRecorder.js +94 -12
  11. package/dist/components/deploymentRecorder.js.map +1 -1
  12. package/dist/components/operations.js +4 -0
  13. package/dist/components/operations.js.map +1 -1
  14. package/dist/config/configUtils.d.ts +6 -0
  15. package/dist/config/configUtils.js +65 -9
  16. package/dist/config/configUtils.js.map +1 -1
  17. package/dist/config/harperConfigEnvVars.js +108 -16
  18. package/dist/config/harperConfigEnvVars.js.map +1 -1
  19. package/dist/dataLayer/harperBridge/lmdbBridge/lmdbUtility/initializePaths.js +4 -4
  20. package/dist/dataLayer/harperBridge/lmdbBridge/lmdbUtility/initializePaths.js.map +1 -1
  21. package/dist/resources/DatabaseTransaction.d.ts +2 -0
  22. package/dist/resources/DatabaseTransaction.js +6 -5
  23. package/dist/resources/DatabaseTransaction.js.map +1 -1
  24. package/dist/resources/Table.d.ts +2 -1
  25. package/dist/resources/Table.js +66 -16
  26. package/dist/resources/Table.js.map +1 -1
  27. package/dist/resources/auditStore.js +27 -1
  28. package/dist/resources/auditStore.js.map +1 -1
  29. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.d.ts +15 -2
  30. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js +128 -39
  31. package/dist/resources/indexes/HierarchicalNavigableSmallWorld.js.map +1 -1
  32. package/dist/resources/search.d.ts +1 -1
  33. package/dist/resources/search.js +7 -3
  34. package/dist/resources/search.js.map +1 -1
  35. package/dist/server/threads/manageThreads.js +8 -0
  36. package/dist/server/threads/manageThreads.js.map +1 -1
  37. package/dist/sqlEngine/parser/normalizer.js +37 -9
  38. package/dist/sqlEngine/parser/normalizer.js.map +1 -1
  39. package/dist/utility/environment/environmentManager.d.ts +11 -0
  40. package/dist/utility/environment/environmentManager.js +154 -0
  41. package/dist/utility/environment/environmentManager.js.map +1 -1
  42. package/dist/utility/lmdb/environmentUtility.js +2 -1
  43. package/dist/utility/lmdb/environmentUtility.js.map +1 -1
  44. package/npm-shrinkwrap.json +13 -7
  45. package/package.json +2 -2
  46. package/resources/DESIGN.md +1 -0
  47. package/resources/DatabaseTransaction.ts +7 -5
  48. package/resources/Table.ts +77 -16
  49. package/resources/auditStore.ts +32 -1
  50. package/resources/indexes/HierarchicalNavigableSmallWorld.ts +119 -45
  51. package/resources/search.ts +8 -3
  52. package/server/threads/manageThreads.js +8 -0
  53. package/studio/web/assets/{Chat-aApwhRmz.js → Chat-BMUjPklt.js} +5 -5
  54. package/studio/web/assets/{Chat-aApwhRmz.js.map → Chat-BMUjPklt.js.map} +1 -1
  55. package/studio/web/assets/{FloatingChat-sC0H91n9.js → FloatingChat-Cbghuxe5.js} +5 -5
  56. package/studio/web/assets/{FloatingChat-sC0H91n9.js.map → FloatingChat-Cbghuxe5.js.map} +1 -1
  57. package/studio/web/assets/{apiToken-DZ8JhHOI.js → apiToken-CkgTQAqc.js} +2 -2
  58. package/studio/web/assets/{apiToken-DZ8JhHOI.js.map → apiToken-CkgTQAqc.js.map} +1 -1
  59. package/studio/web/assets/{applications-9SEVLIO5.js → applications-WvF4NOTN.js} +13 -13
  60. package/studio/web/assets/applications-WvF4NOTN.js.map +1 -0
  61. package/studio/web/assets/chevron-right-anDJCGlp.js +2 -0
  62. package/studio/web/assets/chevron-right-anDJCGlp.js.map +1 -0
  63. package/studio/web/assets/index-CDeqVx71.css +1 -0
  64. package/studio/web/assets/index-Sevt3MVx.js +819 -0
  65. package/studio/web/assets/index-Sevt3MVx.js.map +1 -0
  66. package/studio/web/assets/index.lazy-Dg5YYPGg.js +14 -0
  67. package/studio/web/assets/{index.lazy-CN1zq4I4.js.map → index.lazy-Dg5YYPGg.js.map} +1 -1
  68. package/studio/web/assets/{jsonMode-Cjj7dtlr.js → jsonMode-CBSEleE7.js} +2 -2
  69. package/studio/web/assets/{jsonMode-Cjj7dtlr.js.map → jsonMode-CBSEleE7.js.map} +1 -1
  70. package/studio/web/assets/languageServices-gxedeeTo.js +2 -0
  71. package/studio/web/assets/languageServices-gxedeeTo.js.map +1 -0
  72. package/studio/web/assets/{notifications-BFAF07xr.js → notifications-Ap84YyQp.js} +2 -2
  73. package/studio/web/assets/{notifications-BFAF07xr.js.map → notifications-Ap84YyQp.js.map} +1 -1
  74. package/studio/web/assets/notifications-vehqyOLM.js +2 -0
  75. package/studio/web/assets/{notifications-CKlYVvVN.js.map → notifications-vehqyOLM.js.map} +1 -1
  76. package/studio/web/assets/{pollUnlessForbidden-HHdQZW1N.js → pollUnlessForbidden-BhzefVRn.js} +2 -2
  77. package/studio/web/assets/pollUnlessForbidden-BhzefVRn.js.map +1 -0
  78. package/studio/web/assets/{profile-A1zhEdFG.js → profile-DzDpRLHY.js} +2 -2
  79. package/studio/web/assets/{profile-A1zhEdFG.js.map → profile-DzDpRLHY.js.map} +1 -1
  80. package/studio/web/assets/queryClient-CgtkoiCY.js +2 -0
  81. package/studio/web/assets/queryClient-CgtkoiCY.js.map +1 -0
  82. package/studio/web/assets/regions-DpJ8s7iN.js +2 -0
  83. package/studio/web/assets/regions-DpJ8s7iN.js.map +1 -0
  84. package/studio/web/assets/register-BDy01-q3.js +3 -0
  85. package/studio/web/assets/register-BDy01-q3.js.map +1 -0
  86. package/studio/web/assets/register-CQHRwNP4.js +3 -0
  87. package/studio/web/assets/register-CQHRwNP4.js.map +1 -0
  88. package/studio/web/assets/{setComponentFile-SEtBt_GV.js → setComponentFile-D0aPcI3W.js} +2 -2
  89. package/studio/web/assets/{setComponentFile-SEtBt_GV.js.map → setComponentFile-D0aPcI3W.js.map} +1 -1
  90. package/studio/web/assets/setup-I15FAF9H.js +3 -0
  91. package/studio/web/assets/{setup-BisINqdH.js.map → setup-I15FAF9H.js.map} +1 -1
  92. package/studio/web/assets/status-BF1eJshJ.js +62 -0
  93. package/studio/web/assets/status-BF1eJshJ.js.map +1 -0
  94. package/studio/web/assets/{swagger-ui-react-CAi_s1PC.js → swagger-ui-react-DwSPXXhl.js} +2 -2
  95. package/studio/web/assets/{swagger-ui-react-CAi_s1PC.js.map → swagger-ui-react-DwSPXXhl.js.map} +1 -1
  96. package/studio/web/assets/{textarea-DhLMZ3PA.js → table-DpOjNQHt.js} +2 -10
  97. package/studio/web/assets/table-DpOjNQHt.js.map +1 -0
  98. package/studio/web/assets/{tsMode-DT74tlkM.js → tsMode-Bu51A-VG.js} +2 -2
  99. package/studio/web/assets/{tsMode-DT74tlkM.js.map → tsMode-Bu51A-VG.js.map} +1 -1
  100. package/studio/web/assets/{useEntityRestURL-CGRGc1n7.js → useEntityRestURL-DrV1zMrN.js} +2 -2
  101. package/studio/web/assets/{useEntityRestURL-CGRGc1n7.js.map → useEntityRestURL-DrV1zMrN.js.map} +1 -1
  102. package/studio/web/index.html +6 -7
  103. package/utility/environment/environmentManager.ts +152 -0
  104. package/utility/lmdb/environmentUtility.ts +2 -1
  105. package/studio/web/assets/applications-9SEVLIO5.js.map +0 -1
  106. package/studio/web/assets/index-C8Mv9kHV.css +0 -1
  107. package/studio/web/assets/index-Dy3uDGXb.js +0 -809
  108. package/studio/web/assets/index-Dy3uDGXb.js.map +0 -1
  109. package/studio/web/assets/index.lazy-CN1zq4I4.js +0 -14
  110. package/studio/web/assets/notifications-CKlYVvVN.js +0 -2
  111. package/studio/web/assets/pollUnlessForbidden-HHdQZW1N.js.map +0 -1
  112. package/studio/web/assets/queryClient-CbA8wM7J.js +0 -2
  113. package/studio/web/assets/queryClient-CbA8wM7J.js.map +0 -1
  114. package/studio/web/assets/setup-BisINqdH.js +0 -3
  115. package/studio/web/assets/status-BuQoCc7l.js +0 -62
  116. package/studio/web/assets/status-BuQoCc7l.js.map +0 -1
  117. package/studio/web/assets/textarea-DhLMZ3PA.js.map +0 -1
@@ -1,4 +1,4 @@
1
- import{a as e,t}from"./rolldown-runtime-CNC7AqOf.js";import{C as n,S as r,_ as i,a,b as o,c as s,d as c,h as l,i as u,l as d,m as f,p,r as m,s as h,t as g,u as _,v,w as ee,x as y,y as b}from"./vendor-core-xUefYpUO.js";import{i as x,t as S}from"./button-oQgW4t1x.js";import{C as te,I as ne,N as re,j as ie}from"./vendor-tanstack-0SjDjtT0.js";import{a as ae}from"./vendor-datadog-DyjkTkvg.js";import{r as oe}from"./vendor-react-DeL8Gtgl.js";import{Rt as C}from"./vendor-ui-Bj22lHGK.js";import{t as w}from"./createLucideIcon-BDx8noBh.js";import{l as se,t as ce}from"./react-CjDfh48f.js";import{i as le,n as ue,r as de,t as fe}from"./x-C3uc0qMD.js";import{c as pe,f as me,g as he,h as ge,i as _e,l as ve,m as ye,p as be,r as xe,t as Se,u as Ce}from"./setComponentFile-SEtBt_GV.js";import{n as we}from"./queryClient-CbA8wM7J.js";import{n as Te}from"./setLocalStorage-CD_L8p_D.js";import{t as Ee}from"./useLocalStorage-hkNSGGg8.js";import{o as De}from"./pollUnlessForbidden-HHdQZW1N.js";import{$n as Oe,At as ke,Bn as Ae,Gn as je,Gt as Me,Hn as Ne,Jn as Pe,L as Fe,Nt as Ie,Ot as Le,Qn as Re,R as ze,Un as Be,_t as Ve,ar as He,c as Ue,dn as We,ir as Ge,jt as Ke,kt as qe,lr as Je,nr as Ye,o as Xe,ot as Ze,q as Qe,s as $e,u as et,ut as tt}from"./index-Dy3uDGXb.js";import{t as nt}from"./useEntityRestURL-CGRGc1n7.js";import{n as rt}from"./getAnalytics-ChWFgfXd.js";var it=w(`between-horizontal-start`,[[`rect`,{width:`13`,height:`7`,x:`8`,y:`3`,rx:`1`,key:`pkso9a`}],[`path`,{d:`m2 9 3 3-3 3`,key:`1agib5`}],[`rect`,{width:`13`,height:`7`,x:`8`,y:`14`,rx:`1`,key:`1q5fc1`}]]),at=w(`book`,[[`path`,{d:`M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20`,key:`k3hazp`}]]),ot=w(`chart-area`,[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z`,key:`q0gr47`}]]),st=w(`circle-x`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]]),ct=w(`file-pen`,[[`path`,{d:`M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34`,key:`o6klzx`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z`,key:`zhnas1`}]]),lt=w(`logs`,[[`path`,{d:`M3 5h1`,key:`1mv5vm`}],[`path`,{d:`M3 12h1`,key:`lp3yf2`}],[`path`,{d:`M3 19h1`,key:`w6f3n9`}],[`path`,{d:`M8 5h1`,key:`1nxr5w`}],[`path`,{d:`M8 12h1`,key:`1con00`}],[`path`,{d:`M8 19h1`,key:`k7p10e`}],[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}]]),ut=w(`message-square-heart`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7.5 9.5c0 .687.265 1.383.697 1.844l3.009 3.264a1.14 1.14 0 0 0 .407.314 1 1 0 0 0 .783-.004 1.14 1.14 0 0 0 .398-.31l3.008-3.264A2.77 2.77 0 0 0 16.5 9.5 2.5 2.5 0 0 0 12 8a2.5 2.5 0 0 0-4.5 1.5`,key:`1faxuh`}]]),dt=w(`send`,[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]),ft=w(`wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]);async function pt(){await x.delete(`/Chat/Messages/`)}var T=e(ae(),1),E=oe();function mt({setMessages:e}){let[t,n]=(0,T.useState)(!1);return(0,E.jsxs)(`button`,{type:`button`,className:`clear-chat-button gap-1`,onClick:(0,T.useCallback)(async()=>{if(!t){n(!0);try{await pt(),e([])}catch(e){console.error(`Failed to clear chat:`,e)}finally{n(!1)}}},[t,e]),disabled:t,title:`Clear chat`,children:[t?(0,E.jsx)(Re,{className:`animate-spin`,size:18}):(0,E.jsx)(Be,{size:18}),`Clear`]})}async function ht(){let{data:e}=await x.get(`/Chat/Messages/`);return e}var gt=`vercel.ai.error`,_t=Symbol.for(gt),vt,yt,D=class e extends (yt=Error,vt=_t,yt){constructor({name:e,message:t,cause:n}){super(t),this[vt]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,gt)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};function bt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.toString():JSON.stringify(e)}var xt=`AI_InvalidArgumentError`,St=`vercel.ai.error.${xt}`,Ct=Symbol.for(St),wt,Tt,Et=class extends (Tt=D,wt=Ct,Tt){constructor({message:e,cause:t,argument:n}){super({name:xt,message:e,cause:t}),this[wt]=!0,this.argument=n}static isInstance(e){return D.hasMarker(e,St)}},Dt=`AI_JSONParseError`,Ot=`vercel.ai.error.${Dt}`,kt=Symbol.for(Ot),At,jt,Mt=class extends (jt=D,At=kt,jt){constructor({text:e,cause:t}){super({name:Dt,message:`JSON parsing failed: Text: ${e}.
1
+ import{a as e,t}from"./rolldown-runtime-CNC7AqOf.js";import{C as n,S as r,_ as i,a,b as o,c as s,d as c,h as l,i as u,l as d,m as f,p,r as m,s as h,t as g,u as _,v,w as ee,x as y,y as b}from"./vendor-core-xUefYpUO.js";import{i as x,t as S}from"./button-oQgW4t1x.js";import{C as te,I as ne,N as re,j as ie}from"./vendor-tanstack-0SjDjtT0.js";import{a as ae}from"./vendor-datadog-DyjkTkvg.js";import{r as oe}from"./vendor-react-DeL8Gtgl.js";import{Rt as C}from"./vendor-ui-Bj22lHGK.js";import{t as w}from"./createLucideIcon-BDx8noBh.js";import{l as se,t as ce}from"./react-CjDfh48f.js";import{i as le,n as ue,r as de,t as fe}from"./x-C3uc0qMD.js";import{t as pe}from"./chevron-right-anDJCGlp.js";import{c as me,f as he,g as ge,h as _e,i as ve,l as ye,m as be,p as xe,r as Se,t as Ce,u as we}from"./setComponentFile-D0aPcI3W.js";import{n as Te}from"./queryClient-CgtkoiCY.js";import{n as Ee}from"./setLocalStorage-CD_L8p_D.js";import{t as De}from"./useLocalStorage-hkNSGGg8.js";import{o as Oe}from"./pollUnlessForbidden-BhzefVRn.js";import{At as ke,Gn as Ae,H as je,Hn as Me,Kt as Ne,Mt as Pe,Pt as Fe,V as Ie,Wn as Le,Xn as Re,Y as ze,_t as Be,c as Ve,ct as He,d as Ue,er as We,f as Ge,fn as Ke,ir as qe,jt as Je,kt as Ye,m as Xe,or as Ze,qn as Qe,sr as $e,tr as et,ut as tt}from"./index-Sevt3MVx.js";import{t as nt}from"./useEntityRestURL-DrV1zMrN.js";import{n as rt}from"./getAnalytics-ChWFgfXd.js";var it=w(`between-horizontal-start`,[[`rect`,{width:`13`,height:`7`,x:`8`,y:`3`,rx:`1`,key:`pkso9a`}],[`path`,{d:`m2 9 3 3-3 3`,key:`1agib5`}],[`rect`,{width:`13`,height:`7`,x:`8`,y:`14`,rx:`1`,key:`1q5fc1`}]]),at=w(`book`,[[`path`,{d:`M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20`,key:`k3hazp`}]]),ot=w(`chart-area`,[[`path`,{d:`M3 3v16a2 2 0 0 0 2 2h16`,key:`c24i48`}],[`path`,{d:`M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z`,key:`q0gr47`}]]),st=w(`circle-x`,[[`circle`,{cx:`12`,cy:`12`,r:`10`,key:`1mglay`}],[`path`,{d:`m15 9-6 6`,key:`1uzhvr`}],[`path`,{d:`m9 9 6 6`,key:`z0biqf`}]]),ct=w(`file-pen`,[[`path`,{d:`M12.659 22H18a2 2 0 0 0 2-2V8a2.4 2.4 0 0 0-.706-1.706l-3.588-3.588A2.4 2.4 0 0 0 14 2H6a2 2 0 0 0-2 2v9.34`,key:`o6klzx`}],[`path`,{d:`M14 2v5a1 1 0 0 0 1 1h5`,key:`wfsgrz`}],[`path`,{d:`M10.378 12.622a1 1 0 0 1 3 3.003L8.36 20.637a2 2 0 0 1-.854.506l-2.867.837a.5.5 0 0 1-.62-.62l.836-2.869a2 2 0 0 1 .506-.853z`,key:`zhnas1`}]]),lt=w(`logs`,[[`path`,{d:`M3 5h1`,key:`1mv5vm`}],[`path`,{d:`M3 12h1`,key:`lp3yf2`}],[`path`,{d:`M3 19h1`,key:`w6f3n9`}],[`path`,{d:`M8 5h1`,key:`1nxr5w`}],[`path`,{d:`M8 12h1`,key:`1con00`}],[`path`,{d:`M8 19h1`,key:`k7p10e`}],[`path`,{d:`M13 5h8`,key:`a7qcls`}],[`path`,{d:`M13 12h8`,key:`h98zly`}],[`path`,{d:`M13 19h8`,key:`c3s6r1`}]]),ut=w(`message-square-heart`,[[`path`,{d:`M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z`,key:`18887p`}],[`path`,{d:`M7.5 9.5c0 .687.265 1.383.697 1.844l3.009 3.264a1.14 1.14 0 0 0 .407.314 1 1 0 0 0 .783-.004 1.14 1.14 0 0 0 .398-.31l3.008-3.264A2.77 2.77 0 0 0 16.5 9.5 2.5 2.5 0 0 0 12 8a2.5 2.5 0 0 0-4.5 1.5`,key:`1faxuh`}]]),dt=w(`send`,[[`path`,{d:`M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z`,key:`1ffxy3`}],[`path`,{d:`m21.854 2.147-10.94 10.939`,key:`12cjpa`}]]),ft=w(`wrench`,[[`path`,{d:`M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.106-3.105c.32-.322.863-.22.983.218a6 6 0 0 1-8.259 7.057l-7.91 7.91a1 1 0 0 1-2.999-3l7.91-7.91a6 6 0 0 1 7.057-8.259c.438.12.54.662.219.984z`,key:`1ngwbx`}]]);async function pt(){await x.delete(`/Chat/Messages/`)}var T=e(ae(),1),E=oe();function mt({setMessages:e}){let[t,n]=(0,T.useState)(!1);return(0,E.jsxs)(`button`,{type:`button`,className:`clear-chat-button gap-1`,onClick:(0,T.useCallback)(async()=>{if(!t){n(!0);try{await pt(),e([])}catch(e){console.error(`Failed to clear chat:`,e)}finally{n(!1)}}},[t,e]),disabled:t,title:`Clear chat`,children:[t?(0,E.jsx)(We,{className:`animate-spin`,size:18}):(0,E.jsx)(Ae,{size:18}),`Clear`]})}async function ht(){let{data:e}=await x.get(`/Chat/Messages/`);return e}var gt=`vercel.ai.error`,_t=Symbol.for(gt),vt,yt,D=class e extends (yt=Error,vt=_t,yt){constructor({name:e,message:t,cause:n}){super(t),this[vt]=!0,this.name=e,this.cause=n}static isInstance(t){return e.hasMarker(t,gt)}static hasMarker(e,t){let n=Symbol.for(t);return typeof e==`object`&&!!e&&n in e&&typeof e[n]==`boolean`&&e[n]===!0}};function bt(e){return e==null?`unknown error`:typeof e==`string`?e:e instanceof Error?e.toString():JSON.stringify(e)}var xt=`AI_InvalidArgumentError`,St=`vercel.ai.error.${xt}`,Ct=Symbol.for(St),wt,Tt,Et=class extends (Tt=D,wt=Ct,Tt){constructor({message:e,cause:t,argument:n}){super({name:xt,message:e,cause:t}),this[wt]=!0,this.argument=n}static isInstance(e){return D.hasMarker(e,St)}},Dt=`AI_JSONParseError`,Ot=`vercel.ai.error.${Dt}`,kt=Symbol.for(Ot),At,jt,Mt=class extends (jt=D,At=kt,jt){constructor({text:e,cause:t}){super({name:Dt,message:`JSON parsing failed: Text: ${e}.
2
2
  Error message: ${bt(t)}`,cause:t}),this[At]=!0,this.text=e}static isInstance(e){return D.hasMarker(e,Ot)}},Nt=`AI_TypeValidationError`,Pt=`vercel.ai.error.${Nt}`,Ft=Symbol.for(Pt),It,Lt,O=class e extends (Lt=D,It=Ft,Lt){constructor({value:e,cause:t,context:n}){let r=`Type validation failed`;if(n?.field&&(r+=` for ${n.field}`),n?.entityName||n?.entityId){r+=` (`;let e=[];n.entityName&&e.push(n.entityName),n.entityId&&e.push(`id: "${n.entityId}"`),r+=e.join(`, `),r+=`)`}super({name:Nt,message:`${r}: Value: ${JSON.stringify(e)}.
3
3
  Error message: ${bt(t)}`,cause:t}),this[It]=!0,this.value=e,this.context=n}static isInstance(e){return D.hasMarker(e,Pt)}static wrap({value:t,cause:n,context:r}){return e.isInstance(n)&&n.value===t&&n.context?.field===r?.field&&n.context?.entityName===r?.entityName&&n.context?.entityId===r?.entityId?n:new e({value:t,cause:n,context:r})}},Rt=class extends Error{constructor(e,t){super(e),this.name=`ParseError`,this.type=t.type,this.field=t.field,this.value=t.value,this.line=t.line}},zt=10,Bt=13,k=32;function Vt(e){}function Ht(e){if(typeof e==`function`)throw TypeError("`config` must be an object, got a function instead. Did you mean `createParser({onEvent: fn})`?");let{onEvent:t=Vt,onError:n=Vt,onRetry:r=Vt,onComment:i,maxBufferSize:a}=e,o=[],s=0,c=!0,l,u=``,d=0,f,p=!1;function m(e){if(p)throw Error("Cannot feed parser: it was terminated after exceeding the configured max buffer size. Call `reset()` to resume parsing.");if(c&&(c=!1,e.charCodeAt(0)===239&&e.charCodeAt(1)===187&&e.charCodeAt(2)===191&&(e=e.slice(3))),o.length===0){let t=g(e);t!==``&&(o.push(t),s=t.length),h();return}if(e.indexOf(`
4
4
  `)===-1&&e.indexOf(`\r`)===-1){o.push(e),s+=e.length,h();return}o.push(e);let t=o.join(``);o.length=0,s=0;let n=g(t);n!==``&&(o.push(n),s=n.length),h()}function h(){a!==void 0&&(s+u.length<=a||(p=!0,o.length=0,s=0,l=void 0,u=``,d=0,f=void 0,n(new Rt(`Buffered data exceeded max buffer size of ${a} characters`,{type:`max-buffer-size-exceeded`}))))}function g(e){let n=0;if(e.indexOf(`\r`)===-1){let r=e.indexOf(`
@@ -13,7 +13,7 @@ ${t}`,d++;break;case`id`:l=t.includes(`\0`)?void 0:t;break;case`retry`:/^\d+$/.t
13
13
  ]))`;continue}else if(r[e]===`$`){i+=`($|(?=[\r
14
14
  ]))`;continue}}if(n.s&&r[e]===`.`){i+=o?`${r[e]}\r
15
15
  `:`[${r[e]}\r
16
- ]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Tn(e,t){let n={type:`object`,additionalProperties:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===g.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=bn(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===g.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===g.ZodBranded&&e.keyType._def.type._def.typeName===g.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=ln(e.keyType._def,t);return{...n,propertyNames:i}}return n}function En(e,t){return t.mapStrategy===`record`?Tn(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[L(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||N(),L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||N()],minItems:2,maxItems:2}}}function Dn(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function On(){return{not:N()}}function kn(){return{type:`null`}}var An={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function jn(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in An&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=An[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Mn(e,t)}var Mn=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Nn(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[An[e.innerType._def.typeName],`null`]};let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Pn(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function Fn(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=Ln(a),s=L(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=In(e,t);return a!==void 0&&(n.additionalProperties=a),n}function In(e,t){if(e.catchall._def.typeName!==`ZodNever`)return L(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Ln(e){try{return e.isOptional()}catch{return!0}}var Rn=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return L(e.innerType._def,t);let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:N()},n]}:N()},zn=(e,t)=>{if(t.pipeStrategy===`input`)return L(e.in._def,t);if(t.pipeStrategy===`output`)return L(e.out._def,t);let n=L(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,L(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Bn(e,t){return L(e.type._def,t)}function Vn(e,t){let n={type:`array`,uniqueItems:!0,items:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function Hn(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:L(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Un(){return{not:N()}}function Wn(){return N()}var Gn=(e,t)=>L(e.innerType._def,t),Kn=(e,t,n)=>{switch(t){case g.ZodString:return bn(e,n);case g.ZodNumber:return Pn(e);case g.ZodObject:return Fn(e,n);case g.ZodBigInt:return sn(e);case g.ZodBoolean:return cn();case g.ZodDate:return dn(e,n);case g.ZodUndefined:return Un();case g.ZodNull:return kn();case g.ZodArray:return on(e,n);case g.ZodUnion:case g.ZodDiscriminatedUnion:return jn(e,n);case g.ZodIntersection:return _n(e,n);case g.ZodTuple:return Hn(e,n);case g.ZodRecord:return Tn(e,n);case g.ZodLiteral:return vn(e);case g.ZodEnum:return hn(e);case g.ZodNativeEnum:return Dn(e);case g.ZodNullable:return Nn(e,n);case g.ZodOptional:return Rn(e,n);case g.ZodMap:return En(e,n);case g.ZodSet:return Vn(e,n);case g.ZodLazy:return()=>e.getter()._def;case g.ZodPromise:return Bn(e,n);case g.ZodNaN:case g.ZodNever:return On();case g.ZodEffects:return mn(e,n);case g.ZodAny:return N();case g.ZodUnknown:return Wn();case g.ZodDefault:return pn(e,n);case g.ZodBranded:return ln(e,n);case g.ZodReadonly:return Gn(e,n);case g.ZodCatch:return un(e,n);case g.ZodPipeline:return zn(e,n);case g.ZodFunction:case g.ZodVoid:case g.ZodSymbol:return;default:return(e=>void 0)(t)}},qn=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function L(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==nn)return i}if(r&&!n){let e=Jn(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Kn(e,e.typeName,t),o=typeof a==`function`?L(a(),t):a;if(o&&Yn(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Jn=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:qn(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),N()):t.$refStrategy===`seen`?N():void 0}},Yn=(e,t,n)=>(e.description&&(n.description=e.description),n),Xn=e=>{let t=an(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Zn=(e,t)=>{let n=Xn(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:L(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??N()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=L(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??N(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},Qn=Symbol.for(`vercel.ai.schema`);function $n(e){let t;return()=>(t??=e(),t)}function er(e,{validate:t}={}){return{[Qn]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function tr(e){return typeof e==`object`&&!!e&&Qn in e&&e[Qn]===!0&&`jsonSchema`in e&&`validate`in e}function nr(e){return e==null?er({type:`object`,properties:{},additionalProperties:!1}):tr(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?cr(e):rr(e):e()}function rr(e){return er(()=>{if(!ir(e))throw Error(`Standard schema vendor '${e[`~standard`].vendor}' does not support JSON Schema conversion.`);return tn(e[`~standard`].jsonSchema.input({target:`draft-07`}))},{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new O({value:t,cause:n.issues})}}})}function ir(e){return e[`~standard`].jsonSchema!=null}function ar(e,t){let n=t?.useReferences??!1;return er(()=>Zn(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function or(e,t){let r=t?.useReferences??!1;return er(()=>tn(ee(e,{target:`draft-7`,io:`input`,reused:r?`ref`:`inline`})),{validate:async t=>{let r=await n(e,t);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}}})}function sr(e){return`_zod`in e}function cr(e,t){return sr(e)?or(e,t):ar(e,t)}async function lr({value:e,schema:t,context:n}){let r=await R({value:e,schema:t,context:n});if(!r.success)throw O.wrap({value:e,cause:r.error,context:n});return r.value}async function R({value:e,schema:t,context:n}){let r=nr(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:O.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:O.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function z({text:e,schema:t}){try{let n=en(e);return t==null?{success:!0,value:n,rawValue:n}:await R({value:n,schema:t})}catch(t){return{success:!1,error:Mt.isInstance(t)?t:new Mt({text:e,cause:t}),rawValue:void 0}}}function ur({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Gt).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await z({text:e,schema:t}))}}))}async function B(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}new TextDecoder;var dr=Object.defineProperty,fr=(e,t)=>{for(var n in t)dr(e,n,{get:t[n],enumerable:!0})},pr=`AI_NoObjectGeneratedError`,mr=`vercel.ai.error.${pr}`,hr=Symbol.for(mr),gr,V=class extends D{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:pr,message:e,cause:t}),this[gr]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return D.hasMarker(e,mr)}};gr=hr;var _r=`AI_UIMessageStreamError`,vr=`vercel.ai.error.${_r}`,yr=Symbol.for(vr),br,H=class extends D{constructor({chunkType:e,chunkId:t,message:n}){super({name:_r,message:n}),this[br]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return D.hasMarker(e,vr)}};br=yr;function xr(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let r in t)if(!(r===`__proto__`||r===`constructor`||r===`prototype`)&&Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(i===void 0)continue;let a=r in e?e[r]:void 0,o=typeof i==`object`&&!!i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),s=typeof a==`object`&&!!a&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);o&&s?n[r]=xr(a,i):n[r]=i}return n}var U=p(()=>y([a(),o(),i(),d(),b(o(),U.optional()),s(U)])),W=b(o(),b(o(),U.optional())),Sr=y([o(),u(Uint8Array),u(ArrayBuffer),_(Yt,{message:`Must be a Buffer`})]),Cr=b(o(),o()),wr=v({type:f(`text`),text:o(),providerOptions:W.optional()}),Tr=v({type:f(`image`),image:y([Sr,u(URL),Cr]),mediaType:o().optional(),providerOptions:W.optional()}),Er=c(`type`,[v({type:f(`data`),data:Sr}),v({type:f(`url`),url:u(URL)}),v({type:f(`reference`),reference:Cr}),v({type:f(`text`),text:o()})]),Dr=c(`type`,[v({type:f(`data`),data:Sr}),v({type:f(`url`),url:u(URL)})]),Or=v({type:f(`file`),data:y([Er,Sr,u(URL),Cr]),filename:o().optional(),mediaType:o(),providerOptions:W.optional()}),kr=v({type:f(`reasoning`),text:o(),providerOptions:W.optional()}),Ar=v({type:f(`custom`),kind:o().transform(e=>e),providerOptions:W.optional()}),jr=v({type:f(`reasoning-file`),data:y([Dr,Sr,u(URL)]),mediaType:o(),providerOptions:W.optional()}),Mr=v({type:f(`tool-call`),toolCallId:o(),toolName:o(),input:r(),providerOptions:W.optional(),providerExecuted:d().optional()}),Nr=c(`type`,[v({type:f(`text`),value:o(),providerOptions:W.optional()}),v({type:f(`json`),value:U,providerOptions:W.optional()}),v({type:f(`execution-denied`),reason:o().optional(),providerOptions:W.optional()}),v({type:f(`error-text`),value:o(),providerOptions:W.optional()}),v({type:f(`error-json`),value:U,providerOptions:W.optional()}),v({type:f(`content`),value:s(y([v({type:f(`text`),text:o(),providerOptions:W.optional()}),v({type:f(`file`),data:Er,mediaType:o(),filename:o().optional(),providerOptions:W.optional()}),v({type:f(`file-data`),data:o(),mediaType:o(),filename:o().optional(),providerOptions:W.optional()}),v({type:f(`file-url`),url:o(),mediaType:o().optional(),providerOptions:W.optional()}),v({type:f(`file-id`),fileId:y([o(),b(o(),o())]),providerOptions:W.optional()}),v({type:f(`file-reference`),providerReference:b(o(),o()),providerOptions:W.optional()}),v({type:f(`image-data`),data:o(),mediaType:o(),providerOptions:W.optional()}),v({type:f(`image-url`),url:o(),providerOptions:W.optional()}),v({type:f(`image-file-id`),fileId:y([o(),b(o(),o())]),providerOptions:W.optional()}),v({type:f(`image-file-reference`),providerReference:b(o(),o()),providerOptions:W.optional()}),v({type:f(`custom`),providerOptions:W.optional()})]))})]),Pr=v({type:f(`tool-result`),toolCallId:o(),toolName:o(),output:Nr,providerOptions:W.optional()}),Fr=v({type:f(`tool-approval-request`),approvalId:o(),toolCallId:o()}),Ir=v({type:f(`tool-approval-response`),approvalId:o(),approved:d(),reason:o().optional()});y([v({role:f(`system`),content:o(),providerOptions:W.optional()}),v({role:f(`user`),content:y([o(),s(y([wr,Tr,Or]))]),providerOptions:W.optional()}),v({role:f(`assistant`),content:y([o(),s(y([wr,Ar,Or,kr,jr,Mr,Pr,Fr]))]),providerOptions:W.optional()}),v({role:f(`tool`),content:s(y([Pr,Ir])),providerOptions:W.optional()})]),fr({},{array:()=>Vr,choice:()=>Hr,json:()=>Ur,object:()=>Br,text:()=>zr});function Lr(e){let t=[`ROOT`],n=-1,r=null,i=0;function a(e){return e>=`0`&&e<=`9`||e>=`A`&&e<=`F`||e>=`a`&&e<=`f`}function o(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`);break}}function s(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let l=0;l<e.length;l++){let u=e[l];switch(t[t.length-1]){case`ROOT`:o(u,l,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=l,t.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break}break;case`INSIDE_OBJECT_KEY`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(u){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:o(u,l,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:s(u,l);break;case`INSIDE_STRING`:switch(u){case`"`:t.pop(),n=l;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=l}break;case`INSIDE_ARRAY_START`:switch(u){case`]`:n=l,t.pop();break;default:n=l,o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(u){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=l,t.pop();break;default:n=l;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),u===`u`?(i=0,t.push(`INSIDE_STRING_UNICODE_ESCAPE`)):n=l;break;case`INSIDE_STRING_UNICODE_ESCAPE`:a(u)&&(i++,i===4&&(t.pop(),n=l));break;case`INSIDE_NUMBER`:switch(u){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=l;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,l+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?s(u,l):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l)):n=l;break}}}let l=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:l+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:l+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:l+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?l+=`true`.slice(t.length):`false`.startsWith(t)?l+=`false`.slice(t.length):`null`.startsWith(t)&&(l+=`null`.slice(t.length))}}return l}async function Rr(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await z({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await z({text:Lr(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var zr=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),Br=({schema:e,name:t,description:n})=>{let r=nr(e);return{name:`object`,responseFormat:B(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await z({text:e});if(!n.success)throw new V({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await R({value:n.value,schema:r});if(!i.success)throw new V({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await Rr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},Vr=({element:e,name:t,description:n})=>{let r=nr(e);return{name:`array`,responseFormat:B(r.jsonSchema).then(e=>{let{$schema:r,...i}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{elements:{type:`array`,items:i}},required:[`elements`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:e},t){let n=await z({text:e});if(!n.success)throw new V({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=n.value;if(typeof i!=`object`||!i||!(`elements`in i)||!Array.isArray(i.elements))throw new V({message:`No object generated: response did not match schema.`,cause:new O({value:i,cause:`response must be an object with an elements array`}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let a=[];for(let n of i.elements){let i=await R({value:n,schema:r});if(!i.success)throw new V({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});a.push(i.value)}return a},async parsePartialOutput({text:e}){let t=await Rr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,i=[];for(let e of n){let t=await R({value:e,schema:r});t.success&&i.push(t.value)}return{partial:i}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},n){if(t!=null)for(;e<t.length;e++)n.enqueue(t[e])}})}}},Hr=({options:e,name:t,description:n})=>({name:`choice`,responseFormat:Promise.resolve({type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await z({text:t});if(!r.success)throw new V({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new V({message:`No object generated: response did not match schema.`,cause:new O({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await Rr(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),Ur=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await z({text:e});if(!n.success)throw new V({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await Rr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});new TextEncoder,new TextEncoder,A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),TransformStream;var Wr=b(o(),U.optional()),Gr=$n(()=>cr(y([l({type:f(`text-start`),id:o(),providerMetadata:W.optional()}),l({type:f(`text-delta`),id:o(),delta:o(),providerMetadata:W.optional()}),l({type:f(`text-end`),id:o(),providerMetadata:W.optional()}),l({type:f(`error`),errorText:o()}),l({type:f(`tool-input-start`),toolCallId:o(),toolName:o(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional(),title:o().optional()}),l({type:f(`tool-input-delta`),toolCallId:o(),inputTextDelta:o()}),l({type:f(`tool-input-available`),toolCallId:o(),toolName:o(),input:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional(),title:o().optional()}),l({type:f(`tool-input-error`),toolCallId:o(),toolName:o(),input:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional(),errorText:o(),title:o().optional()}),l({type:f(`tool-approval-request`),approvalId:o(),toolCallId:o(),isAutomatic:d().optional(),signature:o().optional()}),l({type:f(`tool-approval-response`),approvalId:o(),approved:d(),reason:o().optional(),providerExecuted:d().optional(),providerMetadata:W.optional()}),l({type:f(`tool-output-available`),toolCallId:o(),output:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional(),preliminary:d().optional()}),l({type:f(`tool-output-error`),toolCallId:o(),errorText:o(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional()}),l({type:f(`tool-output-denied`),toolCallId:o()}),l({type:f(`reasoning-start`),id:o(),providerMetadata:W.optional()}),l({type:f(`reasoning-delta`),id:o(),delta:o(),providerMetadata:W.optional()}),l({type:f(`reasoning-end`),id:o(),providerMetadata:W.optional()}),l({type:f(`custom`),kind:o().transform(e=>e),providerMetadata:W.optional()}),l({type:f(`source-url`),sourceId:o(),url:o(),title:o().optional(),providerMetadata:W.optional()}),l({type:f(`source-document`),sourceId:o(),mediaType:o(),title:o(),filename:o().optional(),providerMetadata:W.optional()}),l({type:f(`file`),url:o(),mediaType:o(),providerMetadata:W.optional()}),l({type:f(`reasoning-file`),url:o(),mediaType:o(),providerMetadata:W.optional()}),l({type:_(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:o().optional(),data:r(),transient:d().optional()}),l({type:f(`start-step`)}),l({type:f(`finish-step`)}),l({type:f(`start`),messageId:o().optional(),messageMetadata:r().optional()}),l({type:f(`finish`),finishReason:m([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:r().optional()}),l({type:f(`abort`),reason:o().optional()}),l({type:f(`message-metadata`),messageMetadata:r()})])));function Kr(e){return e.type.startsWith(`data-`)}function qr(){return Object.create(null)}function Jr(e){return e.type===`text`}function Yr(e){return e.type.startsWith(`tool-`)}function Xr(e){return e.type===`dynamic-tool`}function G(e){return Yr(e)||Xr(e)}function Zr(e){return e.type.split(`-`).slice(1).join(`-`)}function Qr(e){return Xr(e)?e.toolName:Zr(e)}function $r({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:qr(),activeReasoningParts:qr(),partialToolCalls:qr()}}function ei({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:a,onData:o}){return e.pipeThrough(new TransformStream({async transform(e,s){await r(async({state:r,write:c})=>{function l(){let e=r.message.parts,t=e.length-1;for(;t>=0&&e[t].type!==`step-start`;)t--;return e.slice(t+1)}function u(){return l().filter(G)}function d(e){let t=u().find(t=>t.toolCallId===e);if(t==null){let n=r.message.parts;for(let r=n.length-1;r>=0;r--){let i=n[r];if(G(i)&&i.toolCallId===e){t=i;break}}}if(t==null)throw new H({chunkType:`tool-invocation`,chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function f(e){let t=r.message.parts.filter(G).find(t=>t.approval?.id===e);if(t==null)throw new H({chunkType:`tool-approval-response`,chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}function p(e,t){let n=t??l().find(t=>Yr(t)&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null)if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}else r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},input:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&!(e.state===`output-available`||e.state===`output-error`)?{callProviderMetadata:i.providerMetadata}:{}})}function m(e,t){let n=t??l().find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.toolName=e.toolName,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput??a.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null)if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}else r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&!(e.state===`output-available`||e.state===`output-error`)?{callProviderMetadata:i.providerMetadata}:{}})}async function h(e){if(e!=null){let n=r.message.metadata==null?e:xr(r.message.metadata,e);t!=null&&await lr({value:n,schema:t,context:{field:`message.metadata`,entityId:r.message.id}}),r.message.metadata=n}}switch(e.type){case`text-start`:{let t={type:`text`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeTextParts[e.id]=t,r.message.parts.push(t),c();break}case`text-delta`:{let t=r.activeTextParts[e.id];if(t==null)throw new H({chunkType:`text-delta`,chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`text-end`:{let t=r.activeTextParts[e.id];if(t==null)throw new H({chunkType:`text-end`,chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state=`done`,t.providerMetadata=e.providerMetadata??t.providerMetadata,delete r.activeTextParts[e.id],c();break}case`custom`:{let t={type:`custom`,kind:e.kind,providerMetadata:e.providerMetadata};r.message.parts.push(t),c();break}case`reasoning-start`:{let t={type:`reasoning`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),c();break}case`reasoning-delta`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new H({chunkType:`reasoning-delta`,chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`reasoning-end`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new H({chunkType:`reasoning-end`,chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=e.providerMetadata??t.providerMetadata,t.state=`done`,delete r.activeReasoningParts[e.id],c();break}case`file`:case`reasoning-file`:r.message.parts.push({type:e.type,mediaType:e.mediaType,url:e.url,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}}),c();break;case`source-url`:r.message.parts.push({type:`source-url`,sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),c();break;case`source-document`:r.message.parts.push({type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),c();break;case`tool-input-start`:{let t=l().filter(Yr);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];if(t==null)throw new H({chunkType:`tool-input-delta`,chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:n}=await Rr(t.text);t.dynamic?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}):p({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`tool-input-available`:e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:{let t=l().filter(G).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}),c();break}case`tool-approval-request`:{let t=d(e.toolCallId);t.state=`approval-requested`,t.approval={id:e.approvalId,...e.isAutomatic===!0?{isAutomatic:!0}:{},...e.signature==null?{}:{signature:e.signature}},c();break}case`tool-approval-response`:{let t=f(e.approvalId),n=t.approval==null?{id:e.approvalId}:t.approval;t.state=`approval-responded`,t.approval={id:e.approvalId,approved:e.approved,...e.reason==null?{}:{reason:e.reason},...n.isAutomatic===!0?{isAutomatic:!0}:{},...n.signature==null?{}:{signature:n.signature}},e.providerExecuted!=null&&(t.providerExecuted=e.providerExecuted),e.providerMetadata!=null&&(t.callProviderMetadata=e.providerMetadata),c();break}case`tool-output-denied`:{let t=d(e.toolCallId);t.state=`output-denied`,c();break}case`tool-output-available`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-available`,input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:Zr(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`tool-output-error`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:Zr(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts=qr(),r.activeReasoningParts=qr();break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await h(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(Kr(e)){if(n?.[e.type]!=null){let t=r.message.parts.findIndex(t=>`id`in t&&`data`in t&&t.id===e.id&&t.type===e.type),i=t>=0?t:r.message.parts.length;await lr({value:e.data,schema:n[e.type],context:{field:`message.parts[${i}].data`,entityName:e.type,entityId:e.id}})}let t=e;if(t.transient){o?.(t);break}let i=t.id==null?void 0:r.message.parts.find(e=>t.type===e.type&&t.id===e.id);i==null?r.message.parts.push(t):i.data=t.data,o?.(t),c()}}s.enqueue(e)})}}))}async function ti({stream:e,onError:t}){let n=e.getReader();try{for(;;){let{done:e}=await n.read();if(e)break}}catch(e){t?.(e)}finally{n.releaseLock()}}A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),b(o(),U.optional()),b(o(),o()),A({prefix:`call`,size:24}),A({prefix:`call`,size:24}),A({prefix:`aiobj`,size:24});var ni=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(e){n(e)}}),this.processQueue()})}};A({prefix:`aiobj`,size:24}),A({prefix:`call`,size:24});async function ri(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw Error(`FileList is not supported in the current environment`);return Promise.all(Array.from(e).map(async e=>{let{name:t,type:n}=e;return{type:`file`,mediaType:n,filename:t,url:await new Promise((t,n)=>{let r=new FileReader;r.onload=e=>{t(e.target?.result)},r.onerror=e=>n(e),r.readAsDataURL(e)})}}))}var ii=class{constructor({api:e=`/api/chat`,credentials:t,headers:n,body:r,fetch:i,prepareSendMessagesRequest:a,prepareReconnectToStreamRequest:o}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=i,this.prepareSendMessagesRequest=a,this.prepareReconnectToStreamRequest=o}async sendMessages({abortSignal:e,...t}){let n=await B(this.body),r=await B(this.headers),i=await B(this.credentials),a={...j(r),...j(t.headers)},o=await this.prepareSendMessagesRequest?.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...n,...t.body},headers:a,credentials:i,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId}),s=o?.api??this.api,c=o?.headers===void 0?a:j(o.headers),l=o?.body===void 0?{...n,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId}:o.body,u=o?.credentials??i,d=await(this.fetch??globalThis.fetch)(s,{method:`POST`,headers:{"Content-Type":`application/json`,...c},body:JSON.stringify(l),credentials:u,signal:e});if(!d.ok)throw Error(await d.text()??`Failed to fetch the chat response.`);if(!d.body)throw Error(`The response body is empty.`);return this.processResponseStream(d.body)}async reconnectToStream(e){let t=await B(this.body),n=await B(this.headers),r=await B(this.credentials),i={...j(n),...j(e.headers)},a=await this.prepareReconnectToStreamRequest?.call(this,{api:this.api,id:e.chatId,body:{...t,...e.body},headers:i,credentials:r,requestMetadata:e.metadata}),o=a?.api??`${this.api}/${e.chatId}/stream`,s=a?.headers===void 0?i:j(a.headers),c=a?.credentials??r,l=await(this.fetch??globalThis.fetch)(o,{method:`GET`,headers:s,credentials:c});if(l.status===204)return null;if(!l.ok)throw Error(await l.text()??`Failed to fetch the chat response.`);if(!l.body)throw Error(`The response body is empty.`);return this.processResponseStream(l.body)}},ai=class extends ii{constructor(e={}){super(e)}processResponseStream(e){return ur({stream:e,schema:Gr}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},oi=class{constructor({generateId:e=Jt,id:t=e(),transport:n=new ai,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.activeResponse=void 0,this.jobExecutor=new ni,this.sendMessage=async(e,t)=>{if(e==null){await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...t});return}let n;if(n=`text`in e||`files`in e?{parts:[...Array.isArray(e.files)?e.files:await ri(e.files),...`text`in e&&e.text!=null?[{type:`text`,text:e.text}]:[]]}:e,e.messageId!=null){let t=this.state.messages.findIndex(t=>t.id===e.messageId);if(t===-1)throw Error(`message with id ${e.messageId} not found`);if(this.state.messages[t].role!==`user`)throw Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{...n,id:e.messageId,role:n.role??`user`,metadata:e.metadata})}else this.state.pushMessage({...n,id:n.id??this.generateId(),role:n.role??`user`,metadata:e.metadata});await this.makeRequest({trigger:`submit-message`,messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{let n=e==null?this.state.messages.length-1:this.state.messages.findIndex(t=>t.id===e);if(n===-1)throw Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,this.messages[n].role===`assistant`?n:n+1),await this.makeRequest({trigger:`regenerate-message`,messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:`resume-stream`,...e})},this.clearError=()=>{this.status===`error`&&(this.state.error=void 0,this.setStatus({status:`ready`}))},this.addToolApprovalResponse=async({id:e,approved:t,reason:n,options:r})=>this.jobExecutor.run(async()=>{let i=this.state.messages,a=i[i.length-1],o=r=>G(r)&&r.state===`approval-requested`&&r.approval.id===e?{...r,state:`approval-responded`,approval:{...r.approval,id:e,approved:t,reason:n}}:r;this.state.replaceMessage(i.length-1,{...a,parts:a.parts.map(o)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(o)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...r})})}),this.addToolOutput=async({state:e=`output-available`,toolCallId:t,output:n,errorText:r,options:i})=>this.jobExecutor.run(async()=>{let a=this.state.messages,o=a[a.length-1],s=i=>G(i)&&i.toolCallId===t?{...i,state:e,output:n,errorText:r}:i;this.state.replaceMessage(a.length-1,{...o,parts:o.parts.map(s)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(s)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...i})})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{this.status!==`streaming`&&this.status!==`submitted`||this.activeResponse?.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=i,this.state=a,this.onError=o,this.onToolCall=s,this.onFinish=c,this.onData=l,this.sendAutomaticallyWhen=u}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async shouldSendAutomatically(){if(!this.sendAutomaticallyWhen)return!1;let e=this.sendAutomaticallyWhen({messages:this.state.messages});return e&&typeof e==`object`&&`then`in e?await e:e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:i}){var a;let o;if(e===`resume-stream`)try{let e=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(e==null)return;o=e}catch(e){this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e});return}this.setStatus({status:`submitted`,error:void 0});let s=this.lastMessage,c=!1,l=!1,u=!1,d;try{let a={state:$r({lastMessage:this.state.snapshot(s),messageId:this.generateId()}),abortController:new AbortController};d=a,a.abortController.signal.addEventListener(`abort`,()=>{c=!0}),this.activeResponse=a;let l;l=e===`resume-stream`?o:await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:a.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:i}),await ti({stream:ei({stream:l,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:e=>this.jobExecutor.run(()=>e({state:a.state,write:()=>{this.setStatus({status:`streaming`}),a.state.message.id===this.lastMessage?.id?this.state.replaceMessage(this.state.messages.length-1,a.state.message):this.state.pushMessage(a.state.message)}})),onError:e=>{throw e}}),onError:e=>{throw e}}),this.setStatus({status:`ready`})}catch(e){if(c||e.name===`AbortError`)return c=!0,this.setStatus({status:`ready`}),null;u=!0,e instanceof TypeError&&(e.message.toLowerCase().includes(`fetch`)||e.message.toLowerCase().includes(`network`))&&(l=!0),this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e})}finally{try{d&&((a=this.onFinish)==null||a.call(this,{message:d.state.message,messages:this.state.messages,isAbort:c,isDisconnect:l,isError:u,finishReason:d.state.finishReason}))}catch(e){console.error(e)}this.activeResponse===d&&(this.activeResponse=void 0)}!u&&await this.shouldSendAutomatically()&&await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,metadata:t,headers:n,body:r})}};function si({messages:e}){let t=e[e.length-1];if(!t||t.role!==`assistant`)return!1;let n=t.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=t.parts.slice(n+1).filter(G).filter(e=>!e.providerExecuted);return r.length>0&&r.every(e=>e.state===`output-available`||e.state===`output-error`)}function ci(e){return new ai({api:ye(`/`,`Chat/Messages/`),credentials:`include`,body:{orgId:e}})}var li=e(t(((e,t)=>{function n(e,t){if(typeof e!=`function`)throw TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...i){clearTimeout(n);let a=Date.now(),o=t-(a-r);o<=0?(r=a,e.apply(this,i)):n=setTimeout(()=>{r=Date.now(),e.apply(this,i)},o)}}t.exports=n}))(),1),ui=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},K=(e,t,n)=>(ui(e,t,`read from private field`),n?n.call(e):t.get(e)),q=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},J=(e,t,n,r)=>(ui(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function di(e,t){return t==null?e:(0,li.default)(e,t)}var Y,fi,pi,X,mi,Z,Q,hi,gi,_i=class{constructor(e=[]){q(this,Y,void 0),q(this,fi,`ready`),q(this,pi,void 0),q(this,X,new Set),q(this,mi,new Set),q(this,Z,new Set),this.pushMessage=e=>{J(this,Y,K(this,Y).concat(e)),K(this,Q).call(this)},this.popMessage=()=>{J(this,Y,K(this,Y).slice(0,-1)),K(this,Q).call(this)},this.replaceMessage=(e,t)=>{J(this,Y,[...K(this,Y).slice(0,e),this.snapshot(t),...K(this,Y).slice(e+1)]),K(this,Q).call(this)},this.snapshot=e=>structuredClone(e),this[`~registerMessagesCallback`]=(e,t)=>{let n=t?di(e,t):e;return K(this,X).add(n),()=>{K(this,X).delete(n)}},this[`~registerStatusCallback`]=e=>(K(this,mi).add(e),()=>{K(this,mi).delete(e)}),this[`~registerErrorCallback`]=e=>(K(this,Z).add(e),()=>{K(this,Z).delete(e)}),q(this,Q,()=>{K(this,X).forEach(e=>e())}),q(this,hi,()=>{K(this,mi).forEach(e=>e())}),q(this,gi,()=>{K(this,Z).forEach(e=>e())}),J(this,Y,e)}get status(){return K(this,fi)}set status(e){J(this,fi,e),K(this,hi).call(this)}get error(){return K(this,pi)}set error(e){J(this,pi,e),K(this,gi).call(this)}get messages(){return K(this,Y)}set messages(e){J(this,Y,[...e]),K(this,Q).call(this)}};Y=new WeakMap,fi=new WeakMap,pi=new WeakMap,X=new WeakMap,mi=new WeakMap,Z=new WeakMap,Q=new WeakMap,hi=new WeakMap,gi=new WeakMap;var $,vi=class extends oi{constructor({messages:e,...t}){let n=new _i(e);super({...t,state:n}),q(this,$,void 0),this[`~registerMessagesCallback`]=(e,t)=>K(this,$)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>K(this,$)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>K(this,$)[`~registerErrorCallback`](e),J(this,$,n)}};$=new WeakMap;function yi({throttle:e,experimental_throttle:t,resume:n=!1,...r}={}){let i=e??t,a=(0,T.useRef)({});`chat`in r||(a.current={onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen,transport:r.transport});let o,s=()=>a.current.transport??(o??=new ai),c={...r,transport:{sendMessages:e=>s().sendMessages(e),reconnectToStream:e=>s().reconnectToStream(e)},onToolCall:e=>{var t;return(t=a.current).onToolCall?.call(t,e)},onData:e=>{var t;return(t=a.current).onData?.call(t,e)},onFinish:e=>{var t;return(t=a.current).onFinish?.call(t,e)},onError:e=>{var t;return(t=a.current).onError?.call(t,e)},sendAutomaticallyWhen:e=>{var t;return(t=a.current).sendAutomaticallyWhen?.call(t,e)??!1}},l=(0,T.useRef)(`chat`in r?r.chat:new vi(c));(`chat`in r&&r.chat!==l.current||`id`in r&&r.id!=null&&l.current.id!==r.id)&&(l.current=`chat`in r?r.chat:new vi(c));let u=(0,T.useSyncExternalStore)((0,T.useCallback)(e=>l.current[`~registerMessagesCallback`](e,i),[i,l.current.id]),()=>l.current.messages,()=>l.current.messages),d=(0,T.useSyncExternalStore)(l.current[`~registerStatusCallback`],()=>l.current.status,()=>l.current.status),f=(0,T.useSyncExternalStore)(l.current[`~registerErrorCallback`],()=>l.current.error,()=>l.current.error),p=(0,T.useCallback)(e=>{typeof e==`function`&&(e=e(l.current.messages)),l.current.messages=e},[l]);return(0,T.useEffect)(()=>{n&&l.current.resumeStream()},[n,l]),{id:l.current.id,messages:u,setMessages:p,sendMessage:l.current.sendMessage,regenerate:l.current.regenerate,clearError:l.current.clearError,stop:l.current.stop,error:f,resumeStream:l.current.resumeStream,status:d,addToolResult:l.current.addToolOutput,addToolOutput:l.current.addToolOutput,addToolApprovalResponse:l.current.addToolApprovalResponse}}function bi({input:e,setInput:t,onSubmit:n,disabled:r,autoFocus:i}){let a=(0,T.useRef)(null);return(0,T.useEffect)(()=>{i&&!r&&a.current?.focus()},[i,r]),(0,E.jsxs)(`form`,{onSubmit:n,className:`input-area`,children:[(0,E.jsx)(`input`,{ref:a,value:e,onChange:e=>t(e.target.value),placeholder:`Type a message...`,disabled:r}),(0,E.jsx)(`button`,{type:`submit`,disabled:r||!e.trim(),children:(0,E.jsx)(dt,{size:18})})]})}function xi(){return(0,E.jsxs)(`div`,{className:`loading-state`,children:[(0,E.jsx)(Re,{className:`animate-spin`,size:24}),(0,E.jsx)(`p`,{children:`Loading conversation...`})]})}var Si={name:`collectFeedback`,description:`Collects feedback from the user by fetching a link to a pre-populated GitHub Discussion. Use this if the user lets us know we did something well, or if the user seems frustrated, or wants to report a bug.`,inputSchema:v({feedbackSummary:o().describe(`A brief summary of the feedback, used as the discussion title.`),feedbackDetails:o().describe(`Detailed feedback from the user or agent observation.`),recap:o().describe(`A sanitized recap of what the agent and user did together and if it was successful. No sensitive information.`)})};async function Ci({input:{feedbackSummary:e,feedbackDetails:t,recap:n}}){let r=e,i=`${t}\n\n${n}`;return{success:!0,url:`https://github.com/HarperFast/harper-agent/discussions/new?category=usage-feedback&title=${encodeURIComponent(r)}&body=${encodeURIComponent(i)}`,message:`Feedback URL created! Ask the user to open it in their browser, and they will be brought to a form to approve the details of the feedback.`}}var wi={...Si,icon:ut,execute:Ci},Ti={name:`createApp`,description:`Create a new Harper app with the specified name and template type.`,inputSchema:v({name:o().trim(),type:m(be)})};async function Ei({input:{name:e,type:t},instanceClientParams:n,baseURL:r}){let i=Me(e),a=ve(me,`id`,t);if(!a)return{success:!1,message:`Error: Invalid template type, ${t}, please choose from: ${me.map(e=>e.id).join(`, `)}`};let o=C.loading(`Creating from template...`,{description:`This may take a bit.`,duration:3e5});try{await Ce({...n,project:i,template:a.npm||a.githubUrl})}catch(e){return{success:!1,message:`Error: ${e}`}}Ie(`ReloadApplicationRootEntries`,!0),C.loading(`Created successfully!`,{description:`${i} created! Restarting the HTTP service...`,id:o,duration:3e5});try{await Ve({...n,operation:`restart_service`,replicated:n.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return C.success(`Created successfully!`,{description:`${i} created!`,id:o,duration:5e3}),{success:!0,message:`App "${i}" created successfully.`,webURL:r}}var Di={...Ti,icon:Oe,execute:Ei,requiresApproval:!0},Oi={name:`deleteTableRecords`,description:`Deletes records in a particular table in a particular database on the server by their primary keys.`,inputSchema:v({database:o().trim(),table:o().trim(),primaryKeys:s(o())})};async function ki({input:{database:e,table:t,primaryKeys:n},instanceClientParams:r,params:i}){try{let a=await Ue({...r,databaseName:e,tableName:t,hashValues:n}),{databaseName:o,tableName:s}=i;return await we.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ai={...Oi,icon:it,execute:ki,requiresApproval:!0},ji={name:`dropComponentFile`,description:`Drops a component file by its full path (which was returned by getComponents)`,inputSchema:v({path:o().trim()})};async function Mi({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await pe({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ni={...ji,icon:Ne,execute:Mi,requiresApproval:!0},Pi={name:`getAnalytics`,description:`Retrieves analytics metrics for the server, such as CPU usage or database operations (reads, writes, messages).`,inputSchema:v({metricName:o().describe(`The name of the metric to retrieve.`),startTime:i().describe(`The start of the time range for the metric, in milliseconds since the Unix epoch.`),endTime:i().describe(`The end of the time range for the metric, in milliseconds since the Unix epoch.`)})};async function Fi({input:e,instanceClientParams:t}){try{let{metricName:n,startTime:r,endTime:i}=e;return{success:!0,data:await rt({metric:n,startTime:r,endTime:i,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var Ii={...Pi,icon:ot,execute:Fi},Li={name:`getComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:v({path:o().trim()})};async function Ri({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await et({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var zi={...Li,icon:he,execute:Ri},Bi={name:`getComponents`,description:`Retrieves a tree of all the component (files and folders) names and sizes stored on the server.`,inputSchema:v({})};async function Vi({instanceClientParams:e}){try{let{rootEntries:t}=xe((await tt(e)).entries);return{success:!0,items:_e(t).items}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Hi={...Bi,icon:ge,execute:Vi},Ui={name:`getDescribeAll`,description:`Retrieves a map of the names of databases and their tables stored on the server.`,inputSchema:v({})};async function Wi({instanceClientParams:e}){try{return{success:!0,map:await Ze(e)}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Gi={...Ui,icon:He,execute:Wi},Ki={name:`getDescribeTable`,description:`Returns the schema metadata describing a particular table in a particular database on the server.`,inputSchema:v({database:o().trim(),table:o().trim()})};async function qi({input:{database:e,table:t},instanceClientParams:n}){try{return{success:!0,data:await Fe({...n,databaseName:e,tableName:t})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ji={...Ki,icon:je,execute:qi},Yi={name:`getUserContext`,description:`Retrieves the context of what the user is looking at on their screen, such as the current page, the file they are viewing, the database and table visible to them, that sort of thing.`,inputSchema:v({})};async function Xi({instanceClientParams:e,params:t}){let n=We();if(n.includes(`/databases`)){let{databaseName:e,tableName:n}=t;return{success:!0,description:`viewing the database`,data:{databaseName:e,tableName:n}}}if(n.endsWith(`/apis`))return{success:!0,description:`viewing the APIs`};if(n.endsWith(`/status`))return{success:!0,description:`viewing the status graphs`};if(n.endsWith(`/logs`))return{success:!0,description:`viewing the logs`};if(n.includes(`/config/`))return{success:!0,description:`viewing the configuration pages`};let r=Ke(`FileFocused/${e.entityId}`,void 0),i=Ke(`FolderOpened/${e.entityId}`,[]),a=Ke(`FileSelected/${e.entityId}`,[]);return r?{success:!0,description:`editing application files`,data:{openedPath:r,expandedItems:i,selectedItems:a}}:{success:!0,description:n}}var Zi={...Yi,icon:Ae,execute:Xi},Qi={name:`insertTableRecords`,description:`Inserts one or more records into a particular table in a particular database on the server.`,inputSchema:v({database:o().trim(),table:o().trim(),records:s(h())})};async function $i({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Qe({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await we.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ea={...Qi,icon:it,execute:$i,requiresApproval:!0},ta={name:`listAnalyticsMetrics`,description:`Lists the available analytics metric names available for calling getAnalytics upon.`,inputSchema:v({metricTypes:m([`builtin`,`custom`]),customWindowMS:i().optional().describe(`Default to one week time window for finding custom metrics.`)})};async function na({metricTypes:e,customWindowMS:t,instanceParams:n}){let{data:r}=await n.instanceClient.post(`/`,{operation:`list_analytics_metrics`,metricTypes:e,customWindowMS:t});return r}async function ra({input:e,instanceClientParams:t}){try{let{metricTypes:n,customWindowMS:r}=e;return{success:!0,metricNames:await na({metricTypes:n,customWindowMS:r,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var ia={...ta,icon:ot,execute:ra},aa=[`adding-tables-with-schemas`,`automatic-apis`,`caching`,`checking-authentication`,`creating-a-fabric-account-and-cluster`,`creating-harper-apps`,`custom-resources`,`defining-relationships`,`deploying-to-harper-fabric`,`extending-tables`,`handling-binary-data`,`load-env`,`logging`,`programmatic-table-requests`,`querying-rest-apis`,`real-time-apps`,`schema-design-tooling`,`serving-web-content`,`typescript-type-stripping`,`using-blob-datatype`,`v5-upgrade`,`vector-indexing`],oa={"adding-tables-with-schemas":"---\nname: adding-tables-with-schemas\ndescription: Guidelines for adding tables to a Harper database using GraphQL schemas.\nmetadata:\n mode: synthesized\n---\n\n# Adding Tables with Schemas\n\nInstructions for the agent to follow when adding tables to a Harper database.\n\n## When to Use\n\nUse this skill when you need to define new data structures or modify existing ones in a Harper database.\n\n## How It Works\n\n1. **Create Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.\n2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/harper/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.\n3. **Define Relationships**: Link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.\n4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. **Important**: REST endpoints also require `rest: true` in `config.yaml` — without it, `@export`ed tables will not respond to HTTP requests. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.\n - `GET /{TableName}`: Describes the schema itself.\n - `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.\n - `GET /{TableName}/{id}`: Retrieves a single record by its ID.\n - `POST /{TableName}/`: Creates a new record.\n - `PUT /{TableName}/{id}`: Updates an existing record.\n - `PATCH /{TableName}/{id}`: Performs a partial update on a record.\n - `DELETE /{TableName}/`: Deletes all records or filtered records.\n - `DELETE /{TableName}/{id}`: Deletes a single record by its ID.\n5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.\n\n## Examples\n\nIn a hypothetical `schemas/ExamplePerson.graphql`:\n\n```graphql\ntype ExamplePerson @table @export {\n id: ID @primaryKey\n name: String\n tag: String @indexed\n}\n```\n","automatic-apis":`---
16
+ ]`;continue}i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function Tn(e,t){let n={type:`object`,additionalProperties:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(e.keyType?._def.typeName===g.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=bn(e.keyType._def,t);return{...n,propertyNames:i}}else if(e.keyType?._def.typeName===g.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};else if(e.keyType?._def.typeName===g.ZodBranded&&e.keyType._def.type._def.typeName===g.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=ln(e.keyType._def,t);return{...n,propertyNames:i}}return n}function En(e,t){return t.mapStrategy===`record`?Tn(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[L(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||N(),L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||N()],minItems:2,maxItems:2}}}function Dn(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function On(){return{not:N()}}function kn(){return{type:`null`}}var An={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function jn(e,t){let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in An&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=An[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}else if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return Mn(e,t)}var Mn=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function Nn(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return{type:[An[e.innerType._def.typeName],`null`]};let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function Pn(e){let t={type:`number`};if(!e.checks)return t;for(let n of e.checks)switch(n.kind){case`int`:t.type=`integer`;break;case`min`:n.inclusive?t.minimum=n.value:t.exclusiveMinimum=n.value;break;case`max`:n.inclusive?t.maximum=n.value:t.exclusiveMaximum=n.value;break;case`multipleOf`:t.multipleOf=n.value;break}return t}function Fn(e,t){let n={type:`object`,properties:{}},r=[],i=e.shape();for(let e in i){let a=i[e];if(a===void 0||a._def===void 0)continue;let o=Ln(a),s=L(a._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});s!==void 0&&(n.properties[e]=s,o||r.push(e))}r.length&&(n.required=r);let a=In(e,t);return a!==void 0&&(n.additionalProperties=a),n}function In(e,t){if(e.catchall._def.typeName!==`ZodNever`)return L(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function Ln(e){try{return e.isOptional()}catch{return!0}}var Rn=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return L(e.innerType._def,t);let n=L(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:N()},n]}:N()},zn=(e,t)=>{if(t.pipeStrategy===`input`)return L(e.in._def,t);if(t.pipeStrategy===`output`)return L(e.out._def,t);let n=L(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,L(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Bn(e,t){return L(e.type._def,t)}function Vn(e,t){let n={type:`array`,uniqueItems:!0,items:L(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&(n.minItems=e.minSize.value),e.maxSize&&(n.maxItems=e.maxSize.value),n}function Hn(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:L(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>L(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Un(){return{not:N()}}function Wn(){return N()}var Gn=(e,t)=>L(e.innerType._def,t),Kn=(e,t,n)=>{switch(t){case g.ZodString:return bn(e,n);case g.ZodNumber:return Pn(e);case g.ZodObject:return Fn(e,n);case g.ZodBigInt:return sn(e);case g.ZodBoolean:return cn();case g.ZodDate:return dn(e,n);case g.ZodUndefined:return Un();case g.ZodNull:return kn();case g.ZodArray:return on(e,n);case g.ZodUnion:case g.ZodDiscriminatedUnion:return jn(e,n);case g.ZodIntersection:return _n(e,n);case g.ZodTuple:return Hn(e,n);case g.ZodRecord:return Tn(e,n);case g.ZodLiteral:return vn(e);case g.ZodEnum:return hn(e);case g.ZodNativeEnum:return Dn(e);case g.ZodNullable:return Nn(e,n);case g.ZodOptional:return Rn(e,n);case g.ZodMap:return En(e,n);case g.ZodSet:return Vn(e,n);case g.ZodLazy:return()=>e.getter()._def;case g.ZodPromise:return Bn(e,n);case g.ZodNaN:case g.ZodNever:return On();case g.ZodEffects:return mn(e,n);case g.ZodAny:return N();case g.ZodUnknown:return Wn();case g.ZodDefault:return pn(e,n);case g.ZodBranded:return ln(e,n);case g.ZodReadonly:return Gn(e,n);case g.ZodCatch:return un(e,n);case g.ZodPipeline:return zn(e,n);case g.ZodFunction:case g.ZodVoid:case g.ZodSymbol:return;default:return(e=>void 0)(t)}},qn=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function L(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.call(t,e,t,r,n);if(i!==nn)return i}if(r&&!n){let e=Jn(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Kn(e,e.typeName,t),o=typeof a==`function`?L(a(),t):a;if(o&&Yn(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}var Jn=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:qn(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),N()):t.$refStrategy===`seen`?N():void 0}},Yn=(e,t,n)=>(e.description&&(n.description=e.description),n),Xn=e=>{let t=an(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}},Zn=(e,t)=>{let n=Xn(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:L(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??N()}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=L(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??N(),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o);let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return s.$schema=`http://json-schema.org/draft-07/schema#`,s},Qn=Symbol.for(`vercel.ai.schema`);function $n(e){let t;return()=>(t??=e(),t)}function er(e,{validate:t}={}){return{[Qn]:!0,_type:void 0,get jsonSchema(){return typeof e==`function`&&(e=e()),e},validate:t}}function tr(e){return typeof e==`object`&&!!e&&Qn in e&&e[Qn]===!0&&`jsonSchema`in e&&`validate`in e}function nr(e){return e==null?er({type:`object`,properties:{},additionalProperties:!1}):tr(e)?e:`~standard`in e?e[`~standard`].vendor===`zod`?cr(e):rr(e):e()}function rr(e){return er(()=>{if(!ir(e))throw Error(`Standard schema vendor '${e[`~standard`].vendor}' does not support JSON Schema conversion.`);return tn(e[`~standard`].jsonSchema.input({target:`draft-07`}))},{validate:async t=>{let n=await e[`~standard`].validate(t);return`value`in n?{success:!0,value:n.value}:{success:!1,error:new O({value:t,cause:n.issues})}}})}function ir(e){return e[`~standard`].jsonSchema!=null}function ar(e,t){let n=t?.useReferences??!1;return er(()=>Zn(e,{$refStrategy:n?`root`:`none`}),{validate:async t=>{let n=await e.safeParseAsync(t);return n.success?{success:!0,value:n.data}:{success:!1,error:n.error}}})}function or(e,t){let r=t?.useReferences??!1;return er(()=>tn(ee(e,{target:`draft-7`,io:`input`,reused:r?`ref`:`inline`})),{validate:async t=>{let r=await n(e,t);return r.success?{success:!0,value:r.data}:{success:!1,error:r.error}}})}function sr(e){return`_zod`in e}function cr(e,t){return sr(e)?or(e,t):ar(e,t)}async function lr({value:e,schema:t,context:n}){let r=await R({value:e,schema:t,context:n});if(!r.success)throw O.wrap({value:e,cause:r.error,context:n});return r.value}async function R({value:e,schema:t,context:n}){let r=nr(t);try{if(r.validate==null)return{success:!0,value:e,rawValue:e};let t=await r.validate(e);return t.success?{success:!0,value:t.value,rawValue:e}:{success:!1,error:O.wrap({value:e,cause:t.error,context:n}),rawValue:e}}catch(t){return{success:!1,error:O.wrap({value:e,cause:t,context:n}),rawValue:e}}}async function z({text:e,schema:t}){try{let n=en(e);return t==null?{success:!0,value:n,rawValue:n}:await R({value:n,schema:t})}catch(t){return{success:!1,error:Mt.isInstance(t)?t:new Mt({text:e,cause:t}),rawValue:void 0}}}function ur({stream:e,schema:t}){return e.pipeThrough(new TextDecoderStream).pipeThrough(new Gt).pipeThrough(new TransformStream({async transform({data:e},n){e!==`[DONE]`&&n.enqueue(await z({text:e,schema:t}))}}))}async function B(e){return typeof e==`function`&&(e=e()),Promise.resolve(e)}new TextDecoder;var dr=Object.defineProperty,fr=(e,t)=>{for(var n in t)dr(e,n,{get:t[n],enumerable:!0})},pr=`AI_NoObjectGeneratedError`,mr=`vercel.ai.error.${pr}`,hr=Symbol.for(mr),gr,V=class extends D{constructor({message:e=`No object generated.`,cause:t,text:n,response:r,usage:i,finishReason:a}){super({name:pr,message:e,cause:t}),this[gr]=!0,this.text=n,this.response=r,this.usage=i,this.finishReason=a}static isInstance(e){return D.hasMarker(e,mr)}};gr=hr;var _r=`AI_UIMessageStreamError`,vr=`vercel.ai.error.${_r}`,yr=Symbol.for(vr),br,H=class extends D{constructor({chunkType:e,chunkId:t,message:n}){super({name:_r,message:n}),this[br]=!0,this.chunkType=e,this.chunkId=t}static isInstance(e){return D.hasMarker(e,vr)}};br=yr;function xr(e,t){if(e===void 0&&t===void 0)return;if(e===void 0)return t;if(t===void 0)return e;let n={...e};for(let r in t)if(!(r===`__proto__`||r===`constructor`||r===`prototype`)&&Object.prototype.hasOwnProperty.call(t,r)){let i=t[r];if(i===void 0)continue;let a=r in e?e[r]:void 0,o=typeof i==`object`&&!!i&&!Array.isArray(i)&&!(i instanceof Date)&&!(i instanceof RegExp),s=typeof a==`object`&&!!a&&!Array.isArray(a)&&!(a instanceof Date)&&!(a instanceof RegExp);o&&s?n[r]=xr(a,i):n[r]=i}return n}var U=p(()=>y([a(),o(),i(),d(),b(o(),U.optional()),s(U)])),W=b(o(),b(o(),U.optional())),Sr=y([o(),u(Uint8Array),u(ArrayBuffer),_(Yt,{message:`Must be a Buffer`})]),Cr=b(o(),o()),wr=v({type:f(`text`),text:o(),providerOptions:W.optional()}),Tr=v({type:f(`image`),image:y([Sr,u(URL),Cr]),mediaType:o().optional(),providerOptions:W.optional()}),Er=c(`type`,[v({type:f(`data`),data:Sr}),v({type:f(`url`),url:u(URL)}),v({type:f(`reference`),reference:Cr}),v({type:f(`text`),text:o()})]),Dr=c(`type`,[v({type:f(`data`),data:Sr}),v({type:f(`url`),url:u(URL)})]),Or=v({type:f(`file`),data:y([Er,Sr,u(URL),Cr]),filename:o().optional(),mediaType:o(),providerOptions:W.optional()}),kr=v({type:f(`reasoning`),text:o(),providerOptions:W.optional()}),Ar=v({type:f(`custom`),kind:o().transform(e=>e),providerOptions:W.optional()}),jr=v({type:f(`reasoning-file`),data:y([Dr,Sr,u(URL)]),mediaType:o(),providerOptions:W.optional()}),Mr=v({type:f(`tool-call`),toolCallId:o(),toolName:o(),input:r(),providerOptions:W.optional(),providerExecuted:d().optional()}),Nr=c(`type`,[v({type:f(`text`),value:o(),providerOptions:W.optional()}),v({type:f(`json`),value:U,providerOptions:W.optional()}),v({type:f(`execution-denied`),reason:o().optional(),providerOptions:W.optional()}),v({type:f(`error-text`),value:o(),providerOptions:W.optional()}),v({type:f(`error-json`),value:U,providerOptions:W.optional()}),v({type:f(`content`),value:s(y([v({type:f(`text`),text:o(),providerOptions:W.optional()}),v({type:f(`file`),data:Er,mediaType:o(),filename:o().optional(),providerOptions:W.optional()}),v({type:f(`file-data`),data:o(),mediaType:o(),filename:o().optional(),providerOptions:W.optional()}),v({type:f(`file-url`),url:o(),mediaType:o().optional(),providerOptions:W.optional()}),v({type:f(`file-id`),fileId:y([o(),b(o(),o())]),providerOptions:W.optional()}),v({type:f(`file-reference`),providerReference:b(o(),o()),providerOptions:W.optional()}),v({type:f(`image-data`),data:o(),mediaType:o(),providerOptions:W.optional()}),v({type:f(`image-url`),url:o(),providerOptions:W.optional()}),v({type:f(`image-file-id`),fileId:y([o(),b(o(),o())]),providerOptions:W.optional()}),v({type:f(`image-file-reference`),providerReference:b(o(),o()),providerOptions:W.optional()}),v({type:f(`custom`),providerOptions:W.optional()})]))})]),Pr=v({type:f(`tool-result`),toolCallId:o(),toolName:o(),output:Nr,providerOptions:W.optional()}),Fr=v({type:f(`tool-approval-request`),approvalId:o(),toolCallId:o()}),Ir=v({type:f(`tool-approval-response`),approvalId:o(),approved:d(),reason:o().optional()});y([v({role:f(`system`),content:o(),providerOptions:W.optional()}),v({role:f(`user`),content:y([o(),s(y([wr,Tr,Or]))]),providerOptions:W.optional()}),v({role:f(`assistant`),content:y([o(),s(y([wr,Ar,Or,kr,jr,Mr,Pr,Fr]))]),providerOptions:W.optional()}),v({role:f(`tool`),content:s(y([Pr,Ir])),providerOptions:W.optional()})]),fr({},{array:()=>Vr,choice:()=>Hr,json:()=>Ur,object:()=>Br,text:()=>zr});function Lr(e){let t=[`ROOT`],n=-1,r=null,i=0;function a(e){return e>=`0`&&e<=`9`||e>=`A`&&e<=`F`||e>=`a`&&e<=`f`}function o(e,i,a){switch(e){case`"`:n=i,t.pop(),t.push(a),t.push(`INSIDE_STRING`);break;case`f`:case`t`:case`n`:n=i,r=i,t.pop(),t.push(a),t.push(`INSIDE_LITERAL`);break;case`-`:t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=i,t.pop(),t.push(a),t.push(`INSIDE_NUMBER`);break;case`{`:n=i,t.pop(),t.push(a),t.push(`INSIDE_OBJECT_START`);break;case`[`:n=i,t.pop(),t.push(a),t.push(`INSIDE_ARRAY_START`);break}}function s(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_COMMA`);break;case`}`:n=r,t.pop();break}}function c(e,r){switch(e){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=r,t.pop();break}}for(let l=0;l<e.length;l++){let u=e[l];switch(t[t.length-1]){case`ROOT`:o(u,l,`FINISH`);break;case`INSIDE_OBJECT_START`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break;case`}`:n=l,t.pop();break}break;case`INSIDE_OBJECT_AFTER_COMMA`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_KEY`);break}break;case`INSIDE_OBJECT_KEY`:switch(u){case`"`:t.pop(),t.push(`INSIDE_OBJECT_AFTER_KEY`);break}break;case`INSIDE_OBJECT_AFTER_KEY`:switch(u){case`:`:t.pop(),t.push(`INSIDE_OBJECT_BEFORE_VALUE`);break}break;case`INSIDE_OBJECT_BEFORE_VALUE`:o(u,l,`INSIDE_OBJECT_AFTER_VALUE`);break;case`INSIDE_OBJECT_AFTER_VALUE`:s(u,l);break;case`INSIDE_STRING`:switch(u){case`"`:t.pop(),n=l;break;case`\\`:t.push(`INSIDE_STRING_ESCAPE`);break;default:n=l}break;case`INSIDE_ARRAY_START`:switch(u){case`]`:n=l,t.pop();break;default:n=l,o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break}break;case`INSIDE_ARRAY_AFTER_VALUE`:switch(u){case`,`:t.pop(),t.push(`INSIDE_ARRAY_AFTER_COMMA`);break;case`]`:n=l,t.pop();break;default:n=l;break}break;case`INSIDE_ARRAY_AFTER_COMMA`:o(u,l,`INSIDE_ARRAY_AFTER_VALUE`);break;case`INSIDE_STRING_ESCAPE`:t.pop(),u===`u`?(i=0,t.push(`INSIDE_STRING_UNICODE_ESCAPE`)):n=l;break;case`INSIDE_STRING_UNICODE_ESCAPE`:a(u)&&(i++,i===4&&(t.pop(),n=l));break;case`INSIDE_NUMBER`:switch(u){case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n=l;break;case`e`:case`E`:case`-`:case`.`:break;case`,`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`}`:t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`&&s(u,l);break;case`]`:t.pop(),t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l);break;default:t.pop();break}break;case`INSIDE_LITERAL`:{let i=e.substring(r,l+1);!`false`.startsWith(i)&&!`true`.startsWith(i)&&!`null`.startsWith(i)?(t.pop(),t[t.length-1]===`INSIDE_OBJECT_AFTER_VALUE`?s(u,l):t[t.length-1]===`INSIDE_ARRAY_AFTER_VALUE`&&c(u,l)):n=l;break}}}let l=e.slice(0,n+1);for(let n=t.length-1;n>=0;n--)switch(t[n]){case`INSIDE_STRING`:l+=`"`;break;case`INSIDE_OBJECT_KEY`:case`INSIDE_OBJECT_AFTER_KEY`:case`INSIDE_OBJECT_AFTER_COMMA`:case`INSIDE_OBJECT_START`:case`INSIDE_OBJECT_BEFORE_VALUE`:case`INSIDE_OBJECT_AFTER_VALUE`:l+=`}`;break;case`INSIDE_ARRAY_START`:case`INSIDE_ARRAY_AFTER_COMMA`:case`INSIDE_ARRAY_AFTER_VALUE`:l+=`]`;break;case`INSIDE_LITERAL`:{let t=e.substring(r,e.length);`true`.startsWith(t)?l+=`true`.slice(t.length):`false`.startsWith(t)?l+=`false`.slice(t.length):`null`.startsWith(t)&&(l+=`null`.slice(t.length))}}return l}async function Rr(e){if(e===void 0)return{value:void 0,state:`undefined-input`};let t=await z({text:e});return t.success?{value:t.value,state:`successful-parse`}:(t=await z({text:Lr(e)}),t.success?{value:t.value,state:`repaired-parse`}:{value:void 0,state:`failed-parse`})}var zr=()=>({name:`text`,responseFormat:Promise.resolve({type:`text`}),async parseCompleteOutput({text:e}){return e},async parsePartialOutput({text:e}){return{partial:e}},createElementStreamTransform(){}}),Br=({schema:e,name:t,description:n})=>{let r=nr(e);return{name:`object`,responseFormat:B(r.jsonSchema).then(e=>({type:`json`,schema:e,...t!=null&&{name:t},...n!=null&&{description:n}})),async parseCompleteOutput({text:e},t){let n=await z({text:e});if(!n.success)throw new V({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=await R({value:n.value,schema:r});if(!i.success)throw new V({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return i.value},async parsePartialOutput({text:e}){let t=await Rr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return{partial:t.value}}},createElementStreamTransform(){}}},Vr=({element:e,name:t,description:n})=>{let r=nr(e);return{name:`array`,responseFormat:B(r.jsonSchema).then(e=>{let{$schema:r,...i}=e;return{type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{elements:{type:`array`,items:i}},required:[`elements`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}}),async parseCompleteOutput({text:e},t){let n=await z({text:e});if(!n.success)throw new V({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let i=n.value;if(typeof i!=`object`||!i||!(`elements`in i)||!Array.isArray(i.elements))throw new V({message:`No object generated: response did not match schema.`,cause:new O({value:i,cause:`response must be an object with an elements array`}),text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});let a=[];for(let n of i.elements){let i=await R({value:n,schema:r});if(!i.success)throw new V({message:`No object generated: response did not match schema.`,cause:i.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});a.push(i.value)}return a},async parsePartialOutput({text:e}){let t=await Rr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let e=t.value;if(typeof e!=`object`||!e||!(`elements`in e)||!Array.isArray(e.elements))return;let n=t.state===`repaired-parse`&&e.elements.length>0?e.elements.slice(0,-1):e.elements,i=[];for(let e of n){let t=await R({value:e,schema:r});t.success&&i.push(t.value)}return{partial:i}}}},createElementStreamTransform(){let e=0;return new TransformStream({transform({partialOutput:t},n){if(t!=null)for(;e<t.length;e++)n.enqueue(t[e])}})}}},Hr=({options:e,name:t,description:n})=>({name:`choice`,responseFormat:Promise.resolve({type:`json`,schema:{$schema:`http://json-schema.org/draft-07/schema#`,type:`object`,properties:{result:{type:`string`,enum:e}},required:[`result`],additionalProperties:!1},...t!=null&&{name:t},...n!=null&&{description:n}}),async parseCompleteOutput({text:t},n){let r=await z({text:t});if(!r.success)throw new V({message:`No object generated: could not parse the response.`,cause:r.error,text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});let i=r.value;if(typeof i!=`object`||!i||!(`result`in i)||typeof i.result!=`string`||!e.includes(i.result))throw new V({message:`No object generated: response did not match schema.`,cause:new O({value:i,cause:`response must be an object that contains a choice value.`}),text:t,response:n.response,usage:n.usage,finishReason:n.finishReason});return i.result},async parsePartialOutput({text:t}){let n=await Rr(t);switch(n.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:{let t=n.value;if(typeof t!=`object`||!t||!(`result`in t)||typeof t.result!=`string`)return;let r=e.filter(e=>e.startsWith(t.result));return n.state===`successful-parse`?r.includes(t.result)?{partial:t.result}:void 0:r.length===1?{partial:r[0]}:void 0}}},createElementStreamTransform(){}}),Ur=({name:e,description:t}={})=>({name:`json`,responseFormat:Promise.resolve({type:`json`,...e!=null&&{name:e},...t!=null&&{description:t}}),async parseCompleteOutput({text:e},t){let n=await z({text:e});if(!n.success)throw new V({message:`No object generated: could not parse the response.`,cause:n.error,text:e,response:t.response,usage:t.usage,finishReason:t.finishReason});return n.value},async parsePartialOutput({text:e}){let t=await Rr(e);switch(t.state){case`failed-parse`:case`undefined-input`:return;case`repaired-parse`:case`successful-parse`:return t.value===void 0?void 0:{partial:t.value}}},createElementStreamTransform(){}});new TextEncoder,new TextEncoder,A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),TransformStream;var Wr=b(o(),U.optional()),Gr=$n(()=>cr(y([l({type:f(`text-start`),id:o(),providerMetadata:W.optional()}),l({type:f(`text-delta`),id:o(),delta:o(),providerMetadata:W.optional()}),l({type:f(`text-end`),id:o(),providerMetadata:W.optional()}),l({type:f(`error`),errorText:o()}),l({type:f(`tool-input-start`),toolCallId:o(),toolName:o(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional(),title:o().optional()}),l({type:f(`tool-input-delta`),toolCallId:o(),inputTextDelta:o()}),l({type:f(`tool-input-available`),toolCallId:o(),toolName:o(),input:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional(),title:o().optional()}),l({type:f(`tool-input-error`),toolCallId:o(),toolName:o(),input:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional(),errorText:o(),title:o().optional()}),l({type:f(`tool-approval-request`),approvalId:o(),toolCallId:o(),isAutomatic:d().optional(),signature:o().optional()}),l({type:f(`tool-approval-response`),approvalId:o(),approved:d(),reason:o().optional(),providerExecuted:d().optional(),providerMetadata:W.optional()}),l({type:f(`tool-output-available`),toolCallId:o(),output:r(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional(),preliminary:d().optional()}),l({type:f(`tool-output-error`),toolCallId:o(),errorText:o(),providerExecuted:d().optional(),providerMetadata:W.optional(),toolMetadata:Wr.optional(),dynamic:d().optional()}),l({type:f(`tool-output-denied`),toolCallId:o()}),l({type:f(`reasoning-start`),id:o(),providerMetadata:W.optional()}),l({type:f(`reasoning-delta`),id:o(),delta:o(),providerMetadata:W.optional()}),l({type:f(`reasoning-end`),id:o(),providerMetadata:W.optional()}),l({type:f(`custom`),kind:o().transform(e=>e),providerMetadata:W.optional()}),l({type:f(`source-url`),sourceId:o(),url:o(),title:o().optional(),providerMetadata:W.optional()}),l({type:f(`source-document`),sourceId:o(),mediaType:o(),title:o(),filename:o().optional(),providerMetadata:W.optional()}),l({type:f(`file`),url:o(),mediaType:o(),providerMetadata:W.optional()}),l({type:f(`reasoning-file`),url:o(),mediaType:o(),providerMetadata:W.optional()}),l({type:_(e=>typeof e==`string`&&e.startsWith(`data-`),{message:`Type must start with "data-"`}),id:o().optional(),data:r(),transient:d().optional()}),l({type:f(`start-step`)}),l({type:f(`finish-step`)}),l({type:f(`start`),messageId:o().optional(),messageMetadata:r().optional()}),l({type:f(`finish`),finishReason:m([`stop`,`length`,`content-filter`,`tool-calls`,`error`,`other`]).optional(),messageMetadata:r().optional()}),l({type:f(`abort`),reason:o().optional()}),l({type:f(`message-metadata`),messageMetadata:r()})])));function Kr(e){return e.type.startsWith(`data-`)}function qr(){return Object.create(null)}function Jr(e){return e.type===`text`}function Yr(e){return e.type.startsWith(`tool-`)}function Xr(e){return e.type===`dynamic-tool`}function G(e){return Yr(e)||Xr(e)}function Zr(e){return e.type.split(`-`).slice(1).join(`-`)}function Qr(e){return Xr(e)?e.toolName:Zr(e)}function $r({lastMessage:e,messageId:t}){return{message:e?.role===`assistant`?e:{id:t,metadata:void 0,role:`assistant`,parts:[]},activeTextParts:qr(),activeReasoningParts:qr(),partialToolCalls:qr()}}function ei({stream:e,messageMetadataSchema:t,dataPartSchemas:n,runUpdateMessageJob:r,onError:i,onToolCall:a,onData:o}){return e.pipeThrough(new TransformStream({async transform(e,s){await r(async({state:r,write:c})=>{function l(){let e=r.message.parts,t=e.length-1;for(;t>=0&&e[t].type!==`step-start`;)t--;return e.slice(t+1)}function u(){return l().filter(G)}function d(e){let t=u().find(t=>t.toolCallId===e);if(t==null){let n=r.message.parts;for(let r=n.length-1;r>=0;r--){let i=n[r];if(G(i)&&i.toolCallId===e){t=i;break}}}if(t==null)throw new H({chunkType:`tool-invocation`,chunkId:e,message:`No tool invocation found for tool call ID "${e}".`});return t}function f(e){let t=r.message.parts.filter(G).find(t=>t.approval?.id===e);if(t==null)throw new H({chunkType:`tool-approval-response`,chunkId:e,message:`No tool invocation found for approval ID "${e}".`});return t}function p(e,t){let n=t??l().find(t=>Yr(t)&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null)if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}else r.message.parts.push({type:`tool-${e.toolName}`,toolCallId:e.toolCallId,state:e.state,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},input:i.input,output:i.output,rawInput:i.rawInput,errorText:i.errorText,providerExecuted:i.providerExecuted,preliminary:i.preliminary,...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&!(e.state===`output-available`||e.state===`output-error`)?{callProviderMetadata:i.providerMetadata}:{}})}function m(e,t){let n=t??l().find(t=>t.type===`dynamic-tool`&&t.toolCallId===e.toolCallId),i=e,a=n;if(n!=null){n.state=e.state,a.toolName=e.toolName,a.input=i.input,a.output=i.output,a.errorText=i.errorText,a.rawInput=i.rawInput??a.rawInput,a.preliminary=i.preliminary,e.title!==void 0&&(a.title=e.title),e.toolMetadata!==void 0&&(a.toolMetadata=e.toolMetadata),a.providerExecuted=i.providerExecuted??n.providerExecuted;let t=i.providerMetadata;if(t!=null)if(e.state===`output-available`||e.state===`output-error`){let e=n;e.resultProviderMetadata=t}else n.callProviderMetadata=t}else r.message.parts.push({type:`dynamic-tool`,toolName:e.toolName,toolCallId:e.toolCallId,state:e.state,input:i.input,output:i.output,errorText:i.errorText,preliminary:i.preliminary,providerExecuted:i.providerExecuted,title:e.title,...e.toolMetadata===void 0?{}:{toolMetadata:e.toolMetadata},...i.providerMetadata!=null&&(e.state===`output-available`||e.state===`output-error`)?{resultProviderMetadata:i.providerMetadata}:{},...i.providerMetadata!=null&&!(e.state===`output-available`||e.state===`output-error`)?{callProviderMetadata:i.providerMetadata}:{}})}async function h(e){if(e!=null){let n=r.message.metadata==null?e:xr(r.message.metadata,e);t!=null&&await lr({value:n,schema:t,context:{field:`message.metadata`,entityId:r.message.id}}),r.message.metadata=n}}switch(e.type){case`text-start`:{let t={type:`text`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeTextParts[e.id]=t,r.message.parts.push(t),c();break}case`text-delta`:{let t=r.activeTextParts[e.id];if(t==null)throw new H({chunkType:`text-delta`,chunkId:e.id,message:`Received text-delta for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`text-end`:{let t=r.activeTextParts[e.id];if(t==null)throw new H({chunkType:`text-end`,chunkId:e.id,message:`Received text-end for missing text part with ID "${e.id}". Ensure a "text-start" chunk is sent before any "text-end" chunks.`});t.state=`done`,t.providerMetadata=e.providerMetadata??t.providerMetadata,delete r.activeTextParts[e.id],c();break}case`custom`:{let t={type:`custom`,kind:e.kind,providerMetadata:e.providerMetadata};r.message.parts.push(t),c();break}case`reasoning-start`:{let t={type:`reasoning`,text:``,providerMetadata:e.providerMetadata,state:`streaming`};r.activeReasoningParts[e.id]=t,r.message.parts.push(t),c();break}case`reasoning-delta`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new H({chunkType:`reasoning-delta`,chunkId:e.id,message:`Received reasoning-delta for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-delta" chunks.`});t.text+=e.delta,t.providerMetadata=e.providerMetadata??t.providerMetadata,c();break}case`reasoning-end`:{let t=r.activeReasoningParts[e.id];if(t==null)throw new H({chunkType:`reasoning-end`,chunkId:e.id,message:`Received reasoning-end for missing reasoning part with ID "${e.id}". Ensure a "reasoning-start" chunk is sent before any "reasoning-end" chunks.`});t.providerMetadata=e.providerMetadata??t.providerMetadata,t.state=`done`,delete r.activeReasoningParts[e.id],c();break}case`file`:case`reasoning-file`:r.message.parts.push({type:e.type,mediaType:e.mediaType,url:e.url,...e.providerMetadata==null?{}:{providerMetadata:e.providerMetadata}}),c();break;case`source-url`:r.message.parts.push({type:`source-url`,sourceId:e.sourceId,url:e.url,title:e.title,providerMetadata:e.providerMetadata}),c();break;case`source-document`:r.message.parts.push({type:`source-document`,sourceId:e.sourceId,mediaType:e.mediaType,title:e.title,filename:e.filename,providerMetadata:e.providerMetadata}),c();break;case`tool-input-start`:{let t=l().filter(Yr);r.partialToolCalls[e.toolCallId]={text:``,toolName:e.toolName,index:t.length,dynamic:e.dynamic,title:e.title,toolMetadata:e.toolMetadata},e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-streaming`,input:void 0,providerExecuted:e.providerExecuted,title:e.title,toolMetadata:e.toolMetadata,providerMetadata:e.providerMetadata}),c();break}case`tool-input-delta`:{let t=r.partialToolCalls[e.toolCallId];if(t==null)throw new H({chunkType:`tool-input-delta`,chunkId:e.toolCallId,message:`Received tool-input-delta for missing tool call with ID "${e.toolCallId}". Ensure a "tool-input-start" chunk is sent before any "tool-input-delta" chunks.`});t.text+=e.inputTextDelta;let{value:n}=await Rr(t.text);t.dynamic?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}):p({toolCallId:e.toolCallId,toolName:t.toolName,state:`input-streaming`,input:n,title:t.title,toolMetadata:t.toolMetadata}),c();break}case`tool-input-available`:e.dynamic?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`input-available`,input:e.input,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:e.title,toolMetadata:e.toolMetadata}),c(),a&&!e.providerExecuted&&await a({toolCall:e});break;case`tool-input-error`:{let t=l().filter(G).find(t=>t.toolCallId===e.toolCallId);(t==null?e.dynamic:t.type===`dynamic-tool`)?m({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}):p({toolCallId:e.toolCallId,toolName:e.toolName,state:`output-error`,input:void 0,rawInput:e.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,toolMetadata:e.toolMetadata}),c();break}case`tool-approval-request`:{let t=d(e.toolCallId);t.state=`approval-requested`,t.approval={id:e.approvalId,...e.isAutomatic===!0?{isAutomatic:!0}:{},...e.signature==null?{}:{signature:e.signature}},c();break}case`tool-approval-response`:{let t=f(e.approvalId),n=t.approval==null?{id:e.approvalId}:t.approval;t.state=`approval-responded`,t.approval={id:e.approvalId,approved:e.approved,...e.reason==null?{}:{reason:e.reason},...n.isAutomatic===!0?{isAutomatic:!0}:{},...n.signature==null?{}:{signature:n.signature}},e.providerExecuted!=null&&(t.providerExecuted=e.providerExecuted),e.providerMetadata!=null&&(t.callProviderMetadata=e.providerMetadata),c();break}case`tool-output-denied`:{let t=d(e.toolCallId);t.state=`output-denied`,c();break}case`tool-output-available`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-available`,input:t.input,output:e.output,preliminary:e.preliminary,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:Zr(t),state:`output-available`,input:t.input,output:e.output,providerExecuted:e.providerExecuted,preliminary:e.preliminary,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`tool-output-error`:{let t=d(e.toolCallId);t.type===`dynamic-tool`?m({toolCallId:e.toolCallId,toolName:t.toolName,state:`output-error`,input:t.input,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t):p({toolCallId:e.toolCallId,toolName:Zr(t),state:`output-error`,input:t.input,rawInput:t.rawInput,errorText:e.errorText,providerExecuted:e.providerExecuted,providerMetadata:e.providerMetadata,title:t.title,toolMetadata:t.toolMetadata},t),c();break}case`start-step`:r.message.parts.push({type:`step-start`});break;case`finish-step`:r.activeTextParts=qr(),r.activeReasoningParts=qr();break;case`start`:e.messageId!=null&&(r.message.id=e.messageId),await h(e.messageMetadata),(e.messageId!=null||e.messageMetadata!=null)&&c();break;case`finish`:e.finishReason!=null&&(r.finishReason=e.finishReason),await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`message-metadata`:await h(e.messageMetadata),e.messageMetadata!=null&&c();break;case`error`:i?.(Error(e.errorText));break;default:if(Kr(e)){if(n?.[e.type]!=null){let t=r.message.parts.findIndex(t=>`id`in t&&`data`in t&&t.id===e.id&&t.type===e.type),i=t>=0?t:r.message.parts.length;await lr({value:e.data,schema:n[e.type],context:{field:`message.parts[${i}].data`,entityName:e.type,entityId:e.id}})}let t=e;if(t.transient){o?.(t);break}let i=t.id==null?void 0:r.message.parts.find(e=>t.type===e.type&&t.id===e.id);i==null?r.message.parts.push(t):i.data=t.data,o?.(t),c()}}s.enqueue(e)})}}))}async function ti({stream:e,onError:t}){let n=e.getReader();try{for(;;){let{done:e}=await n.read();if(e)break}}catch(e){t?.(e)}finally{n.releaseLock()}}A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),A({prefix:`aitxt`,size:24}),A({prefix:`call`,size:24}),b(o(),U.optional()),b(o(),o()),A({prefix:`call`,size:24}),A({prefix:`call`,size:24}),A({prefix:`aiobj`,size:24});var ni=class{constructor(){this.queue=[],this.isProcessing=!1}async processQueue(){if(!this.isProcessing){for(this.isProcessing=!0;this.queue.length>0;)await this.queue[0](),this.queue.shift();this.isProcessing=!1}}async run(e){return new Promise((t,n)=>{this.queue.push(async()=>{try{await e(),t()}catch(e){n(e)}}),this.processQueue()})}};A({prefix:`aiobj`,size:24}),A({prefix:`call`,size:24});async function ri(e){if(e==null)return[];if(!globalThis.FileList||!(e instanceof globalThis.FileList))throw Error(`FileList is not supported in the current environment`);return Promise.all(Array.from(e).map(async e=>{let{name:t,type:n}=e;return{type:`file`,mediaType:n,filename:t,url:await new Promise((t,n)=>{let r=new FileReader;r.onload=e=>{t(e.target?.result)},r.onerror=e=>n(e),r.readAsDataURL(e)})}}))}var ii=class{constructor({api:e=`/api/chat`,credentials:t,headers:n,body:r,fetch:i,prepareSendMessagesRequest:a,prepareReconnectToStreamRequest:o}){this.api=e,this.credentials=t,this.headers=n,this.body=r,this.fetch=i,this.prepareSendMessagesRequest=a,this.prepareReconnectToStreamRequest=o}async sendMessages({abortSignal:e,...t}){let n=await B(this.body),r=await B(this.headers),i=await B(this.credentials),a={...j(r),...j(t.headers)},o=await this.prepareSendMessagesRequest?.call(this,{api:this.api,id:t.chatId,messages:t.messages,body:{...n,...t.body},headers:a,credentials:i,requestMetadata:t.metadata,trigger:t.trigger,messageId:t.messageId}),s=o?.api??this.api,c=o?.headers===void 0?a:j(o.headers),l=o?.body===void 0?{...n,...t.body,id:t.chatId,messages:t.messages,trigger:t.trigger,messageId:t.messageId}:o.body,u=o?.credentials??i,d=await(this.fetch??globalThis.fetch)(s,{method:`POST`,headers:{"Content-Type":`application/json`,...c},body:JSON.stringify(l),credentials:u,signal:e});if(!d.ok)throw Error(await d.text()??`Failed to fetch the chat response.`);if(!d.body)throw Error(`The response body is empty.`);return this.processResponseStream(d.body)}async reconnectToStream(e){let t=await B(this.body),n=await B(this.headers),r=await B(this.credentials),i={...j(n),...j(e.headers)},a=await this.prepareReconnectToStreamRequest?.call(this,{api:this.api,id:e.chatId,body:{...t,...e.body},headers:i,credentials:r,requestMetadata:e.metadata}),o=a?.api??`${this.api}/${e.chatId}/stream`,s=a?.headers===void 0?i:j(a.headers),c=a?.credentials??r,l=await(this.fetch??globalThis.fetch)(o,{method:`GET`,headers:s,credentials:c});if(l.status===204)return null;if(!l.ok)throw Error(await l.text()??`Failed to fetch the chat response.`);if(!l.body)throw Error(`The response body is empty.`);return this.processResponseStream(l.body)}},ai=class extends ii{constructor(e={}){super(e)}processResponseStream(e){return ur({stream:e,schema:Gr}).pipeThrough(new TransformStream({async transform(e,t){if(!e.success)throw e.error;t.enqueue(e.value)}}))}},oi=class{constructor({generateId:e=Jt,id:t=e(),transport:n=new ai,messageMetadataSchema:r,dataPartSchemas:i,state:a,onError:o,onToolCall:s,onFinish:c,onData:l,sendAutomaticallyWhen:u}){this.activeResponse=void 0,this.jobExecutor=new ni,this.sendMessage=async(e,t)=>{if(e==null){await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...t});return}let n;if(n=`text`in e||`files`in e?{parts:[...Array.isArray(e.files)?e.files:await ri(e.files),...`text`in e&&e.text!=null?[{type:`text`,text:e.text}]:[]]}:e,e.messageId!=null){let t=this.state.messages.findIndex(t=>t.id===e.messageId);if(t===-1)throw Error(`message with id ${e.messageId} not found`);if(this.state.messages[t].role!==`user`)throw Error(`message with id ${e.messageId} is not a user message`);this.state.messages=this.state.messages.slice(0,t+1),this.state.replaceMessage(t,{...n,id:e.messageId,role:n.role??`user`,metadata:e.metadata})}else this.state.pushMessage({...n,id:n.id??this.generateId(),role:n.role??`user`,metadata:e.metadata});await this.makeRequest({trigger:`submit-message`,messageId:e.messageId,...t})},this.regenerate=async({messageId:e,...t}={})=>{let n=e==null?this.state.messages.length-1:this.state.messages.findIndex(t=>t.id===e);if(n===-1)throw Error(`message ${e} not found`);this.state.messages=this.state.messages.slice(0,this.messages[n].role===`assistant`?n:n+1),await this.makeRequest({trigger:`regenerate-message`,messageId:e,...t})},this.resumeStream=async(e={})=>{await this.makeRequest({trigger:`resume-stream`,...e})},this.clearError=()=>{this.status===`error`&&(this.state.error=void 0,this.setStatus({status:`ready`}))},this.addToolApprovalResponse=async({id:e,approved:t,reason:n,options:r})=>this.jobExecutor.run(async()=>{let i=this.state.messages,a=i[i.length-1],o=r=>G(r)&&r.state===`approval-requested`&&r.approval.id===e?{...r,state:`approval-responded`,approval:{...r.approval,id:e,approved:t,reason:n}}:r;this.state.replaceMessage(i.length-1,{...a,parts:a.parts.map(o)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(o)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...r})})}),this.addToolOutput=async({state:e=`output-available`,toolCallId:t,output:n,errorText:r,options:i})=>this.jobExecutor.run(async()=>{let a=this.state.messages,o=a[a.length-1],s=i=>G(i)&&i.toolCallId===t?{...i,state:e,output:n,errorText:r}:i;this.state.replaceMessage(a.length-1,{...o,parts:o.parts.map(s)}),this.activeResponse&&(this.activeResponse.state.message.parts=this.activeResponse.state.message.parts.map(s)),this.status!==`streaming`&&this.status!==`submitted`&&this.sendAutomaticallyWhen&&this.shouldSendAutomatically().then(e=>{e&&this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,...i})})}),this.addToolResult=this.addToolOutput,this.stop=async()=>{this.status!==`streaming`&&this.status!==`submitted`||this.activeResponse?.abortController&&this.activeResponse.abortController.abort()},this.id=t,this.transport=n,this.generateId=e,this.messageMetadataSchema=r,this.dataPartSchemas=i,this.state=a,this.onError=o,this.onToolCall=s,this.onFinish=c,this.onData=l,this.sendAutomaticallyWhen=u}get status(){return this.state.status}setStatus({status:e,error:t}){this.status!==e&&(this.state.status=e,this.state.error=t)}get error(){return this.state.error}get messages(){return this.state.messages}get lastMessage(){return this.state.messages[this.state.messages.length-1]}set messages(e){this.state.messages=e}async shouldSendAutomatically(){if(!this.sendAutomaticallyWhen)return!1;let e=this.sendAutomaticallyWhen({messages:this.state.messages});return e&&typeof e==`object`&&`then`in e?await e:e}async makeRequest({trigger:e,metadata:t,headers:n,body:r,messageId:i}){var a;let o;if(e===`resume-stream`)try{let e=await this.transport.reconnectToStream({chatId:this.id,metadata:t,headers:n,body:r});if(e==null)return;o=e}catch(e){this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e});return}this.setStatus({status:`submitted`,error:void 0});let s=this.lastMessage,c=!1,l=!1,u=!1,d;try{let a={state:$r({lastMessage:this.state.snapshot(s),messageId:this.generateId()}),abortController:new AbortController};d=a,a.abortController.signal.addEventListener(`abort`,()=>{c=!0}),this.activeResponse=a;let l;l=e===`resume-stream`?o:await this.transport.sendMessages({chatId:this.id,messages:this.state.messages,abortSignal:a.abortController.signal,metadata:t,headers:n,body:r,trigger:e,messageId:i}),await ti({stream:ei({stream:l,onToolCall:this.onToolCall,onData:this.onData,messageMetadataSchema:this.messageMetadataSchema,dataPartSchemas:this.dataPartSchemas,runUpdateMessageJob:e=>this.jobExecutor.run(()=>e({state:a.state,write:()=>{this.setStatus({status:`streaming`}),a.state.message.id===this.lastMessage?.id?this.state.replaceMessage(this.state.messages.length-1,a.state.message):this.state.pushMessage(a.state.message)}})),onError:e=>{throw e}}),onError:e=>{throw e}}),this.setStatus({status:`ready`})}catch(e){if(c||e.name===`AbortError`)return c=!0,this.setStatus({status:`ready`}),null;u=!0,e instanceof TypeError&&(e.message.toLowerCase().includes(`fetch`)||e.message.toLowerCase().includes(`network`))&&(l=!0),this.onError&&e instanceof Error&&this.onError(e),this.setStatus({status:`error`,error:e})}finally{try{d&&((a=this.onFinish)==null||a.call(this,{message:d.state.message,messages:this.state.messages,isAbort:c,isDisconnect:l,isError:u,finishReason:d.state.finishReason}))}catch(e){console.error(e)}this.activeResponse===d&&(this.activeResponse=void 0)}!u&&await this.shouldSendAutomatically()&&await this.makeRequest({trigger:`submit-message`,messageId:this.lastMessage?.id,metadata:t,headers:n,body:r})}};function si({messages:e}){let t=e[e.length-1];if(!t||t.role!==`assistant`)return!1;let n=t.parts.reduce((e,t,n)=>t.type===`step-start`?n:e,-1),r=t.parts.slice(n+1).filter(G).filter(e=>!e.providerExecuted);return r.length>0&&r.every(e=>e.state===`output-available`||e.state===`output-error`)}function ci(e){return new ai({api:be(`/`,`Chat/Messages/`),credentials:`include`,body:{orgId:e}})}var li=e(t(((e,t)=>{function n(e,t){if(typeof e!=`function`)throw TypeError(`Expected the first argument to be a \`function\`, got \`${typeof e}\`.`);let n,r=0;return function(...i){clearTimeout(n);let a=Date.now(),o=t-(a-r);o<=0?(r=a,e.apply(this,i)):n=setTimeout(()=>{r=Date.now(),e.apply(this,i)},o)}}t.exports=n}))(),1),ui=(e,t,n)=>{if(!t.has(e))throw TypeError(`Cannot `+n)},K=(e,t,n)=>(ui(e,t,`read from private field`),n?n.call(e):t.get(e)),q=(e,t,n)=>{if(t.has(e))throw TypeError(`Cannot add the same private member more than once`);t instanceof WeakSet?t.add(e):t.set(e,n)},J=(e,t,n,r)=>(ui(e,t,`write to private field`),r?r.call(e,n):t.set(e,n),n);function di(e,t){return t==null?e:(0,li.default)(e,t)}var Y,fi,pi,X,mi,Z,Q,hi,gi,_i=class{constructor(e=[]){q(this,Y,void 0),q(this,fi,`ready`),q(this,pi,void 0),q(this,X,new Set),q(this,mi,new Set),q(this,Z,new Set),this.pushMessage=e=>{J(this,Y,K(this,Y).concat(e)),K(this,Q).call(this)},this.popMessage=()=>{J(this,Y,K(this,Y).slice(0,-1)),K(this,Q).call(this)},this.replaceMessage=(e,t)=>{J(this,Y,[...K(this,Y).slice(0,e),this.snapshot(t),...K(this,Y).slice(e+1)]),K(this,Q).call(this)},this.snapshot=e=>structuredClone(e),this[`~registerMessagesCallback`]=(e,t)=>{let n=t?di(e,t):e;return K(this,X).add(n),()=>{K(this,X).delete(n)}},this[`~registerStatusCallback`]=e=>(K(this,mi).add(e),()=>{K(this,mi).delete(e)}),this[`~registerErrorCallback`]=e=>(K(this,Z).add(e),()=>{K(this,Z).delete(e)}),q(this,Q,()=>{K(this,X).forEach(e=>e())}),q(this,hi,()=>{K(this,mi).forEach(e=>e())}),q(this,gi,()=>{K(this,Z).forEach(e=>e())}),J(this,Y,e)}get status(){return K(this,fi)}set status(e){J(this,fi,e),K(this,hi).call(this)}get error(){return K(this,pi)}set error(e){J(this,pi,e),K(this,gi).call(this)}get messages(){return K(this,Y)}set messages(e){J(this,Y,[...e]),K(this,Q).call(this)}};Y=new WeakMap,fi=new WeakMap,pi=new WeakMap,X=new WeakMap,mi=new WeakMap,Z=new WeakMap,Q=new WeakMap,hi=new WeakMap,gi=new WeakMap;var $,vi=class extends oi{constructor({messages:e,...t}){let n=new _i(e);super({...t,state:n}),q(this,$,void 0),this[`~registerMessagesCallback`]=(e,t)=>K(this,$)[`~registerMessagesCallback`](e,t),this[`~registerStatusCallback`]=e=>K(this,$)[`~registerStatusCallback`](e),this[`~registerErrorCallback`]=e=>K(this,$)[`~registerErrorCallback`](e),J(this,$,n)}};$=new WeakMap;function yi({throttle:e,experimental_throttle:t,resume:n=!1,...r}={}){let i=e??t,a=(0,T.useRef)({});`chat`in r||(a.current={onToolCall:r.onToolCall,onData:r.onData,onFinish:r.onFinish,onError:r.onError,sendAutomaticallyWhen:r.sendAutomaticallyWhen,transport:r.transport});let o,s=()=>a.current.transport??(o??=new ai),c={...r,transport:{sendMessages:e=>s().sendMessages(e),reconnectToStream:e=>s().reconnectToStream(e)},onToolCall:e=>{var t;return(t=a.current).onToolCall?.call(t,e)},onData:e=>{var t;return(t=a.current).onData?.call(t,e)},onFinish:e=>{var t;return(t=a.current).onFinish?.call(t,e)},onError:e=>{var t;return(t=a.current).onError?.call(t,e)},sendAutomaticallyWhen:e=>{var t;return(t=a.current).sendAutomaticallyWhen?.call(t,e)??!1}},l=(0,T.useRef)(`chat`in r?r.chat:new vi(c));(`chat`in r&&r.chat!==l.current||`id`in r&&r.id!=null&&l.current.id!==r.id)&&(l.current=`chat`in r?r.chat:new vi(c));let u=(0,T.useSyncExternalStore)((0,T.useCallback)(e=>l.current[`~registerMessagesCallback`](e,i),[i,l.current.id]),()=>l.current.messages,()=>l.current.messages),d=(0,T.useSyncExternalStore)(l.current[`~registerStatusCallback`],()=>l.current.status,()=>l.current.status),f=(0,T.useSyncExternalStore)(l.current[`~registerErrorCallback`],()=>l.current.error,()=>l.current.error),p=(0,T.useCallback)(e=>{typeof e==`function`&&(e=e(l.current.messages)),l.current.messages=e},[l]);return(0,T.useEffect)(()=>{n&&l.current.resumeStream()},[n,l]),{id:l.current.id,messages:u,setMessages:p,sendMessage:l.current.sendMessage,regenerate:l.current.regenerate,clearError:l.current.clearError,stop:l.current.stop,error:f,resumeStream:l.current.resumeStream,status:d,addToolResult:l.current.addToolOutput,addToolOutput:l.current.addToolOutput,addToolApprovalResponse:l.current.addToolApprovalResponse}}function bi({input:e,setInput:t,onSubmit:n,disabled:r,autoFocus:i}){let a=(0,T.useRef)(null);return(0,T.useEffect)(()=>{i&&!r&&a.current?.focus()},[i,r]),(0,E.jsxs)(`form`,{onSubmit:n,className:`input-area`,children:[(0,E.jsx)(`input`,{ref:a,value:e,onChange:e=>t(e.target.value),placeholder:`Type a message...`,disabled:r}),(0,E.jsx)(`button`,{type:`submit`,disabled:r||!e.trim(),children:(0,E.jsx)(dt,{size:18})})]})}function xi(){return(0,E.jsxs)(`div`,{className:`loading-state`,children:[(0,E.jsx)(We,{className:`animate-spin`,size:24}),(0,E.jsx)(`p`,{children:`Loading conversation...`})]})}var Si={name:`collectFeedback`,description:`Collects feedback from the user by fetching a link to a pre-populated GitHub Discussion. Use this if the user lets us know we did something well, or if the user seems frustrated, or wants to report a bug.`,inputSchema:v({feedbackSummary:o().describe(`A brief summary of the feedback, used as the discussion title.`),feedbackDetails:o().describe(`Detailed feedback from the user or agent observation.`),recap:o().describe(`A sanitized recap of what the agent and user did together and if it was successful. No sensitive information.`)})};async function Ci({input:{feedbackSummary:e,feedbackDetails:t,recap:n}}){let r=e,i=`${t}\n\n${n}`;return{success:!0,url:`https://github.com/HarperFast/harper-agent/discussions/new?category=usage-feedback&title=${encodeURIComponent(r)}&body=${encodeURIComponent(i)}`,message:`Feedback URL created! Ask the user to open it in their browser, and they will be brought to a form to approve the details of the feedback.`}}var wi={...Si,icon:ut,execute:Ci},Ti={name:`createApp`,description:`Create a new Harper app with the specified name and template type.`,inputSchema:v({name:o().trim(),type:m(xe)})};async function Ei({input:{name:e,type:t},instanceClientParams:n,baseURL:r}){let i=Ne(e),a=ye(he,`id`,t);if(!a)return{success:!1,message:`Error: Invalid template type, ${t}, please choose from: ${he.map(e=>e.id).join(`, `)}`};let o=C.loading(`Creating from template...`,{description:`This may take a bit.`,duration:3e5});try{await we({...n,project:i,template:a.npm||a.githubUrl})}catch(e){return{success:!1,message:`Error: ${e}`}}Fe(`ReloadApplicationRootEntries`,!0),C.loading(`Created successfully!`,{description:`${i} created! Restarting the HTTP service...`,id:o,duration:3e5});try{await Be({...n,operation:`restart_service`,replicated:n.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return C.success(`Created successfully!`,{description:`${i} created!`,id:o,duration:5e3}),{success:!0,message:`App "${i}" created successfully.`,webURL:r}}var Di={...Ti,icon:et,execute:Ei,requiresApproval:!0},Oi={name:`deleteTableRecords`,description:`Deletes records in a particular table in a particular database on the server by their primary keys.`,inputSchema:v({database:o().trim(),table:o().trim(),primaryKeys:s(o())})};async function ki({input:{database:e,table:t,primaryKeys:n},instanceClientParams:r,params:i}){try{let a=await Ge({...r,databaseName:e,tableName:t,hashValues:n}),{databaseName:o,tableName:s}=i;return await Te.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ai={...Oi,icon:it,execute:ki,requiresApproval:!0},ji={name:`dropComponentFile`,description:`Drops a component file by its full path (which was returned by getComponents)`,inputSchema:v({path:o().trim()})};async function Mi({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await me({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ni={...ji,icon:Le,execute:Mi,requiresApproval:!0},Pi={name:`getAnalytics`,description:`Retrieves analytics metrics for the server, such as CPU usage or database operations (reads, writes, messages).`,inputSchema:v({metricName:o().describe(`The name of the metric to retrieve.`),startTime:i().describe(`The start of the time range for the metric, in milliseconds since the Unix epoch.`),endTime:i().describe(`The end of the time range for the metric, in milliseconds since the Unix epoch.`)})};async function Fi({input:e,instanceClientParams:t}){try{let{metricName:n,startTime:r,endTime:i}=e;return{success:!0,data:await rt({metric:n,startTime:r,endTime:i,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var Ii={...Pi,icon:ot,execute:Fi},Li={name:`getComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:v({path:o().trim()})};async function Ri({input:{path:e},instanceClientParams:t}){try{let n=e.split(`/`),r=n.shift(),i=n.join(`/`);return{success:!0,data:await Xe({...t,file:i,project:r})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var zi={...Li,icon:ge,execute:Ri},Bi={name:`getComponents`,description:`Retrieves a tree of all the component (files and folders) names and sizes stored on the server.`,inputSchema:v({})};async function Vi({instanceClientParams:e}){try{let{rootEntries:t}=Se((await tt(e)).entries);return{success:!0,items:ve(t).items}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Hi={...Bi,icon:_e,execute:Vi},Ui={name:`getDescribeAll`,description:`Retrieves a map of the names of databases and their tables stored on the server.`,inputSchema:v({})};async function Wi({instanceClientParams:e}){try{return{success:!0,map:await He(e)}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Gi={...Ui,icon:$e,execute:Wi},Ki={name:`getDescribeTable`,description:`Returns the schema metadata describing a particular table in a particular database on the server.`,inputSchema:v({database:o().trim(),table:o().trim()})};async function qi({input:{database:e,table:t},instanceClientParams:n}){try{return{success:!0,data:await Ie({...n,databaseName:e,tableName:t})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var Ji={...Ki,icon:Qe,execute:qi},Yi={name:`getUserContext`,description:`Retrieves the context of what the user is looking at on their screen, such as the current page, the file they are viewing, the database and table visible to them, that sort of thing.`,inputSchema:v({})};async function Xi({instanceClientParams:e,params:t}){let n=Ke();if(n.includes(`/databases`)){let{databaseName:e,tableName:n}=t;return{success:!0,description:`viewing the database`,data:{databaseName:e,tableName:n}}}if(n.endsWith(`/apis`))return{success:!0,description:`viewing the APIs`};if(n.endsWith(`/status`))return{success:!0,description:`viewing the status graphs`};if(n.endsWith(`/logs`))return{success:!0,description:`viewing the logs`};if(n.includes(`/config/`))return{success:!0,description:`viewing the configuration pages`};let r=Pe(`FileFocused/${e.entityId}`,void 0),i=Pe(`FolderOpened/${e.entityId}`,[]),a=Pe(`FileSelected/${e.entityId}`,[]);return r?{success:!0,description:`editing application files`,data:{openedPath:r,expandedItems:i,selectedItems:a}}:{success:!0,description:n}}var Zi={...Yi,icon:Me,execute:Xi},Qi={name:`insertTableRecords`,description:`Inserts one or more records into a particular table in a particular database on the server.`,inputSchema:v({database:o().trim(),table:o().trim(),records:s(h())})};async function $i({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await ze({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Te.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ea={...Qi,icon:it,execute:$i,requiresApproval:!0},ta={name:`listAnalyticsMetrics`,description:`Lists the available analytics metric names available for calling getAnalytics upon.`,inputSchema:v({metricTypes:m([`builtin`,`custom`]),customWindowMS:i().optional().describe(`Default to one week time window for finding custom metrics.`)})};async function na({metricTypes:e,customWindowMS:t,instanceParams:n}){let{data:r}=await n.instanceClient.post(`/`,{operation:`list_analytics_metrics`,metricTypes:e,customWindowMS:t});return r}async function ra({input:e,instanceClientParams:t}){try{let{metricTypes:n,customWindowMS:r}=e;return{success:!0,metricNames:await na({metricTypes:n,customWindowMS:r,instanceParams:t})}}catch(e){return{success:!1,message:`Error retrieving analytics: ${e}`}}}var ia={...ta,icon:ot,execute:ra},aa=[`adding-tables-with-schemas`,`automatic-apis`,`caching`,`checking-authentication`,`creating-a-fabric-account-and-cluster`,`creating-harper-apps`,`custom-resources`,`defining-relationships`,`deploying-to-harper-fabric`,`extending-tables`,`handling-binary-data`,`load-env`,`logging`,`programmatic-table-requests`,`querying-rest-apis`,`real-time-apps`,`schema-design-tooling`,`serving-web-content`,`typescript-type-stripping`,`using-blob-datatype`,`v5-upgrade`,`vector-indexing`],oa={"adding-tables-with-schemas":"---\nname: adding-tables-with-schemas\ndescription: Guidelines for adding tables to a Harper database using GraphQL schemas.\nmetadata:\n mode: synthesized\n---\n\n# Adding Tables with Schemas\n\nInstructions for the agent to follow when adding tables to a Harper database.\n\n## When to Use\n\nUse this skill when you need to define new data structures or modify existing ones in a Harper database.\n\n## How It Works\n\n1. **Create Dedicated Schema Files**: Prefer having a dedicated schema `.graphql` file for each table. Check the `config.yaml` file under `graphqlSchema.files` to see how it's configured. It typically accepts wildcards (e.g., `schemas/*.graphql`), but may be configured to point at a single file.\n2. **Use Directives**: All available directives for defining your schema are defined in `node_modules/harper/schema.graphql`. Common directives include `@table`, `@export`, `@primaryKey`, `@indexed`, and `@relationship`.\n3. **Define Relationships**: Link tables together using the `@relationship` directive. For more details, see the [Defining Relationships](defining-relationships.md) skill.\n4. **Enable Automatic APIs**: If you add `@table @export` to a schema type, Harper automatically sets up REST and WebSocket APIs for basic CRUD operations against that table. **Important**: REST endpoints also require `rest: true` in `config.yaml` — without it, `@export`ed tables will not respond to HTTP requests. For a detailed list of available endpoints and how to use them, see the [Automatic REST APIs](automatic-apis.md) skill.\n - `GET /{TableName}`: Describes the schema itself.\n - `GET /{TableName}/`: Lists all records (supports filtering, sorting, and pagination via query parameters). See the [Querying REST APIs](querying-rest-apis.md) skill for details.\n - `GET /{TableName}/{id}`: Retrieves a single record by its ID.\n - `POST /{TableName}/`: Creates a new record.\n - `PUT /{TableName}/{id}`: Updates an existing record.\n - `PATCH /{TableName}/{id}`: Performs a partial update on a record.\n - `DELETE /{TableName}/`: Deletes all records or filtered records.\n - `DELETE /{TableName}/{id}`: Deletes a single record by its ID.\n5. **Consider Table Extensions**: If you are going to [extend the table](./extending-tables.md) in your resources, then do not `@export` the table from the schema.\n\n## Examples\n\nIn a hypothetical `schemas/ExamplePerson.graphql`:\n\n```graphql\ntype ExamplePerson @table @export {\n id: ID @primaryKey\n name: String\n tag: String @indexed\n}\n```\n","automatic-apis":`---
17
17
  name: automatic-apis
18
18
  description: How to use Harper's automatically generated REST and WebSocket APIs.
19
19
  metadata:
@@ -1943,7 +1943,7 @@ jsResource:
1943
1943
  - No build step or transpiler is required — Harper runs \`.ts\` files directly.
1944
1944
  - Type imports (e.g., \`import { type RequestTargetOrId }\`) from the \`harper\` package work as usual.
1945
1945
  - Unsupported TypeScript features include: enums with runtime values, namespaces with runtime semantics, and anything requiring code transformation beyond simple type stripping.
1946
- `,"using-blob-datatype":"---\nname: using-blob-datatype\ndescription: How to use the Blob data type for efficient binary storage in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Blob Type\n - reference/v5/database/api.md#Streaming\n - reference/v5/database/api.md#`BlobOptions`\n - reference/v5/database/api.md#Blob Coercion\n sourceCommit: f37a8c4021e20d5c74c1d339a6b6c8c196b5603e\n inputHash: 92e03eb0b830f335\n---\n\n# Using the Blob Data Type\n\nInstructions for the agent to follow when storing and retrieving large binary content using the `Blob` data type in Harper.\n\n## When to Use\n\nApply this rule when a schema field needs to store large binary content such as images, video, audio, or large HTML — typically content larger than 20KB. Use `Blob` instead of `Bytes` when streaming support and out-of-record storage are required. See [handling-binary-data.md](handling-binary-data.md) for broader binary data guidance.\n\n## How It Works\n\n1. **Declare a `Blob` field in your schema**: Add a field typed as `Blob` to your `@table` type.\n\n ```graphql\n type MyTable @table {\n id: Any! @primaryKey\n data: Blob\n }\n ```\n\n2. **Create and store a blob with `createBlob()`**: Pass a buffer or stream to `createBlob()`, then `put` the record.\n\n ```javascript\n let blob = createBlob(largeBuffer);\n await MyTable.put({ id: 'my-record', data: blob });\n ```\n\n3. **Retrieve blob data using standard Web API methods**: The `Blob` type implements the Web API `Blob` interface. Use `.bytes()`, `.text()`, `.arrayBuffer()`, `.stream()`, or `.slice()` as needed.\n\n ```javascript\n let record = await MyTable.get('my-record');\n let buffer = await record.data.bytes(); // ArrayBuffer\n let text = await record.data.text(); // string\n let stream = record.data.stream(); // ReadableStream\n ```\n\n4. **Use `saveBeforeCommit` when full write must precede commit**: By default, `Blob` is not ACID-compliant — a record can reference a blob before it is fully written. Set `saveBeforeCommit: true` to block the transaction until the blob is fully saved.\n\n ```javascript\n let blob = createBlob(stream, { saveBeforeCommit: true });\n await MyTable.put({ id: 'my-record', data: blob });\n // put() resolves only after blob is fully written and record is committed\n ```\n\n5. **Register an error handler when returning a blob via REST**: Interrupted streams must be handled explicitly.\n\n ```javascript\n export class MyEndpoint extends MyTable {\n static async get(target) {\n const record = super.get(target);\n let blob = record.data;\n blob.on('error', () => {\n MyTable.invalidate(target);\n });\n return { status: 200, headers: {}, body: blob };\n }\n }\n ```\n\n6. **Rely on automatic coercion where applicable**: When a field is typed as `Blob` in the schema, any string or buffer assigned via `put`, `patch`, or `publish` is automatically coerced to a `Blob` — no manual `createBlob()` call is needed in those cases.\n\n### `BlobOptions` reference\n\nPass an options object as the second argument to `createBlob()`.\n\n| Option | Type | Default | Description |\n| ------------------ | --------- | ----------- | ------------------------------------------------------------------------------------------------------------------------ |\n| `type` | `string` | `undefined` | MIME type to associate with the blob (e.g., `image/jpeg`). Readable via `blob.type` and used when serving HTTP. |\n| `size` | `number` | `undefined` | Size of the data in bytes, if known ahead of time. Otherwise inferred from a buffer or determined as a stream completes. |\n| `saveBeforeCommit` | `boolean` | `false` | Wait until the blob is fully written before the transaction commits. |\n| `compress` | `boolean` | `false` | Compress the stored data with deflate. |\n| `flush` | `boolean` | `false` | Flush the file to disk after writing, before the `createBlob` promise chain resolves. |\n\n## Examples\n\n**Store an image with a MIME type:**\n\n```javascript\nlet blob = createBlob(imageBuffer, { type: 'image/jpeg' });\nawait Photo.put({ id, data: blob });\n```\n\n**Stream a blob in as it streams out (low-latency passthrough):**\n\n```javascript\nlet blob = createBlob(incomingStream);\n// blob exists, but data is still streaming to storage\nawait MyTable.put({ id: 'my-record', data: blob });\n\nlet record = await MyTable.get('my-record');\n// blob data is accessible as it arrives\nlet outgoingStream = record.data.stream();\n```\n\n**Guarantee full write before commit using `saveBeforeCommit`:**\n\n```javascript\nlet blob = createBlob(stream, { saveBeforeCommit: true });\nawait MyTable.put({ id: 'my-record', data: blob });\n```\n\n## Notes\n\n- `Blob` stores data separately from the record. If you need the binary data to be a true, ACID-committed part of the record, use a `Bytes` field instead.\n- All standard Web API `Blob` methods — `.text()`, `.arrayBuffer()`, `.stream()`, `.slice()`, and `.bytes()` — are available on retrieved blob fields.\n- Without `saveBeforeCommit: true`, blobs are **not** ACID-compliant by default; a record can reference a blob before it is fully written to storage.\n","v5-upgrade":"---\nname: v5-upgrade\ndescription: >-\n Breaking changes and recommended updates when migrating a Harper application\n to v5.\nmetadata:\n mode: generate\n sources:\n - release-notes/v5-lincoln/v5-migration.md\n sourceCommit: de2aaf1c759a7ff5b93e862ba704153e2a392fcb\n inputHash: 80314689f3a7f42e\n---\n\n# Upgrading a Harper Application to v5\n\nInstructions for the agent to follow when migrating an existing Harper application to version 5, addressing the breaking changes and adopting the recommended patterns.\n\n## When to Use\n\nApply this rule when upgrading a Harper application from v4.x (or earlier) to v5, or when code written against older APIs behaves differently after a v5 upgrade — for example a record that can no longer be mutated, a query that returns stale data, or a `spawn` call that now throws. Harper v5 introduces breaking changes; applications built on documented APIs need the updates below, while code relying on undocumented behavior or timing may need broader review.\n\n## How It Works\n\n1. **Adopt the `harper` package name**: HarperDB is now Harper, and the package was renamed. Install the open source edition with `npm i -g harper` and the pro edition with `npm i -g @harperfast/harper-pro`. Update application imports from `harperdb` to `harper`:\n\n ```javascript\n import { tables } from 'harper';\n ```\n\n2. **Opt in to install scripts when required**: Harper now installs packages with `--ignore-scripts` to guard against accidental script execution, a common security risk. If an application genuinely needs install scripts to run (for example to build native binaries), pass the `allowInstallScripts` option when deploying.\n\n3. **Update `Table.get` return-value handling**: `Table.get` now returns a plain, frozen record object rather than an instance of the table class, so instance methods are no longer available on the result. The commonly used `wasLoadedFromSource()` method is gone; cache-vs-origin information now lives on the request `target` as `target.loadedFromSource`. Pass a `RequestTarget` to `Table.get` and read the flag from it. Because the record is frozen, create a copy instead of mutating it in place.\n\n4. **Account for automatic transaction context**: With RocksDB, transactions are fully supported by the storage engine, and Harper v5 uses asynchronous context tracking to carry the current transaction across calls automatically. A nested `Table.get` now reads within the current transaction's snapshot, so it will not observe newly written data until you commit. Access the context through `getContext()` and either commit the current transaction (`getContext().transaction.commit()`) or run the read inside a fresh `transaction(...)` to see the latest data. This matters most for code executing outside the context of a Harper request.\n\n5. **Register spawnable commands**: Spawning processes is now tightly controlled. `spawn`, `exec`, and `execFile` may only run executables listed in the `applications.allowedSpawnCommands` configuration, and each call must pass a `name` in its `options` so that only a single named process is started across Harper's multiple threads. Use a distinct `name` when you deliberately need a separate process.\n\n6. **Return Response-like objects to set headers**: If a REST method returns an object with a `headers` property, Harper uses it as the response headers.\n\n7. **Replace `blob.save()`**: The `blob.save()` method has been removed. Pass the `saveBeforeCommit` flag in the options to the `Blob` constructor instead.\n\n8. **Configure the VM module loader**: v5 loads application modules through Node.js's VM module API, giving each application its own module cache and an application-scoped `harper` module. All of this is controlled by the `applications` section of `harperdb-config.yaml`:\n - `moduleLoader` — `vm-current-context` (default), `vm`, `native`, or `compartment`. The default shares intrinsics with Harper for best compatibility; choose `vm` only if you need per-application intrinsics, and `native` to disable the VM loader entirely (restores pre-v5 loading, but per-app `logger`/`config` context is unavailable).\n - `lockdown` — `freeze-after-load` (default), `freeze`, `ses`, or `none`. Freezing intrinsics prevents prototype-pollution attacks; set `lockdown: none` only as a temporary workaround if a dependency mutates built-in prototypes.\n - `allowedDirectory` — `app` (default) restricts module loading to the application's own directory tree; set `any` if the app must load files from outside it in production.\n - `allowedBuiltinModules` — an optional allowlist restricting which Node.js built-ins the application may import (all are allowed if omitted).\n - `dependencyLoader` — `auto` (default), `app`, or `native`, controlling how npm dependencies are loaded through or around the VM loader.\n\n## Examples\n\n**Updating `Table.get` and its cache check:**\n\n```javascript\n// Old (v4.x)\nconst record = await Table.get(id);\nif (record.wasLoadedFromSource()) {\n // loaded from origin, not cache\n}\n\n// New (v5)\nconst target = new RequestTarget(); // passed in when overriding `get`\ntarget.id = id;\nconst record = await Table.get(target);\nif (target.loadedFromSource) {\n // loaded from origin, not cache\n}\n```\n\n**Committing the transaction to read fresh data:**\n\n```javascript\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { getContext, transaction } from 'harper';\n\nclass MyResource {\n static async get(target) {\n // The current transaction is a consistent snapshot; commit it to see updates.\n await getContext().transaction.commit();\n while ((await transaction(() => Table.get(target))).status !== 'ready') {\n delay(100);\n }\n return Table.get(target);\n }\n}\n```\n\n**Module loader and security configuration in `harperdb-config.yaml`:**\n\n```yaml\napplications:\n lockdown: freeze-after-load # default\n moduleLoader: vm-current-context # vm-current-context (default) | vm | native | compartment\n dependencyLoader: auto # auto (default) | app | native\n allowedDirectory: app # app (default) | any\n allowedSpawnCommands:\n - npm\n - node\n # allowedBuiltinModules: [] # if omitted, all Node.js built-ins are allowed\n```\n\n## Recommended Changes\n\nBeyond the required fixes above, Harper v5 encourages these patterns for new and migrated code:\n\n- Implement endpoints with `static` methods on Resources/Tables, reading request information from the request `target` argument (or from `getContext()`).\n- Rely on automatic context propagation rather than threading context through every call manually; access it via `getContext()` exported from `harper`.\n- Access Harper functions and APIs through the `harper` package rather than through global variables.\n","vector-indexing":'---\nname: vector-indexing\ndescription: How to enable and query vector indexes for similarity search in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Vector Indexing\n sourceCommit: 4fe4c9c95e0974eaa77032f6f10e36fbd8ec64ac\n inputHash: d90b1b74597d08a6\n---\n\n# Vector Indexing\n\nInstructions for the agent to enable HNSW vector indexes on table fields and query them for similarity search in Harper.\n\n## When to Use\n\nApply this rule when adding a vector similarity search capability to a Harper table — for example, storing text embeddings and querying for nearest neighbors, filtering by distance threshold, or tuning index construction and search parameters. Use it alongside [adding-tables-with-schemas.md](adding-tables-with-schemas.md) when defining the schema that hosts the vector field.\n\n## How It Works\n\n1. **Declare the vector index on a field**: Add `@indexed(type: "HNSW")` to a `[Float]` field inside a `@table` type. This creates an HNSW (Hierarchical Navigable Small World) index for approximate nearest-neighbor search.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW")\n }\n ```\n\n2. **Query by nearest neighbors using `sort`**: Call `.search()` with a `sort` descriptor that specifies the indexed `attribute` and a `target` vector. Use `limit` to cap results.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n3. **Combine with filter conditions**: Add a `conditions` array alongside `sort` to pre-filter records before ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: [{ attribute: \'price\', comparator: \'lt\', value: 50 }],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n4. **Filter by distance threshold**: To return only records within a similarity cutoff (without ranking), place `target` directly on the condition alongside `comparator` and `value`. This bounds result quality rather than ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n });\n ```\n\n5. **Include computed distance in results**: Use the special `$distance` field in `select` to return the distance from the target vector. Available in both `sort`-based and threshold-based queries.\n\n ```javascript\n let results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n6. **Tune per-query search options**: Pass `distance` and `ef` directly on the `sort` descriptor to override index defaults for a single query.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector, distance: \'dotProduct\', ef: 200 },\n limit: 5,\n });\n ```\n\n - `distance` — overrides the distance function for this query: `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n - `ef` — overrides the search exploration budget. Higher values improve recall at the cost of latency.\n\n7. **Configure HNSW index parameters**: Pass parameters directly in the `@indexed` directive. Structural parameters (`distance`, `M`, `efConstruction`, `quantization`) trigger an index rebuild when changed; `efConstructionSearch` does not.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n }\n ```\n\n8. **Enable vector quantization**: Use `quantization: "int8"` to store vectors as 8-bit integers, reducing index size and memory usage. Harper re-ranks nearest-neighbor `sort` results against full-precision vectors automatically.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW", quantization: "int8")\n }\n ```\n\n## Examples\n\nFull schema with custom HNSW parameters and a nearest-neighbor query with distance output:\n\n```graphql\ntype Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n}\n```\n\n```javascript\n// Nearest-neighbor search with distance scores\nlet results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n});\n\n// Distance-threshold query (no ranking)\nlet closeMatches = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n});\n```\n\n## Notes\n\n### HNSW Parameters\n\n| Parameter | Default | Description |\n| ---------------------- | ----------------- | ------------------------------------------------------------------------------------------------------ |\n| `distance` | `"cosine"` | Distance function: `"cosine"`, `"euclidean"`, or `"dotProduct"` |\n| `efConstruction` | `100` | Max nodes explored during index construction. Higher = better recall, lower = better performance |\n| `M` | `16` | Preferred connections per graph layer. Higher = more space, better recall for high-dimensional data |\n| `optimizeRouting` | `0.5` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |\n| `mL` | computed from `M` | Normalization factor for level generation |\n| `efConstructionSearch` | auto-scaled | Max nodes explored during search. When unset, auto-scales with index size; setting it fixes the budget |\n| `quantization` | — | `"int8"` stores vectors quantized to int8 |\n\n- The `distance` option on a per-query `sort` descriptor accepts `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n- When no `ef` is passed and `efConstructionSearch` (or `efConstruction`) is not explicitly set on the index, the search budget auto-scales with index size.\n- `efConstruction` seeds the initial value of `efConstructionSearch`; setting either one fixes the search budget.\n- The correct parameter name is `efConstructionSearch` (not `efSearchConstruction`).\n- `$distance` is available in both `sort`-based ranking and `conditions`-based threshold queries.\n- For `quantization: "int8"`, distance-threshold (`lt`/`le`) queries filter on approximate distance; `sort` queries re-rank against full-precision vectors.\n'},sa={name:`readHarperSkill`,description:`Returns documentation for a Harper skill or best practice. Skills provide guidance on developing Harper applications.`,inputSchema:v({skill:m(aa)})};async function ca({input:{skill:e}}){return{success:!!oa[e],message:oa[e]||`No skill found with the name ${e}`}}var la={...sa,icon:at,execute:ca},ua={name:`readLogs`,description:`Returns the matching logs from the server.`,inputSchema:v({log_name:m([`hdb.log`,`system.log`]).default(`hdb.log`),limit:o().or(a()).optional(),level:m([`notify`,`error`,`warn`,`info`,`debug`,`trace`,`undefined`]).or(a()).optional(),from:o().or(a()).optional(),until:o().or(a()).optional()})};async function da({input:e,instanceClientParams:t}){try{return{success:!0,data:await Xe({...t,logFilters:e,replicated:t.entityType===`cluster`})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var fa={...ua,icon:lt,execute:da},pa={name:`readTableRecords`,description:`Retrieves some or all table records from a database on the server.`,inputSchema:v({database:o().trim(),table:o().trim(),pageIndex:i().default(0),pageSize:i().default(10),primaryKey:o(),conditions:s(v({search_attribute:o(),search_type:m([`between`,`eq`,`equals`,`greater_than`,`greater_than_equal`,`less_than`,`less_than_equal`,`ne`,`not_equal`,`starts_with`]),search_value:h()})),sort:v({attribute:o(),descending:d()})})};async function ma({input:{database:e,table:t,conditions:n,primaryKey:r,...i},instanceClientParams:a}){try{if(!n.length){let{data:n}=await qe({...a,databaseName:e,tableName:t,onlyIfCached:!0,searchAttribute:r,...i});return{success:!0,data:n}}let{data:o}=await ze({...a,databaseName:e,tableName:t,onlyIfCached:!0,conditions:n,...i});return{success:!0,data:o}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ha={...pa,icon:Pe,execute:ma},ga={name:`restartHTTPService`,description:`Restarts the HTTP service on the server to allow schema and resource changes to be applied.`,inputSchema:v({})};async function _a({instanceClientParams:e,baseURL:t}){let n=C.loading(`Restarting HTTP service...`,{description:`This may take a bit.`,duration:3e5});try{await Ve({...e,operation:`restart_service`,replicated:e.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return C.success(`Done!`,{description:`HTTP Service restarted!`,id:n,duration:5e3}),{success:!0,message:`HTTP Service restarted!`,webURL:t}}var va={...ga,icon:Re,execute:_a,requiresApproval:!0},ya={name:`setComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:v({path:o().trim(),payload:o(),encoding:m([`utf8`,`ASCII`,`binary`,`hex`,`base64`,`utf16le`,`latin1`,`ucs2`])})};async function ba({input:{path:e,encoding:t,payload:n},instanceClientParams:r}){try{let i=e.split(`/`),a=i.shift(),o=i.join(`/`),s=await Se({...r,file:o,project:a,payload:n,encoding:t});return await we.invalidateQueries({queryKey:[r.entityId,`get_component_file`,a,o]}),Ie(`ReloadApplicationRootEntries`,!0),{success:!0,data:s}}catch(e){return{success:!1,message:`Error: ${e}`}}}var xa={...ya,icon:ct,execute:ba,requiresApproval:!0},Sa={name:`updateTableRecords`,description:`Updates records in a particular table in a particular database on the server.`,inputSchema:v({database:o().trim(),table:o().trim(),records:s(h())})};async function Ca({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await $e({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await we.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var wa={readHarperSkill:la,createApp:Di,readLogs:fa,getAnalytics:Ii,listAnalyticsMetrics:ia,restartHTTPService:va,collectFeedback:wi,getUserContext:Zi,getComponentFile:zi,getComponents:Hi,setComponentFile:xa,dropComponentFile:Ni,getDescribeAll:Gi,getDescribeTable:Ji,insertTableRecords:ea,readTableRecords:ha,updateTableRecords:{...Sa,icon:it,execute:Ca,requiresApproval:!0},deleteTableRecords:Ai};function Ta(e){return wa[e]}function Ea(e){return e.state===`input-available`&&!!Ta(Qr(e))?.requiresApproval}function Da(e){let t=[];for(let[n,r]of(e??[]).entries()){if(G(r)){if(Ea(r)){t.push({kind:`part`,part:r,index:n});continue}let e=t.at(-1);e?.kind===`tool-group`?e.parts.push(r):t.push({kind:`tool-group`,parts:[r],index:n});continue}Jr(r)&&r.text.length>0&&t.push({kind:`part`,part:r,index:n})}return t}function Oa({part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i}){let[a,o]=(0,T.useState)(!1),[s,c]=(0,T.useState)(!1),l=Qr(e),u=Ta(l),d=u?.icon||Ge,f=u?.requiresApproval,p=(0,T.useMemo)(()=>!e.input||typeof e.input==`object`&&Object.keys(e.input).length===0,[e.input]),m=(0,T.useMemo)(()=>{let t=JSON.stringify(e.input,null,` `);return{json:t,lines:t?t.split(`
1946
+ `,"using-blob-datatype":"---\nname: using-blob-datatype\ndescription: How to use the Blob data type for efficient binary storage in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Blob Type\n - reference/v5/database/api.md#Streaming\n - reference/v5/database/api.md#`BlobOptions`\n - reference/v5/database/api.md#Blob Coercion\n sourceCommit: f37a8c4021e20d5c74c1d339a6b6c8c196b5603e\n inputHash: 92e03eb0b830f335\n---\n\n# Using the Blob Data Type\n\nInstructions for the agent to follow when storing and retrieving large binary content using the `Blob` data type in Harper.\n\n## When to Use\n\nApply this rule when a schema field needs to store large binary content such as images, video, audio, or large HTML — typically content larger than 20KB. Use `Blob` instead of `Bytes` when streaming support and out-of-record storage are required. See [handling-binary-data.md](handling-binary-data.md) for broader binary data guidance.\n\n## How It Works\n\n1. **Declare a `Blob` field in your schema**: Add a field typed as `Blob` to your `@table` type.\n\n ```graphql\n type MyTable @table {\n id: Any! @primaryKey\n data: Blob\n }\n ```\n\n2. **Create and store a blob with `createBlob()`**: Pass a buffer or stream to `createBlob()`, then `put` the record.\n\n ```javascript\n let blob = createBlob(largeBuffer);\n await MyTable.put({ id: 'my-record', data: blob });\n ```\n\n3. **Retrieve blob data using standard Web API methods**: The `Blob` type implements the Web API `Blob` interface. Use `.bytes()`, `.text()`, `.arrayBuffer()`, `.stream()`, or `.slice()` as needed.\n\n ```javascript\n let record = await MyTable.get('my-record');\n let buffer = await record.data.bytes(); // ArrayBuffer\n let text = await record.data.text(); // string\n let stream = record.data.stream(); // ReadableStream\n ```\n\n4. **Use `saveBeforeCommit` when full write must precede commit**: By default, `Blob` is not ACID-compliant — a record can reference a blob before it is fully written. Set `saveBeforeCommit: true` to block the transaction until the blob is fully saved.\n\n ```javascript\n let blob = createBlob(stream, { saveBeforeCommit: true });\n await MyTable.put({ id: 'my-record', data: blob });\n // put() resolves only after blob is fully written and record is committed\n ```\n\n5. **Register an error handler when returning a blob via REST**: Interrupted streams must be handled explicitly.\n\n ```javascript\n export class MyEndpoint extends MyTable {\n static async get(target) {\n const record = super.get(target);\n let blob = record.data;\n blob.on('error', () => {\n MyTable.invalidate(target);\n });\n return { status: 200, headers: {}, body: blob };\n }\n }\n ```\n\n6. **Rely on automatic coercion where applicable**: When a field is typed as `Blob` in the schema, any string or buffer assigned via `put`, `patch`, or `publish` is automatically coerced to a `Blob` — no manual `createBlob()` call is needed in those cases.\n\n### `BlobOptions` reference\n\nPass an options object as the second argument to `createBlob()`.\n\n| Option | Type | Default | Description |\n| ------------------ | --------- | ----------- | ------------------------------------------------------------------------------------------------------------------------ |\n| `type` | `string` | `undefined` | MIME type to associate with the blob (e.g., `image/jpeg`). Readable via `blob.type` and used when serving HTTP. |\n| `size` | `number` | `undefined` | Size of the data in bytes, if known ahead of time. Otherwise inferred from a buffer or determined as a stream completes. |\n| `saveBeforeCommit` | `boolean` | `false` | Wait until the blob is fully written before the transaction commits. |\n| `compress` | `boolean` | `false` | Compress the stored data with deflate. |\n| `flush` | `boolean` | `false` | Flush the file to disk after writing, before the `createBlob` promise chain resolves. |\n\n## Examples\n\n**Store an image with a MIME type:**\n\n```javascript\nlet blob = createBlob(imageBuffer, { type: 'image/jpeg' });\nawait Photo.put({ id, data: blob });\n```\n\n**Stream a blob in as it streams out (low-latency passthrough):**\n\n```javascript\nlet blob = createBlob(incomingStream);\n// blob exists, but data is still streaming to storage\nawait MyTable.put({ id: 'my-record', data: blob });\n\nlet record = await MyTable.get('my-record');\n// blob data is accessible as it arrives\nlet outgoingStream = record.data.stream();\n```\n\n**Guarantee full write before commit using `saveBeforeCommit`:**\n\n```javascript\nlet blob = createBlob(stream, { saveBeforeCommit: true });\nawait MyTable.put({ id: 'my-record', data: blob });\n```\n\n## Notes\n\n- `Blob` stores data separately from the record. If you need the binary data to be a true, ACID-committed part of the record, use a `Bytes` field instead.\n- All standard Web API `Blob` methods — `.text()`, `.arrayBuffer()`, `.stream()`, `.slice()`, and `.bytes()` — are available on retrieved blob fields.\n- Without `saveBeforeCommit: true`, blobs are **not** ACID-compliant by default; a record can reference a blob before it is fully written to storage.\n","v5-upgrade":"---\nname: v5-upgrade\ndescription: >-\n Breaking changes and recommended updates when migrating a Harper application\n to v5.\nmetadata:\n mode: generate\n sources:\n - release-notes/v5-lincoln/v5-migration.md\n sourceCommit: de2aaf1c759a7ff5b93e862ba704153e2a392fcb\n inputHash: 80314689f3a7f42e\n---\n\n# Upgrading a Harper Application to v5\n\nInstructions for the agent to follow when migrating an existing Harper application to version 5, addressing the breaking changes and adopting the recommended patterns.\n\n## When to Use\n\nApply this rule when upgrading a Harper application from v4.x (or earlier) to v5, or when code written against older APIs behaves differently after a v5 upgrade — for example a record that can no longer be mutated, a query that returns stale data, or a `spawn` call that now throws. Harper v5 introduces breaking changes; applications built on documented APIs need the updates below, while code relying on undocumented behavior or timing may need broader review.\n\n## How It Works\n\n1. **Adopt the `harper` package name**: HarperDB is now Harper, and the package was renamed. Install the open source edition with `npm i -g harper` and the pro edition with `npm i -g @harperfast/harper-pro`. Update application imports from `harperdb` to `harper`:\n\n ```javascript\n import { tables } from 'harper';\n ```\n\n2. **Opt in to install scripts when required**: Harper now installs packages with `--ignore-scripts` to guard against accidental script execution, a common security risk. If an application genuinely needs install scripts to run (for example to build native binaries), pass the `allowInstallScripts` option when deploying.\n\n3. **Update `Table.get` return-value handling**: `Table.get` now returns a plain, frozen record object rather than an instance of the table class, so instance methods are no longer available on the result. The commonly used `wasLoadedFromSource()` method is gone; cache-vs-origin information now lives on the request `target` as `target.loadedFromSource`. Pass a `RequestTarget` to `Table.get` and read the flag from it. Because the record is frozen, create a copy instead of mutating it in place.\n\n4. **Account for automatic transaction context**: With RocksDB, transactions are fully supported by the storage engine, and Harper v5 uses asynchronous context tracking to carry the current transaction across calls automatically. A nested `Table.get` now reads within the current transaction's snapshot, so it will not observe newly written data until you commit. Access the context through `getContext()` and either commit the current transaction (`getContext().transaction.commit()`) or run the read inside a fresh `transaction(...)` to see the latest data. This matters most for code executing outside the context of a Harper request.\n\n5. **Register spawnable commands**: Spawning processes is now tightly controlled. `spawn`, `exec`, and `execFile` may only run executables listed in the `applications.allowedSpawnCommands` configuration, and each call must pass a `name` in its `options` so that only a single named process is started across Harper's multiple threads. Use a distinct `name` when you deliberately need a separate process.\n\n6. **Return Response-like objects to set headers**: If a REST method returns an object with a `headers` property, Harper uses it as the response headers.\n\n7. **Replace `blob.save()`**: The `blob.save()` method has been removed. Pass the `saveBeforeCommit` flag in the options to the `Blob` constructor instead.\n\n8. **Configure the VM module loader**: v5 loads application modules through Node.js's VM module API, giving each application its own module cache and an application-scoped `harper` module. All of this is controlled by the `applications` section of `harperdb-config.yaml`:\n - `moduleLoader` — `vm-current-context` (default), `vm`, `native`, or `compartment`. The default shares intrinsics with Harper for best compatibility; choose `vm` only if you need per-application intrinsics, and `native` to disable the VM loader entirely (restores pre-v5 loading, but per-app `logger`/`config` context is unavailable).\n - `lockdown` — `freeze-after-load` (default), `freeze`, `ses`, or `none`. Freezing intrinsics prevents prototype-pollution attacks; set `lockdown: none` only as a temporary workaround if a dependency mutates built-in prototypes.\n - `allowedDirectory` — `app` (default) restricts module loading to the application's own directory tree; set `any` if the app must load files from outside it in production.\n - `allowedBuiltinModules` — an optional allowlist restricting which Node.js built-ins the application may import (all are allowed if omitted).\n - `dependencyLoader` — `auto` (default), `app`, or `native`, controlling how npm dependencies are loaded through or around the VM loader.\n\n## Examples\n\n**Updating `Table.get` and its cache check:**\n\n```javascript\n// Old (v4.x)\nconst record = await Table.get(id);\nif (record.wasLoadedFromSource()) {\n // loaded from origin, not cache\n}\n\n// New (v5)\nconst target = new RequestTarget(); // passed in when overriding `get`\ntarget.id = id;\nconst record = await Table.get(target);\nif (target.loadedFromSource) {\n // loaded from origin, not cache\n}\n```\n\n**Committing the transaction to read fresh data:**\n\n```javascript\nimport { setTimeout as delay } from 'node:timers/promises';\nimport { getContext, transaction } from 'harper';\n\nclass MyResource {\n static async get(target) {\n // The current transaction is a consistent snapshot; commit it to see updates.\n await getContext().transaction.commit();\n while ((await transaction(() => Table.get(target))).status !== 'ready') {\n delay(100);\n }\n return Table.get(target);\n }\n}\n```\n\n**Module loader and security configuration in `harperdb-config.yaml`:**\n\n```yaml\napplications:\n lockdown: freeze-after-load # default\n moduleLoader: vm-current-context # vm-current-context (default) | vm | native | compartment\n dependencyLoader: auto # auto (default) | app | native\n allowedDirectory: app # app (default) | any\n allowedSpawnCommands:\n - npm\n - node\n # allowedBuiltinModules: [] # if omitted, all Node.js built-ins are allowed\n```\n\n## Recommended Changes\n\nBeyond the required fixes above, Harper v5 encourages these patterns for new and migrated code:\n\n- Implement endpoints with `static` methods on Resources/Tables, reading request information from the request `target` argument (or from `getContext()`).\n- Rely on automatic context propagation rather than threading context through every call manually; access it via `getContext()` exported from `harper`.\n- Access Harper functions and APIs through the `harper` package rather than through global variables.\n","vector-indexing":'---\nname: vector-indexing\ndescription: How to enable and query vector indexes for similarity search in Harper.\nmetadata:\n mode: generate\n sources:\n - reference/v5/database/schema.md#Vector Indexing\n sourceCommit: 4fe4c9c95e0974eaa77032f6f10e36fbd8ec64ac\n inputHash: d90b1b74597d08a6\n---\n\n# Vector Indexing\n\nInstructions for the agent to enable HNSW vector indexes on table fields and query them for similarity search in Harper.\n\n## When to Use\n\nApply this rule when adding a vector similarity search capability to a Harper table — for example, storing text embeddings and querying for nearest neighbors, filtering by distance threshold, or tuning index construction and search parameters. Use it alongside [adding-tables-with-schemas.md](adding-tables-with-schemas.md) when defining the schema that hosts the vector field.\n\n## How It Works\n\n1. **Declare the vector index on a field**: Add `@indexed(type: "HNSW")` to a `[Float]` field inside a `@table` type. This creates an HNSW (Hierarchical Navigable Small World) index for approximate nearest-neighbor search.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW")\n }\n ```\n\n2. **Query by nearest neighbors using `sort`**: Call `.search()` with a `sort` descriptor that specifies the indexed `attribute` and a `target` vector. Use `limit` to cap results.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n3. **Combine with filter conditions**: Add a `conditions` array alongside `sort` to pre-filter records before ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: [{ attribute: \'price\', comparator: \'lt\', value: 50 }],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n4. **Filter by distance threshold**: To return only records within a similarity cutoff (without ranking), place `target` directly on the condition alongside `comparator` and `value`. This bounds result quality rather than ranking by similarity.\n\n ```javascript\n let results = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n });\n ```\n\n5. **Include computed distance in results**: Use the special `$distance` field in `select` to return the distance from the target vector. Available in both `sort`-based and threshold-based queries.\n\n ```javascript\n let results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n });\n ```\n\n6. **Tune per-query search options**: Pass `distance` and `ef` directly on the `sort` descriptor to override index defaults for a single query.\n\n ```javascript\n let results = Document.search({\n sort: { attribute: \'textEmbeddings\', target: searchVector, distance: \'dotProduct\', ef: 200 },\n limit: 5,\n });\n ```\n\n - `distance` — overrides the distance function for this query: `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n - `ef` — overrides the search exploration budget. Higher values improve recall at the cost of latency.\n\n7. **Configure HNSW index parameters**: Pass parameters directly in the `@indexed` directive. Structural parameters (`distance`, `M`, `efConstruction`, `quantization`) trigger an index rebuild when changed; `efConstructionSearch` does not.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n }\n ```\n\n8. **Enable vector quantization**: Use `quantization: "int8"` to store vectors as 8-bit integers, reducing index size and memory usage. Harper re-ranks nearest-neighbor `sort` results against full-precision vectors automatically.\n\n ```graphql\n type Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float] @indexed(type: "HNSW", quantization: "int8")\n }\n ```\n\n## Examples\n\nFull schema with custom HNSW parameters and a nearest-neighbor query with distance output:\n\n```graphql\ntype Document @table {\n id: Long @primaryKey\n textEmbeddings: [Float]\n @indexed(type: "HNSW", distance: "euclidean", optimizeRouting: 0, efConstructionSearch: 100)\n}\n```\n\n```javascript\n// Nearest-neighbor search with distance scores\nlet results = Document.search({\n select: [\'name\', \'$distance\'],\n sort: { attribute: \'textEmbeddings\', target: searchVector },\n limit: 5,\n});\n\n// Distance-threshold query (no ranking)\nlet closeMatches = Document.search({\n conditions: {\n attribute: \'textEmbeddings\',\n comparator: \'lt\',\n value: 0.1,\n target: searchVector,\n },\n});\n```\n\n## Notes\n\n### HNSW Parameters\n\n| Parameter | Default | Description |\n| ---------------------- | ----------------- | ------------------------------------------------------------------------------------------------------ |\n| `distance` | `"cosine"` | Distance function: `"cosine"`, `"euclidean"`, or `"dotProduct"` |\n| `efConstruction` | `100` | Max nodes explored during index construction. Higher = better recall, lower = better performance |\n| `M` | `16` | Preferred connections per graph layer. Higher = more space, better recall for high-dimensional data |\n| `optimizeRouting` | `0.5` | Heuristic aggressiveness for omitting redundant connections (0 = off, 1 = most aggressive) |\n| `mL` | computed from `M` | Normalization factor for level generation |\n| `efConstructionSearch` | auto-scaled | Max nodes explored during search. When unset, auto-scales with index size; setting it fixes the budget |\n| `quantization` | — | `"int8"` stores vectors quantized to int8 |\n\n- The `distance` option on a per-query `sort` descriptor accepts `"cosine"`, `"euclidean"`, or `"dotProduct"`.\n- When no `ef` is passed and `efConstructionSearch` (or `efConstruction`) is not explicitly set on the index, the search budget auto-scales with index size.\n- `efConstruction` seeds the initial value of `efConstructionSearch`; setting either one fixes the search budget.\n- The correct parameter name is `efConstructionSearch` (not `efSearchConstruction`).\n- `$distance` is available in both `sort`-based ranking and `conditions`-based threshold queries.\n- For `quantization: "int8"`, distance-threshold (`lt`/`le`) queries filter on approximate distance; `sort` queries re-rank against full-precision vectors.\n'},sa={name:`readHarperSkill`,description:`Returns documentation for a Harper skill or best practice. Skills provide guidance on developing Harper applications.`,inputSchema:v({skill:m(aa)})};async function ca({input:{skill:e}}){return{success:!!oa[e],message:oa[e]||`No skill found with the name ${e}`}}var la={...sa,icon:at,execute:ca},ua={name:`readLogs`,description:`Returns the matching logs from the server.`,inputSchema:v({log_name:m([`hdb.log`,`system.log`]).default(`hdb.log`),limit:o().or(a()).optional(),level:m([`notify`,`error`,`warn`,`info`,`debug`,`trace`,`undefined`]).or(a()).optional(),from:o().or(a()).optional(),until:o().or(a()).optional()})};async function da({input:e,instanceClientParams:t}){try{return{success:!0,data:await Ve({...t,logFilters:e,replicated:t.entityType===`cluster`})}}catch(e){return{success:!1,message:`Error: ${e}`}}}var fa={...ua,icon:lt,execute:da},pa={name:`readTableRecords`,description:`Retrieves some or all table records from a database on the server.`,inputSchema:v({database:o().trim(),table:o().trim(),pageIndex:i().default(0),pageSize:i().default(10),primaryKey:o(),conditions:s(v({search_attribute:o(),search_type:m([`between`,`eq`,`equals`,`greater_than`,`greater_than_equal`,`less_than`,`less_than_equal`,`ne`,`not_equal`,`starts_with`]),search_value:h()})),sort:v({attribute:o(),descending:d()})})};async function ma({input:{database:e,table:t,conditions:n,primaryKey:r,...i},instanceClientParams:a}){try{if(!n.length){let{data:n}=await ke({...a,databaseName:e,tableName:t,onlyIfCached:!0,searchAttribute:r,...i});return{success:!0,data:n}}let{data:o}=await je({...a,databaseName:e,tableName:t,onlyIfCached:!0,conditions:n,...i});return{success:!0,data:o}}catch(e){return{success:!1,message:`Error: ${e}`}}}var ha={...pa,icon:Re,execute:ma},ga={name:`restartHTTPService`,description:`Restarts the HTTP service on the server to allow schema and resource changes to be applied.`,inputSchema:v({})};async function _a({instanceClientParams:e,baseURL:t}){let n=C.loading(`Restarting HTTP service...`,{description:`This may take a bit.`,duration:3e5});try{await Be({...e,operation:`restart_service`,replicated:e.entityType===`cluster`})}catch(e){return{success:!1,message:`Error: ${e}`}}return C.success(`Done!`,{description:`HTTP Service restarted!`,id:n,duration:5e3}),{success:!0,message:`HTTP Service restarted!`,webURL:t}}var va={...ga,icon:We,execute:_a,requiresApproval:!0},ya={name:`setComponentFile`,description:`Returns the contents of a component file by its full path (which was returned by getComponents)`,inputSchema:v({path:o().trim(),payload:o(),encoding:m([`utf8`,`ASCII`,`binary`,`hex`,`base64`,`utf16le`,`latin1`,`ucs2`])})};async function ba({input:{path:e,encoding:t,payload:n},instanceClientParams:r}){try{let i=e.split(`/`),a=i.shift(),o=i.join(`/`),s=await Ce({...r,file:o,project:a,payload:n,encoding:t});return await Te.invalidateQueries({queryKey:[r.entityId,`get_component_file`,a,o]}),Fe(`ReloadApplicationRootEntries`,!0),{success:!0,data:s}}catch(e){return{success:!1,message:`Error: ${e}`}}}var xa={...ya,icon:ct,execute:ba,requiresApproval:!0},Sa={name:`updateTableRecords`,description:`Updates records in a particular table in a particular database on the server.`,inputSchema:v({database:o().trim(),table:o().trim(),records:s(h())})};async function Ca({input:{database:e,table:t,records:n},instanceClientParams:r,params:i}){try{let a=await Ue({...r,databaseName:e,tableName:t,records:n}),{databaseName:o,tableName:s}=i;return await Te.invalidateQueries({queryKey:[r.entityId,o,s]}),{success:!0,data:a}}catch(e){return{success:!1,message:`Error: ${e}`}}}var wa={readHarperSkill:la,createApp:Di,readLogs:fa,getAnalytics:Ii,listAnalyticsMetrics:ia,restartHTTPService:va,collectFeedback:wi,getUserContext:Zi,getComponentFile:zi,getComponents:Hi,setComponentFile:xa,dropComponentFile:Ni,getDescribeAll:Gi,getDescribeTable:Ji,insertTableRecords:ea,readTableRecords:ha,updateTableRecords:{...Sa,icon:it,execute:Ca,requiresApproval:!0},deleteTableRecords:Ai};function Ta(e){return wa[e]}function Ea(e){return e.state===`input-available`&&!!Ta(Qr(e))?.requiresApproval}function Da(e){let t=[];for(let[n,r]of(e??[]).entries()){if(G(r)){if(Ea(r)){t.push({kind:`part`,part:r,index:n});continue}let e=t.at(-1);e?.kind===`tool-group`?e.parts.push(r):t.push({kind:`tool-group`,parts:[r],index:n});continue}Jr(r)&&r.text.length>0&&t.push({kind:`part`,part:r,index:n})}return t}function Oa({part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i}){let[a,o]=(0,T.useState)(!1),[s,c]=(0,T.useState)(!1),l=Qr(e),u=Ta(l),d=u?.icon||Ze,f=u?.requiresApproval,p=(0,T.useMemo)(()=>!e.input||typeof e.input==`object`&&Object.keys(e.input).length===0,[e.input]),m=(0,T.useMemo)(()=>{let t=JSON.stringify(e.input,null,` `);return{json:t,lines:t?t.split(`
1947
1947
  `).length:0}},[e.input]),h=(0,T.useMemo)(()=>{let t=JSON.stringify(e.output,null,` `);return{json:t,lines:t?t.split(`
1948
- `).length:0}},[e.output]);return(0,E.jsxs)(`div`,{className:`tool-invocation ${e.state}`,children:[(0,E.jsxs)(`div`,{className:`tool-info`,children:[(0,E.jsxs)(`div`,{className:`tool-name`,children:[(0,E.jsx)(d,{size:14}),(0,E.jsx)(`span`,{children:l})]}),(0,E.jsxs)(`div`,{className:`tool-status`,children:[e.state===`input-streaming`&&(0,E.jsx)(`span`,{children:`Thinking...`}),e.state===`input-available`&&(0,E.jsx)(`span`,{children:i?`Executing...`:f?`Awaiting Approval...`:`Executing...`}),e.state===`output-available`&&(e.output?.error?(0,E.jsx)(st,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14}))]})]}),e.state!==`input-streaming`&&(0,E.jsxs)(`div`,{className:`tool-io`,children:[!p&&(0,E.jsxs)(`div`,{className:`tool-args`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Input:`}),m.lines>3&&(0,E.jsx)(S,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>o(!a),children:a?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(de,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:a?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:m.json})]}),e.state===`input-available`&&f&&(0,E.jsxs)(`div`,{className:`flex gap-2 mt-3 pt-3 border-t`,children:[(0,E.jsxs)(S,{size:`sm`,className:`h-8 text-xs bg-green-600 hover:bg-green-700 text-white`,onClick:()=>t?.(e.toolCallId),disabled:i,children:[i?(0,E.jsx)(Ye,{className:`mr-2 h-3 w-3 animate-spin`}):null,`Approve`]}),(0,E.jsx)(S,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>r?.(e.toolCallId),disabled:i,children:`Always Approve`}),(0,E.jsx)(S,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>n?.(e.toolCallId),disabled:i,children:`Deny`})]}),e.state===`output-available`&&(0,E.jsx)(E.Fragment,{children:u?.render?u.render(e):(0,E.jsxs)(`div`,{className:`tool-result`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Result:`}),h.lines>3&&(0,E.jsx)(S,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>c(!s),children:s?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(de,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:s?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:h.json})]})})]})]})}function ka({parts:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){let[a,o]=(0,T.useState)(!1),s=e.some(e=>e.state!==`output-available`&&e.state!==`output-error`),c=e.some(e=>e.state===`output-error`||e.state===`output-available`&&e.output?.error),l=e.length===1?Qr(e[0]):void 0,u=l&&Ta(l)?.icon||ft,d=l??`${e.length} tools`;return(0,E.jsxs)(`div`,{className:`tool-group`,children:[(0,E.jsxs)(`button`,{type:`button`,className:`tool-group-summary`,"aria-expanded":a,onClick:()=>o(!a),children:[a?(0,E.jsx)(de,{size:14}):(0,E.jsx)(Je,{size:14}),(0,E.jsx)(u,{size:14}),(0,E.jsx)(`span`,{children:s?`Using ${d}...`:`Used ${d}`}),(0,E.jsx)(`span`,{className:`tool-group-status`,children:s?(0,E.jsx)(Ye,{size:14,className:`animate-spin`}):c?(0,E.jsx)(st,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14})})]}),a&&e.map(e=>(0,E.jsx)(Oa,{part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(e.toolCallId)},e.toolCallId))]})}function Aa({message:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){return e.parts?.some(e=>Jr(e)&&e.text.length>0||G(e))?(0,E.jsxs)(ce.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`message-bubble ${e.role===`user`?`user`:`assistant`}`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:e.role===`user`?(0,E.jsx)(Ae,{size:18}):(0,E.jsx)(se,{size:18})}),(0,E.jsx)(`div`,{className:`content`,children:Da(e.parts).map(e=>{if(e.kind===`tool-group`)return(0,E.jsx)(ka,{parts:e.parts,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i},e.parts[0].toolCallId);let{part:a,index:o}=e;return Jr(a)?(0,E.jsx)(`div`,{className:`text-block`,children:a.text},o):G(a)?(0,E.jsx)(Oa,{part:a,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(a.toolCallId)},o):null})})]},e.id):null}function ja(e,t){if(e!==`submitted`&&e!==`streaming`)return!1;if(t?.role!==`assistant`)return!0;let n=t.parts?.at(-1);return n?Jr(n)?n.state!==`streaming`||n.text.length===0:!G(n)||n.state===`output-available`||n.state===`output-error`:!0}function Ma(){return(0,E.jsxs)(ce.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2},className:`message-bubble assistant`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:(0,E.jsx)(se,{size:18})}),(0,E.jsxs)(`div`,{className:`content thinking-indicator`,role:`status`,"aria-label":`Harper Agent is thinking`,children:[(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`})]})]})}function Na(e){return ie({queryKey:[`getMyUsage`,e],queryFn:async()=>{let{data:t}=await x.get(`/Chat/Usage/${e}`);return t}})}function Pa(){let{organizationId:e}=te({strict:!1});return re(Na(e))}function Fa(){let{data:e,isLoading:t,error:n}=Pa();if(t||n||!e)return null;let{usageUSD:r,monthlyLimitUSD:i,usageBarPercent:a}=e,o=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`}).format(e);return(0,E.jsxs)(`div`,{className:`usage-container`,children:[(0,E.jsxs)(`div`,{className:`usage-info`,children:[(0,E.jsx)(`span`,{children:`Monthly Org Usage`}),(0,E.jsxs)(`span`,{children:[o(r),` / `,o(i)]}),(0,E.jsxs)(`span`,{children:[Math.round(a),`%`]})]}),(0,E.jsx)(`div`,{className:`usage-bar-bg`,children:(0,E.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${a}%`}})})]})}function Ia({autoFocus:e,closeChat:t}){let n=te({strict:!1}),{organizationId:r}=n,[i,a]=ke(`ApplicationChat`,``),[o,s]=(0,T.useState)(!0),[c,l]=(0,T.useState)({}),[u,d]=(0,T.useState)(new Set),[f,p]=Ee(Te.ChatAlwaysApprovedTools,[]),m=new Set(f),h=nt(),g=De(),_=ne(),{messages:v,sendMessage:ee,status:y,addToolOutput:b,setMessages:x}=yi({transport:ci(r),generateId:A(),sendAutomaticallyWhen:si,onFinish(){_.invalidateQueries({queryKey:[`getMyUsage`]})},async onToolCall({toolCall:e}){if(e.dynamic)return;let t=Ta(e.toolName);if(t){if(t.requiresApproval&&!m.has(e.toolName)){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input};l(n=>({...n,[e.toolCallId]:t}));return}let r=await t.execute({input:e.input,instanceClientParams:g,baseURL:h,params:n});b({tool:e.toolName,toolCallId:e.toolCallId,output:r})}}}),S=(0,T.useCallback)(async e=>{let t=c[e];if(t){d(t=>{let n=new Set(t);return n.add(e),n});try{let r=Ta(t.toolName);if(r){let i=await r.execute({input:t.input,instanceClientParams:g,baseURL:h,params:n});b({tool:t.toolName,toolCallId:t.toolCallId,output:i}),l(t=>{let n={...t};return delete n[e],n})}}finally{d(t=>{let n=new Set(t);return n.delete(e),n})}}},[c,g,h,b,n]),re=(0,T.useCallback)(e=>{let t=c[e];t&&(b({tool:t.toolName,toolCallId:t.toolCallId,output:{error:`User denied the tool execution.`}}),l(t=>{let n={...t};return delete n[e],n}))},[c,b]),ie=(0,T.useCallback)(async e=>{let t=c[e];t&&(p(e=>Le([...e,t.toolName])),await S(e))},[c,p,S]);(0,T.useEffect)(()=>{(async()=>{try{let e=await ht();Array.isArray(e)&&x(e)}catch(e){console.error(`Failed to fetch initial messages:`,e)}finally{s(!1)}})()},[x]);let ae=y===`streaming`||y===`submitted`,oe=(0,T.useRef)(null);return(0,T.useEffect)(()=>{oe.current?.scrollIntoView({behavior:`smooth`})},[v]),(0,E.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,E.jsxs)(`div`,{className:`flex items-start justify-between gap-6 px-4 py-2.5 border-b border-border bg-card`,children:[(0,E.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,children:[(0,E.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,E.jsx)(se,{className:`text-primary`,size:20}),(0,E.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Harper Agent`})]}),(0,E.jsx)(Fa,{})]}),(0,E.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,E.jsx)(mt,{setMessages:x}),(0,E.jsx)(`button`,{onClick:t,className:`p-1 hover:bg-accent rounded-md transition-colors text-muted-foreground hover:text-foreground`,title:`Close chat`,children:(0,E.jsx)(fe,{size:20})})]})]}),(0,E.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,E.jsxs)(`div`,{className:`chat-interface h-full w-full`,children:[(0,E.jsxs)(`div`,{className:`messages-area`,children:[o&&(0,E.jsx)(xi,{}),!o&&v.length===0&&(0,E.jsxs)(`div`,{className:`empty-state`,children:[(0,E.jsx)(se,{size:48}),(0,E.jsx)(`p`,{children:`Ask me to create a Harper app!`})]}),v.map(e=>(0,E.jsx)(Aa,{message:e,onApprove:S,onDeny:re,onAlwaysApprove:ie,approvingToolCallIds:u},e.id)),ja(y,v.at(-1))&&(0,E.jsx)(Ma,{}),(0,E.jsx)(`div`,{ref:oe})]}),(0,E.jsx)(bi,{input:i,setInput:a,onSubmit:e=>{e.preventDefault(),i.trim()&&!ae&&!o&&(ee({text:i}),a(``))},disabled:o,autoFocus:e})]})})]})}export{Ia as Chat};
1949
- //# sourceMappingURL=Chat-aApwhRmz.js.map
1948
+ `).length:0}},[e.output]);return(0,E.jsxs)(`div`,{className:`tool-invocation ${e.state}`,children:[(0,E.jsxs)(`div`,{className:`tool-info`,children:[(0,E.jsxs)(`div`,{className:`tool-name`,children:[(0,E.jsx)(d,{size:14}),(0,E.jsx)(`span`,{children:l})]}),(0,E.jsxs)(`div`,{className:`tool-status`,children:[e.state===`input-streaming`&&(0,E.jsx)(`span`,{children:`Thinking...`}),e.state===`input-available`&&(0,E.jsx)(`span`,{children:i?`Executing...`:f?`Awaiting Approval...`:`Executing...`}),e.state===`output-available`&&(e.output?.error?(0,E.jsx)(st,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14}))]})]}),e.state!==`input-streaming`&&(0,E.jsxs)(`div`,{className:`tool-io`,children:[!p&&(0,E.jsxs)(`div`,{className:`tool-args`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Input:`}),m.lines>3&&(0,E.jsx)(S,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>o(!a),children:a?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(de,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:a?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:m.json})]}),e.state===`input-available`&&f&&(0,E.jsxs)(`div`,{className:`flex gap-2 mt-3 pt-3 border-t`,children:[(0,E.jsxs)(S,{size:`sm`,className:`h-8 text-xs bg-green-600 hover:bg-green-700 text-white`,onClick:()=>t?.(e.toolCallId),disabled:i,children:[i?(0,E.jsx)(qe,{className:`mr-2 h-3 w-3 animate-spin`}):null,`Approve`]}),(0,E.jsx)(S,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>r?.(e.toolCallId),disabled:i,children:`Always Approve`}),(0,E.jsx)(S,{type:`button`,size:`sm`,variant:`outline`,className:`h-8 text-xs approval-outline`,onClick:()=>n?.(e.toolCallId),disabled:i,children:`Deny`})]}),e.state===`output-available`&&(0,E.jsx)(E.Fragment,{children:u?.render?u.render(e):(0,E.jsxs)(`div`,{className:`tool-result`,children:[(0,E.jsxs)(`div`,{className:`flex items-center justify-between gap-2 mb-1`,children:[(0,E.jsx)(`strong`,{children:`Result:`}),h.lines>3&&(0,E.jsx)(S,{type:`button`,variant:`ghost`,size:`sm`,className:`h-6 px-2 text-[10px] uppercase tracking-wider text-muted-foreground hover:text-foreground`,onClick:()=>c(!s),children:s?(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(ue,{size:12}),`Hide`]}):(0,E.jsxs)(E.Fragment,{children:[(0,E.jsx)(de,{size:12}),`Show`]})})]}),(0,E.jsx)(`div`,{className:s?`whitespace-pre-wrap`:`line-clamp-3 overflow-hidden whitespace-pre-wrap`,children:h.json})]})})]})]})}function ka({parts:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){let[a,o]=(0,T.useState)(!1),s=e.some(e=>e.state!==`output-available`&&e.state!==`output-error`),c=e.some(e=>e.state===`output-error`||e.state===`output-available`&&e.output?.error),l=e.length===1?Qr(e[0]):void 0,u=l&&Ta(l)?.icon||ft,d=l??`${e.length} tools`;return(0,E.jsxs)(`div`,{className:`tool-group`,children:[(0,E.jsxs)(`button`,{type:`button`,className:`tool-group-summary`,"aria-expanded":a,onClick:()=>o(!a),children:[a?(0,E.jsx)(de,{size:14}):(0,E.jsx)(pe,{size:14}),(0,E.jsx)(u,{size:14}),(0,E.jsx)(`span`,{children:s?`Using ${d}...`:`Used ${d}`}),(0,E.jsx)(`span`,{className:`tool-group-status`,children:s?(0,E.jsx)(qe,{size:14,className:`animate-spin`}):c?(0,E.jsx)(st,{size:14,className:`text-destructive`}):(0,E.jsx)(le,{size:14})})]}),a&&e.map(e=>(0,E.jsx)(Oa,{part:e,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(e.toolCallId)},e.toolCallId))]})}function Aa({message:e,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i}){return e.parts?.some(e=>Jr(e)&&e.text.length>0||G(e))?(0,E.jsxs)(ce.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},className:`message-bubble ${e.role===`user`?`user`:`assistant`}`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:e.role===`user`?(0,E.jsx)(Me,{size:18}):(0,E.jsx)(se,{size:18})}),(0,E.jsx)(`div`,{className:`content`,children:Da(e.parts).map(e=>{if(e.kind===`tool-group`)return(0,E.jsx)(ka,{parts:e.parts,onApprove:t,onDeny:n,onAlwaysApprove:r,approvingToolCallIds:i},e.parts[0].toolCallId);let{part:a,index:o}=e;return Jr(a)?(0,E.jsx)(`div`,{className:`text-block`,children:a.text},o):G(a)?(0,E.jsx)(Oa,{part:a,onApprove:t,onDeny:n,onAlwaysApprove:r,isApproving:i?.has(a.toolCallId)},o):null})})]},e.id):null}function ja(e,t){if(e!==`submitted`&&e!==`streaming`)return!1;if(t?.role!==`assistant`)return!0;let n=t.parts?.at(-1);return n?Jr(n)?n.state!==`streaming`||n.text.length===0:!G(n)||n.state===`output-available`||n.state===`output-error`:!0}function Ma(){return(0,E.jsxs)(ce.div,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.2},className:`message-bubble assistant`,children:[(0,E.jsx)(`div`,{className:`avatar`,children:(0,E.jsx)(se,{size:18})}),(0,E.jsxs)(`div`,{className:`content thinking-indicator`,role:`status`,"aria-label":`Harper Agent is thinking`,children:[(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`}),(0,E.jsx)(`span`,{className:`thinking-dot`})]})]})}function Na(e){return ie({queryKey:[`getMyUsage`,e],queryFn:async()=>{let{data:t}=await x.get(`/Chat/Usage/${e}`);return t}})}function Pa(){let{organizationId:e}=te({strict:!1});return re(Na(e))}function Fa(){let{data:e,isLoading:t,error:n}=Pa();if(t||n||!e)return null;let{usageUSD:r,monthlyLimitUSD:i,usageBarPercent:a}=e,o=e=>new Intl.NumberFormat(`en-US`,{style:`currency`,currency:`USD`}).format(e);return(0,E.jsxs)(`div`,{className:`usage-container`,children:[(0,E.jsxs)(`div`,{className:`usage-info`,children:[(0,E.jsx)(`span`,{children:`Monthly Org Usage`}),(0,E.jsxs)(`span`,{children:[o(r),` / `,o(i)]}),(0,E.jsxs)(`span`,{children:[Math.round(a),`%`]})]}),(0,E.jsx)(`div`,{className:`usage-bar-bg`,children:(0,E.jsx)(`div`,{className:`usage-bar-fill`,style:{width:`${a}%`}})})]})}function Ia({autoFocus:e,closeChat:t}){let n=te({strict:!1}),{organizationId:r}=n,[i,a]=Je(`ApplicationChat`,``),[o,s]=(0,T.useState)(!0),[c,l]=(0,T.useState)({}),[u,d]=(0,T.useState)(new Set),[f,p]=De(Ee.ChatAlwaysApprovedTools,[]),m=new Set(f),h=nt(),g=Oe(),_=ne(),{messages:v,sendMessage:ee,status:y,addToolOutput:b,setMessages:x}=yi({transport:ci(r),generateId:A(),sendAutomaticallyWhen:si,onFinish(){_.invalidateQueries({queryKey:[`getMyUsage`]})},async onToolCall({toolCall:e}){if(e.dynamic)return;let t=Ta(e.toolName);if(t){if(t.requiresApproval&&!m.has(e.toolName)){let t={type:`tool-call`,toolCallId:e.toolCallId,toolName:e.toolName,input:e.input};l(n=>({...n,[e.toolCallId]:t}));return}let r=await t.execute({input:e.input,instanceClientParams:g,baseURL:h,params:n});b({tool:e.toolName,toolCallId:e.toolCallId,output:r})}}}),S=(0,T.useCallback)(async e=>{let t=c[e];if(t){d(t=>{let n=new Set(t);return n.add(e),n});try{let r=Ta(t.toolName);if(r){let i=await r.execute({input:t.input,instanceClientParams:g,baseURL:h,params:n});b({tool:t.toolName,toolCallId:t.toolCallId,output:i}),l(t=>{let n={...t};return delete n[e],n})}}finally{d(t=>{let n=new Set(t);return n.delete(e),n})}}},[c,g,h,b,n]),re=(0,T.useCallback)(e=>{let t=c[e];t&&(b({tool:t.toolName,toolCallId:t.toolCallId,output:{error:`User denied the tool execution.`}}),l(t=>{let n={...t};return delete n[e],n}))},[c,b]),ie=(0,T.useCallback)(async e=>{let t=c[e];t&&(p(e=>Ye([...e,t.toolName])),await S(e))},[c,p,S]);(0,T.useEffect)(()=>{(async()=>{try{let e=await ht();Array.isArray(e)&&x(e)}catch(e){console.error(`Failed to fetch initial messages:`,e)}finally{s(!1)}})()},[x]);let ae=y===`streaming`||y===`submitted`,oe=(0,T.useRef)(null);return(0,T.useEffect)(()=>{oe.current?.scrollIntoView({behavior:`smooth`})},[v]),(0,E.jsxs)(`div`,{className:`flex flex-col h-full`,children:[(0,E.jsxs)(`div`,{className:`flex items-start justify-between gap-6 px-4 py-2.5 border-b border-border bg-card`,children:[(0,E.jsxs)(`div`,{className:`flex flex-col gap-1 min-w-0 flex-1`,children:[(0,E.jsxs)(`div`,{className:`flex items-center gap-2`,children:[(0,E.jsx)(se,{className:`text-primary`,size:20}),(0,E.jsx)(`span`,{className:`font-semibold text-foreground`,children:`Harper Agent`})]}),(0,E.jsx)(Fa,{})]}),(0,E.jsxs)(`div`,{className:`flex items-center gap-2 shrink-0`,children:[(0,E.jsx)(mt,{setMessages:x}),(0,E.jsx)(`button`,{onClick:t,className:`p-1 hover:bg-accent rounded-md transition-colors text-muted-foreground hover:text-foreground`,title:`Close chat`,children:(0,E.jsx)(fe,{size:20})})]})]}),(0,E.jsx)(`div`,{className:`flex-1 overflow-hidden`,children:(0,E.jsxs)(`div`,{className:`chat-interface h-full w-full`,children:[(0,E.jsxs)(`div`,{className:`messages-area`,children:[o&&(0,E.jsx)(xi,{}),!o&&v.length===0&&(0,E.jsxs)(`div`,{className:`empty-state`,children:[(0,E.jsx)(se,{size:48}),(0,E.jsx)(`p`,{children:`Ask me to create a Harper app!`})]}),v.map(e=>(0,E.jsx)(Aa,{message:e,onApprove:S,onDeny:re,onAlwaysApprove:ie,approvingToolCallIds:u},e.id)),ja(y,v.at(-1))&&(0,E.jsx)(Ma,{}),(0,E.jsx)(`div`,{ref:oe})]}),(0,E.jsx)(bi,{input:i,setInput:a,onSubmit:e=>{e.preventDefault(),i.trim()&&!ae&&!o&&(ee({text:i}),a(``))},disabled:o,autoFocus:e})]})})]})}export{Ia as Chat};
1949
+ //# sourceMappingURL=Chat-BMUjPklt.js.map