@everfur/sdk 0.5.0 → 0.5.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 (154) hide show
  1. package/CHANGELOG.md +375 -0
  2. package/dist/BookedScreen-BJPbXLCG.d.ts +54 -0
  3. package/dist/BookedScreen-Cnld-jB_.d.cts +54 -0
  4. package/dist/{Chat-TA-aTcVF.d.cts → Chat-B43wIXCv.d.cts} +3 -3
  5. package/dist/{Chat-BOX-03ho.d.ts → Chat-my5aJLz5.d.ts} +3 -3
  6. package/dist/{DepthViews-DSFyaSeL.d.cts → DepthViews-BBTv9VAs.d.cts} +1 -1
  7. package/dist/{DepthViews-Cviea-ri.d.cts → DepthViews-BLK0kgza.d.cts} +1 -1
  8. package/dist/{DepthViews-CgjX2AJ5.d.ts → DepthViews-CNqAyjne.d.ts} +1 -1
  9. package/dist/{DepthViews-D2dRqWRq.d.ts → DepthViews-G-7YRtOX.d.ts} +1 -1
  10. package/dist/animations/index.cjs +1 -1
  11. package/dist/animations/index.d.cts +3 -3
  12. package/dist/animations/index.d.ts +3 -3
  13. package/dist/animations/index.js +1 -1
  14. package/dist/{attachments-DHvnITuE.d.cts → attachments-CEmT52IA.d.cts} +5 -5
  15. package/dist/{attachments-oD5U2fXI.d.ts → attachments-CMNWE6YT.d.ts} +2 -2
  16. package/dist/{attachments-C_vtFu2f.d.ts → attachments-DU1djTNd.d.ts} +5 -5
  17. package/dist/{attachments-pIdGOQfm.d.cts → attachments-ZyjWsZdI.d.cts} +2 -2
  18. package/dist/{bookingCopy-CJir9mjb.d.ts → bookingCopy-BVhEt1bj.d.ts} +38 -200
  19. package/dist/{bookingCopy-DfuA13dh.d.cts → bookingCopy-ChZR5mtd.d.cts} +38 -200
  20. package/dist/bookingTypes-DCs8mmBb.d.cts +188 -0
  21. package/dist/bookingTypes-DCs8mmBb.d.ts +188 -0
  22. package/dist/{callCopy-rDH9JTFo.d.cts → callCopy-CPe9mbwG.d.cts} +7 -2
  23. package/dist/{callCopy-rDH9JTFo.d.ts → callCopy-CPe9mbwG.d.ts} +7 -2
  24. package/dist/{casesRepository-DHgIYKN9.d.ts → casesRepository-C5zrCcaE.d.ts} +1 -1
  25. package/dist/{casesRepository-B-Eg8ZJ3.d.cts → casesRepository-q2ak9AW0.d.cts} +1 -1
  26. package/dist/chat/index.cjs +1 -1
  27. package/dist/chat/index.d.cts +14 -10
  28. package/dist/chat/index.d.ts +14 -10
  29. package/dist/chat/index.js +1 -1
  30. package/dist/client/index.cjs +5 -5
  31. package/dist/client/index.d.cts +6 -6
  32. package/dist/client/index.d.ts +6 -6
  33. package/dist/client/index.js +5 -5
  34. package/dist/{config-ClI7QxB0.d.ts → config-DBpKJJbg.d.ts} +1 -1
  35. package/dist/{config-DAFbf721.d.cts → config-jocy3q66.d.cts} +1 -1
  36. package/dist/consent/index.cjs +1 -1
  37. package/dist/consent/index.d.cts +5 -5
  38. package/dist/consent/index.d.ts +5 -5
  39. package/dist/consent/index.js +1 -1
  40. package/dist/{context-B-dUM1Qf.d.cts → context-BfVBRgro.d.cts} +5 -5
  41. package/dist/{context-CZbgF_OH.d.ts → context-C3n9s4aG.d.ts} +5 -5
  42. package/dist/{copy-CneuYdrO.d.cts → copy-IysFx8yL.d.cts} +2 -2
  43. package/dist/{copy-CeRH3NXy.d.ts → copy-KP91zgtW.d.ts} +2 -2
  44. package/dist/core/index.cjs +7 -7
  45. package/dist/core/index.d.cts +12 -12
  46. package/dist/core/index.d.ts +12 -12
  47. package/dist/core/index.js +7 -7
  48. package/dist/{depth-DO3Ko_qs.d.ts → depth-BsMLLrQo.d.ts} +2 -2
  49. package/dist/{depth-B3NFKlF9.d.cts → depth-O9kiVUjs.d.cts} +2 -2
  50. package/dist/{entitlementRepository-74kW5mK0.d.ts → entitlementRepository-CHsY2kF3.d.ts} +2 -2
  51. package/dist/{entitlementRepository-m6zLUmiB.d.cts → entitlementRepository-DIG16pso.d.cts} +2 -2
  52. package/dist/{identity-C7uxGwfT.d.cts → identity-D7GKfOE7.d.cts} +1 -1
  53. package/dist/{identity-CLAUq-K4.d.ts → identity-k8nCQ_qM.d.ts} +1 -1
  54. package/dist/index.cjs +6 -6
  55. package/dist/index.d.cts +13 -13
  56. package/dist/index.d.ts +13 -13
  57. package/dist/index.js +6 -6
  58. package/dist/notifications/index.cjs +2 -2
  59. package/dist/notifications/index.d.cts +2 -2
  60. package/dist/notifications/index.d.ts +2 -2
  61. package/dist/notifications/index.js +2 -2
  62. package/dist/{pets-BoB5B7kp.d.cts → pets-Bod_DDiW.d.cts} +1 -1
  63. package/dist/{pets-w4M9d-Dn.d.ts → pets-C_QX8s5f.d.ts} +1 -1
  64. package/dist/{petsRepository-DZZoEG3r.d.cts → petsRepository-B3vr628I.d.cts} +1 -1
  65. package/dist/{petsRepository-BjKJ8UsN.d.ts → petsRepository-DdzgINfF.d.ts} +1 -1
  66. package/dist/photo/index.cjs +1 -1
  67. package/dist/photo/index.js +1 -1
  68. package/dist/{ports-C2EVK416.d.cts → ports-BSm48zIC.d.cts} +16 -5
  69. package/dist/{ports-BO3bzTJg.d.ts → ports-DHhxhn95.d.ts} +16 -5
  70. package/dist/records/depth/index.cjs +2 -2
  71. package/dist/records/depth/index.d.cts +7 -7
  72. package/dist/records/depth/index.d.ts +7 -7
  73. package/dist/records/depth/index.js +2 -2
  74. package/dist/records/index.cjs +3 -3
  75. package/dist/records/index.d.cts +10 -10
  76. package/dist/records/index.d.ts +10 -10
  77. package/dist/records/index.js +3 -3
  78. package/dist/{requestFunnel-D7ipek3e.d.ts → requestFunnel-CTG-wNc3.d.ts} +2 -2
  79. package/dist/{requestFunnel-Djjwgoe9.d.cts → requestFunnel-Dcjyh0j2.d.cts} +2 -2
  80. package/dist/{runtimeTypes-D2C9uD85.d.cts → runtimeTypes-4qptUulD.d.cts} +4 -4
  81. package/dist/{runtimeTypes-CTL3yToK.d.ts → runtimeTypes-CmpdQaE2.d.ts} +4 -4
  82. package/dist/server/events/index.cjs +1 -1
  83. package/dist/server/events/index.d.cts +2 -2
  84. package/dist/server/events/index.d.ts +2 -2
  85. package/dist/server/events/index.js +1 -1
  86. package/dist/server/index.cjs +2 -2
  87. package/dist/server/index.d.cts +3 -3
  88. package/dist/server/index.d.ts +3 -3
  89. package/dist/server/index.js +2 -2
  90. package/dist/televet/booking/index.cjs +1 -1
  91. package/dist/televet/booking/index.d.cts +31 -17
  92. package/dist/televet/booking/index.d.ts +31 -17
  93. package/dist/televet/booking/index.js +1 -1
  94. package/dist/televet/call/index.cjs +1 -1
  95. package/dist/televet/call/index.d.cts +13 -1
  96. package/dist/televet/call/index.d.ts +13 -1
  97. package/dist/televet/call/index.js +1 -1
  98. package/dist/televet/index.cjs +1 -1
  99. package/dist/televet/index.js +1 -1
  100. package/dist/testing/index.cjs +3 -3
  101. package/dist/testing/index.d.cts +1 -1
  102. package/dist/testing/index.d.ts +1 -1
  103. package/dist/testing/index.js +3 -3
  104. package/dist/testing/rn/index.cjs +1 -1
  105. package/dist/testing/rn/index.d.cts +7 -7
  106. package/dist/testing/rn/index.d.ts +7 -7
  107. package/dist/testing/rn/index.js +1 -1
  108. package/dist/testing/web/index.cjs +1 -1
  109. package/dist/testing/web/index.d.cts +7 -7
  110. package/dist/testing/web/index.d.ts +7 -7
  111. package/dist/testing/web/index.js +1 -1
  112. package/dist/{timelineRows-CzR1T2DR.d.cts → timelineRows-BkLhRUDt.d.cts} +1 -1
  113. package/dist/{timelineRows-7yFNK_rU.d.ts → timelineRows-Dp4ZSnAo.d.ts} +1 -1
  114. package/dist/{uploadTransport-DKJHs3Yj.d.cts → uploadTransport-C1p8FuG8.d.cts} +5 -1
  115. package/dist/{uploadTransport-D0M0T4hN.d.ts → uploadTransport-bZIKBTyK.d.ts} +5 -1
  116. package/dist/{useRecordsDepth-Bnw36jPr.d.cts → useRecordsDepth-DRNry1r9.d.cts} +1 -1
  117. package/dist/{useRecordsDepth-DFF7Faxx.d.ts → useRecordsDepth-DnDhTaUL.d.ts} +1 -1
  118. package/dist/video/index.cjs +1 -1
  119. package/dist/video/index.js +1 -1
  120. package/dist/{view-BqcOYFTr.d.ts → view-CwuOPIJc.d.ts} +7 -4
  121. package/dist/{view-CaJs8WFH.d.cts → view-D4VdPKCa.d.cts} +7 -4
  122. package/dist/web/consent/index.cjs +1 -1
  123. package/dist/web/consent/index.d.cts +5 -5
  124. package/dist/web/consent/index.d.ts +5 -5
  125. package/dist/web/consent/index.js +1 -1
  126. package/dist/web/index.cjs +10 -10
  127. package/dist/web/index.d.cts +14 -14
  128. package/dist/web/index.d.ts +14 -14
  129. package/dist/web/index.js +10 -10
  130. package/dist/web/notifications/index.cjs +2 -2
  131. package/dist/web/notifications/index.d.cts +3 -3
  132. package/dist/web/notifications/index.d.ts +3 -3
  133. package/dist/web/notifications/index.js +2 -2
  134. package/dist/web/records/depth/index.cjs +2 -2
  135. package/dist/web/records/depth/index.d.cts +7 -7
  136. package/dist/web/records/depth/index.d.ts +7 -7
  137. package/dist/web/records/depth/index.js +2 -2
  138. package/dist/web/records/index.cjs +3 -3
  139. package/dist/web/records/index.d.cts +9 -9
  140. package/dist/web/records/index.d.ts +9 -9
  141. package/dist/web/records/index.js +3 -3
  142. package/dist/web/televet/booking/index.cjs +2 -2
  143. package/dist/web/televet/booking/index.d.cts +41 -52
  144. package/dist/web/televet/booking/index.d.ts +41 -52
  145. package/dist/web/televet/booking/index.js +2 -2
  146. package/dist/web/televet/call/index.cjs +1 -1
  147. package/dist/web/televet/call/index.d.cts +12 -5
  148. package/dist/web/televet/call/index.d.ts +12 -5
  149. package/dist/web/televet/call/index.js +1 -1
  150. package/dist/web/televet/index.cjs +4 -1
  151. package/dist/web/televet/index.d.cts +31 -2
  152. package/dist/web/televet/index.d.ts +31 -2
  153. package/dist/web/televet/index.js +4 -1
  154. package/package.json +4 -3
package/dist/web/index.js CHANGED
@@ -1,14 +1,14 @@
1
- import {createContext,useContext,createElement,useSyncExternalStore,useMemo,useState,useRef,useEffect,useCallback,useReducer,useLayoutEffect,Component,useId}from'react';import {z as z$1}from'zod';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var Yp=Object.defineProperty;var i=(e,t)=>Yp(e,"name",{value:t,configurable:true});function M(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(M,"ok");function E(e){return Object.freeze({ok:false,error:e})}i(E,"err");function Xp(e){return e.ok}i(Xp,"isOk");function Qp(e){return !e.ok}i(Qp,"isErr");var _r=class _r extends Error{constructor(t){super(`${t.code}: ${t.displayMessage}`),this.name="EverfurThrownError",this.error=t,this.code=t.code,this.category=t.category,Object.setPrototypeOf(this,_r.prototype);}};i(_r,"EverfurThrownError");var Pr=_r;function Zp(e){if(e.ok)return e.value;throw new Pr(e.error)}i(Zp,"unwrap");var wr=class wr extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,wr.prototype);}};i(wr,"EverfurConfigError");var J=wr;var Ir=Object.freeze({track(){},trackExpectedFailure(){}});var $n=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze($n.map(e=>e.wireCode));var Jp=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),la=Object.freeze($n.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:Jp[e.wireCode]}))),ef=new Map(la.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),tf=Object.freeze(["http_envelope",...[...new Set(la.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Ar(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...tf]){let o=ef.get(n+r);if(o)return o}}i(Ar,"contractErrorFor");function rf(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(rf,"contractDocUrl");function ua(e){return null}i(ua,"publishedDocUrl");var nf=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function Wn(e){return nf[e]}i(Wn,"categoryFor");function Ie(e){let t=Ar(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Ie,"fromWire");function da(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(da,"fromHttpStatus");var of=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function je(e){return of.has(e)}i(je,"isAutoRetryable");var af=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Kn(e){return je(e)||af.has(e)}i(Kn,"isRetryableCode");function Or(e,t=false){return t||je(e)}i(Or,"shouldRetry");var sf=500,Gn=8e3,jt=4;function Fr(e,t=Math.random){let r=Math.max(0,e),n=Math.min(sf*2**r,Gn);return Math.floor(t()*n)}i(Fr,"backoffDelayMs");function ca(e){return e==="conversationNotFound"}i(ca,"canRecreateOnNotFound");var pa=Object.freeze({shouldRetry(e,t){return je(e)&&t<jt},maxAttempts(){return jt}});var fa=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Je(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Je,"assertNever");function ma(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ma,"acceptedFrame");function ya(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(ya,"heartbeatFrame");function ga(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ga,"deltaFrame");function ha(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(ha,"doneFrame");function pe(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(pe,"errorFrame");function ba(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ba,"analysisStartedFrame");function va(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(va,"analysisCompleteFrame");function Ea(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Ea,"unknownFrame");var df=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function At(e){return df[e]}i(At,"userFacingError");function Ca(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(Ca,"defineHidden");var cf=/^[a-z][a-z0-9_]{0,63}$/;function D(e,t){let r=Ar(t?.wireCode,t?.wireEnvelope),n={code:e,category:Wn(e),retryable:t?.retryable??Kn(e),displayMessage:At(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&cf.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&Ca(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&Ca(n,"raw",t.raw),Object.freeze(n)}i(D,"makeEverfurError");function Sa(e,t,r){let n=null,o=null,a=false,s=i(()=>o||(o=(async()=>{try{let l=await t(),u=typeof l=="string"?l:l?.token;if(typeof u!="string"||u.length===0)throw new J("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:pf(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(a)throw new J("not-initialized","This identity was cleared (sign-out); mint a new one.");return l?.forceRefresh&&(n=null),n!==null?n:s()},hasToken(){return !a&&n!==null},clear(){a=true,n=null;}}}i(Sa,"createIdentityProvider");function pf(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(pf,"expiryMs");function Yn(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(Yn,"newSessionId");function ff(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(ff,"authHeaders");function Vt(e,t){return {...e,headers:{...mf(e.headers),...ff(t)}}}i(Vt,"withAuthHeaders");function mf(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(mf,"stripAuthHeaders");async function Ra(e,t){if(t.mode==="anonymous")return t.transport.request(Vt(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return E(qn())}let n=await t.transport.request(Vt(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return E(qn())}let a=await t.transport.request(Vt(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !a.ok&&a.error.httpStatus===401?E(qn(a.error.httpStatus)):a}i(Ra,"authedSend");function qn(e){return D("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(qn,"authRejectedError");var xa=`
1
+ import {createContext,useContext,createElement,useSyncExternalStore,useMemo,useState,useRef,useEffect,useCallback,useReducer,useLayoutEffect,Component,useId}from'react';import {z as z$1}from'zod';import {jsx,jsxs,Fragment}from'react/jsx-runtime';var rf=Object.defineProperty;var i=(e,t)=>rf(e,"name",{value:t,configurable:true});function M(e,t){return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}i(M,"ok");function E(e){return Object.freeze({ok:false,error:e})}i(E,"err");function nf(e){return e.ok}i(nf,"isOk");function of(e){return !e.ok}i(of,"isErr");var wr=class wr extends Error{constructor(t){super(`${t.code}: ${t.displayMessage}`),this.name="EverfurThrownError",this.error=t,this.code=t.code,this.category=t.category,Object.setPrototypeOf(this,wr.prototype);}};i(wr,"EverfurThrownError");var _r=wr;function af(e){if(e.ok)return e.value;throw new _r(e.error)}i(af,"unwrap");var Ir=class Ir extends Error{constructor(t,r){super(r),this.name="EverfurConfigError",this.kind=t,Object.setPrototypeOf(this,Ir.prototype);}};i(Ir,"EverfurConfigError");var J=Ir;var Ar=Object.freeze({track(){},trackExpectedFailure(){}});var Wn=Object.freeze([Object.freeze({wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true}),Object.freeze({wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true}),Object.freeze({wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false}),Object.freeze({wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false}),Object.freeze({wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false}),Object.freeze({wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true}),Object.freeze({wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false}),Object.freeze({wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false}),Object.freeze({wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false}),Object.freeze({wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false}),Object.freeze({wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false}),Object.freeze({wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false}),Object.freeze({wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true}),Object.freeze({wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false}),Object.freeze({wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false}),Object.freeze({wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true}),Object.freeze({wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false}),Object.freeze({wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false}),Object.freeze({wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true}),Object.freeze({wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false}),Object.freeze({wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true}),Object.freeze({wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false}),Object.freeze({wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false})]);Object.freeze(Wn.map(e=>e.wireCode));var sf=Object.freeze({ValidationException:"validationFailed",AuthorizationException:"authRejected",PaymentRequiredException:"paymentRequired",AccessDeniedException:"accessDenied",ResourceNotFoundException:"resourceNotFound",ConflictException:"conflict",ThrottlingException:"rateLimited",InternalFailureException:"internalError",NotImplementedException:"notImplemented",ServiceUnavailableException:"serviceUnavailable",MethodNotAllowedException:"validationFailed",authExpired:"authExpired",unavailable:"serviceUnavailable",session_required:"sessionRequired",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",event_cursor_invalid:"validationFailed",event_filter_invalid:"validationFailed",event_payload_invalid:"validationFailed",event_type_unknown:"validationFailed",idempotency_key_invalid:"validationFailed",idempotency_key_required:"validationFailed",idempotency_key_reused:"idempotencyConflict",payload_too_large:"validationFailed",webhook_url_rejected:"validationFailed",webhook_endpoint_update_empty:"validationFailed",webhook_endpoint_update_invalid:"validationFailed",event_type_not_available:"conflict",record_subject_not_found:"resourceNotFound",records_consent_required:"conflict",record_species_unsupported:"validationFailed",record_upload_invalid:"validationFailed",FILE_TOO_LARGE:"validationFailed",INVALID_CONTENT_TYPE:"validationFailed",attachment_unreadable:"validationFailed",provider_unsupported:"validationFailed",token_invalid:"validationFailed",device_cipher_unavailable:"serviceUnavailable",email_invalid:"validationFailed",consent_required:"validationFailed",consent_invalid:"validationFailed",consent_scope_wrong_route:"validationFailed",IDEMPOTENCY_KEY_IN_FLIGHT:"idempotencyInFlight",IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST:"idempotencyConflict",DAILY_QUOTA_EXCEEDED:"quotaExceeded",TIER_UPGRADE_REQUIRED:"paymentRequired",not_found:"conversationNotFound",timeout:"streamTimeout",internal_error:"internalError",invalid_request:"validationFailed",invalid_client:"authRejected",invalid_grant:"authRejected",unsupported_grant_type:"validationFailed",invalid_scope:"validationFailed",invalid_target:"validationFailed",invalid_redirect_uri:"validationFailed",invalid_client_metadata:"validationFailed",unsupported_response_type:"validationFailed",access_denied:"accessDenied",slow_down:"rateLimited",mcp_request_not_found:"resourceNotFound",mcp_request_gone:"resourceNotFound",mcp_connection_not_found:"resourceNotFound",mcp_request_conflict:"conflict",sandbox_only:"accessDenied",tenant_has_no_capabilities:"conflict",verify_mint_refused:"accessDenied",verify_mint_rate_limited:"rateLimited",verify_mint_unavailable:"serviceUnavailable",verify_user_ref_invalid:"validationFailed",insufficient_scope:"accessDenied",tenant_filter_invalid:"validationFailed",tenant_resource_not_found:"resourceNotFound",tenant_surface_not_enabled:"conflict",pet_health_species_unsupported:"validationFailed",pet_health_list_removals_unconfirmed:"validationFailed",petRefInUse:"conflict",share_limit_reached:"conflict",pet_not_registered:"resourceNotFound",species_unsupported:"validationFailed",partner_visit_owner_only:"accessDenied",partner_visit_link_conflict:"conflict",partner_visit_pet_already_mapped:"conflict"}),ca=Object.freeze(Wn.map(e=>Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:sf[e.wireCode]}))),lf=new Map(ca.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),uf=Object.freeze(["http_envelope",...[...new Set(ca.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function Or(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let n of [t??"http_envelope",...uf]){let o=lf.get(n+r);if(o)return o}}i(Or,"contractErrorFor");function df(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}i(df,"contractDocUrl");function pa(e){return null}i(pa,"publishedDocUrl");var cf=Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",conversationNotFound:"notFound",petNotFound:"notFound",resourceNotFound:"notFound",conflict:"conflict",idempotencyConflict:"conflict",idempotencyInFlight:"conflict",streamTimeout:"connection",streamIncomplete:"connection",upstreamLlmTimeout:"connection",serviceUnavailable:"connection",internalError:"server",notImplemented:"server",mediaUploadFailed:"media",moderationBlocked:"policy",unknown:"unknown"});function Kn(e){return cf[e]}i(Kn,"categoryFor");function Ie(e){let t=Or(e);if(t)return t.normalized;let r=(e??"").trim().toUpperCase(),n=r.replace(/[^A-Z0-9]/g,"");if(n==="AUTHREJECTED")return "authRejected";if(r.startsWith("AUTH"))return "authExpired";switch(n){case "DAILYQUOTAEXCEEDED":case "QUOTAEXCEEDED":return "quotaExceeded";case "RATELIMITED":case "TOOMANYREQUESTS":case "TELEVETRATELIMITED":return "rateLimited";case "IDEMPOTENCYKEYCONFLICT":case "IDEMPOTENCYCONFLICT":return "idempotencyConflict";case "ACCESSDENIED":case "FORBIDDEN":return "accessDenied";case "NOTFOUND":case "CONVERSATIONNOTFOUND":return "conversationNotFound";case "PETNOTFOUND":return "petNotFound";case "TIMEOUT":case "STREAMTIMEOUT":return "streamTimeout";case "MEDIAUPLOADFAILED":case "UNRECOGNIZEDVIDEOFORMAT":case "FILETOOSMALL":return "mediaUploadFailed";case "MODERATIONBLOCKED":return "moderationBlocked";case "UPSTREAMLLMTIMEOUT":return "upstreamLlmTimeout";case "INTERNALERROR":case "INTERNALSERVERERROR":return "internalError";case "STREAMINCOMPLETE":case "CHATSTREAMINCOMPLETE":return "streamIncomplete";case "INVALIDANALYSISTYPE":case "INVALIDUPLOADPURPOSE":return "unknown";default:return "unknown"}}i(Ie,"fromWire");function fa(e){return e===401?"authExpired":e===403?"accessDenied":e===404?"conversationNotFound":e===409?"idempotencyConflict":e===421?"unknown":e===429?"rateLimited":e===400||e===422?"unknown":e>=500?"internalError":"unknown"}i(fa,"fromHttpStatus");var pf=new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function je(e){return pf.has(e)}i(je,"isAutoRetryable");var ff=new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function Gn(e){return je(e)||ff.has(e)}i(Gn,"isRetryableCode");function Fr(e,t=false){return t||je(e)}i(Fr,"shouldRetry");var mf=500,qn=8e3,$t=4;function Mr(e,t=Math.random){let r=Math.max(0,e),n=Math.min(mf*2**r,qn);return Math.floor(t()*n)}i(Mr,"backoffDelayMs");function ma(e){return e==="conversationNotFound"}i(ma,"canRecreateOnNotFound");var ya=Object.freeze({shouldRetry(e,t){return je(e)&&t<$t},maxAttempts(){return $t}});var ga=Object.freeze({isAvailable:false,async capture(){return Promise.reject(new Error("CameraPort is unavailable; check isAvailable before calling capture"))}});function Je(e){throw new Error(`assertNever: unhandled discriminated-union member ${JSON.stringify(e)}`)}i(Je,"assertNever");function ha(e,t,r=null){return Object.freeze({kind:"accepted",streamId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(ha,"acceptedFrame");function ba(e,t=null){return Object.freeze({kind:"heartbeat",lastEventId:e,serverRequestId:t,terminal:false})}i(ba,"heartbeatFrame");function va(e,t,r=null){return Object.freeze({kind:"delta",delta:e,lastEventId:t,serverRequestId:r,terminal:false})}i(va,"deltaFrame");function Ea(e,t=null){return Object.freeze({kind:"done",terminal:true,conversationId:e.conversationId,messageId:e.messageId,title:e.title,followUpQuestions:Object.freeze([...e.followUpQuestions]),citations:Object.freeze([...e.citations]),citationStatus:e.citationStatus,urgencyLevel:e.urgencyLevel,urgencyReason:e.urgencyReason,urgencyProvided:e.urgencyProvided??e.urgencyLevel!==null,resultId:e.resultId,lastEventId:e.lastEventId,serverRequestId:t})}i(Ea,"doneFrame");function pe(e){return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryable,wireMessage:e.wireMessage,synthesized:e.synthesized,lastEventId:e.lastEventId,serverRequestId:e.serverRequestId??null})}i(pe,"errorFrame");function Ca(e,t,r=null){return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}i(Ca,"analysisStartedFrame");function Ra(e,t=null){return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}i(Ra,"analysisCompleteFrame");function Sa(e,t,r=null){return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}i(Sa,"unknownFrame");var hf=Object.freeze({authExpired:"Please sign in again to continue.",authRejected:"Please sign in again to continue.",sessionRequired:"This app needs to be updated to keep using Everfur.",accessDenied:"This feature isn't available on your account right now.",paymentRequired:"This is part of a paid plan.",quotaExceeded:"You have used today's messages. This resets tomorrow.",rateLimited:"You are sending messages quickly. Try again in a few seconds.",validationFailed:"Something in that request was not right. Check the details and try again.",sdkUpdateRequired:"This app needs to be updated to keep using Everfur.",conflict:"That is already running. Wait for it to finish, then try again.",idempotencyConflict:"That message was already delivered.",idempotencyInFlight:"That is still processing. Give it a moment.",conversationNotFound:"This conversation is no longer available.",petNotFound:"We could not find that pet. Please pick a pet and try again.",resourceNotFound:"We could not find that.",streamTimeout:"The response timed out. Tap retry to try again.",mediaUploadFailed:"We could not upload that photo. Please attach it again.",moderationBlocked:"This request cannot be answered here.",upstreamLlmTimeout:"The response timed out. Tap retry to try again.",internalError:"We hit a snag on our end. Please try again.",notImplemented:"That is not available yet.",serviceUnavailable:"That service is briefly unavailable. Try again shortly.",streamIncomplete:"The connection dropped mid-answer. Tap retry to continue.",unknown:"Something went wrong. Please try again."});function At(e){return hf[e]}i(At,"userFacingError");function xa(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false});}i(xa,"defineHidden");var bf=/^[a-z][a-z0-9_]{0,63}$/;function D(e,t){let r=Or(t?.wireCode,t?.wireEnvelope),n={code:e,category:Kn(e),retryable:t?.retryable??Gn(e),displayMessage:At(e)};if(t?.httpStatus!==void 0&&(n.httpStatus=t.httpStatus),t?.requestId&&(n.requestId=t.requestId),typeof t?.reasonCode=="string"&&bf.test(t.reasonCode)&&(n.reasonCode=t.reasonCode),r);return t?.wireMessage&&xa(n,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&xa(n,"raw",t.raw),Object.freeze(n)}i(D,"makeEverfurError");function Ta(e,t,r){let n=null,o=null,a=false,s=i(()=>o||(o=(async()=>{try{let l=await t(),u=typeof l=="string"?l:l?.token;if(typeof u!="string"||u.length===0)throw new J("invalid-argument","TokenProvider returned an empty token");return n=u,r?.(typeof l=="string"?null:vf(l.expiresAt)),u}finally{o=null;}})(),o),"load");return {userRef:e,async currentToken(l){if(a)throw new J("not-initialized","This identity was cleared (sign-out); mint a new one.");return l?.forceRefresh&&(n=null),n!==null?n:s()},hasToken(){return !a&&n!==null},clear(){a=true,n=null;}}}i(Ta,"createIdentityProvider");function vf(e){if(e===void 0)return null;let t=typeof e=="number"?e<1e11?e*1e3:e:new Date(e).getTime();return Number.isFinite(t)?t:null}i(vf,"expiryMs");function Xn(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let n=0;n<e.length;n+=1)e[n]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let n=0;n<e.length;n+=1)r.push(e[n].toString(16).padStart(2,"0"));return r.slice(0,4).join("")+"-"+r.slice(4,6).join("")+"-"+r.slice(6,8).join("")+"-"+r.slice(8,10).join("")+"-"+r.slice(10,16).join("")}i(Xn,"newSessionId");function Ef(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:t["x-everfur-partner-key"]=e.publishableKey,e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}i(Ef,"authHeaders");function Wt(e,t){return {...e,headers:{...Cf(e.headers),...Ef(t)}}}i(Wt,"withAuthHeaders");function Cf(e){if(!e)return {};let t={};for(let[r,n]of Object.entries(e)){let o=r.toLowerCase();o==="authorization"||o==="x-everfur-partner-key"||(t[r]=n);}return t}i(Cf,"stripAuthHeaders");async function ka(e,t){if(t.mode==="anonymous")return t.transport.request(Wt(e,{mode:"anonymous",publishableKey:t.publishableKey,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));let r;try{r=await t.identity.currentToken();}catch{return E(Yn())}let n=await t.transport.request(Wt(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let o;try{o=await t.identity.currentToken({forceRefresh:!0});}catch{return E(Yn())}let a=await t.transport.request(Wt(e,{mode:"personalized",token:o,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return !a.ok&&a.error.httpStatus===401?E(Yn(a.error.httpStatus)):a}i(ka,"authedSend");function Yn(e){return D("authRejected",{retryable:false,...e!==void 0?{httpStatus:e}:{}})}i(Yn,"authRejectedError");var Pa=`
2
2
 
3
- `,yf=1048576,gf=z$1.record(z$1.string(),z$1.unknown()),hf=["emergency","schedule_soon","home_care"];async function*Mr(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),a="",s=0,l=false;for await(let u of e){for(a+=o.decode(u,{stream:true});;){let d=a.indexOf(xa,s);if(d===-1)break;let c=a.slice(0,d);a=a.slice(d+xa.length),s=0;let p=Ta(c,n());if(p!==null&&(p.kind==="delta"&&(l=true),yield p,p.terminal))return}if(s=a.length>0?a.length-1:0,a.length>yf){yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(a+=o.decode(),a.trim().length>0){let u=Ta(a,n());if(u!==null&&(u.kind==="delta"&&(l=true),yield u,u.terminal))return}yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Mr,"parseSse");function Ta(e,t){let r=null,n=[];for(let s of e.split(`
3
+ `,Rf=1048576,Sf=z$1.record(z$1.string(),z$1.unknown()),xf=["emergency","schedule_soon","home_care"];async function*Dr(e,t=null){let r=null,n=i(()=>(r!==null||(r=typeof t=="function"?t():t),r),"requestIdNow"),o=new TextDecoder("utf-8"),a="",s=0,l=false;for await(let u of e){for(a+=o.decode(u,{stream:true});;){let c=a.indexOf(Pa,s);if(c===-1)break;let d=a.slice(0,c);a=a.slice(c+Pa.length),s=0;let p=_a(d,n());if(p!==null&&(p.kind==="delta"&&(l=true),yield p,p.terminal))return}if(s=a.length>0?a.length-1:0,a.length>Rf){yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(a+=o.decode(),a.trim().length>0){let u=_a(a,n());if(u!==null&&(u.kind==="delta"&&(l=true),yield u,u.terminal))return}yield pe({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});}i(Dr,"parseSse");function _a(e,t){let r=null,n=[];for(let s of e.split(`
4
4
  `)){let l=s.replace(/\s+$/,"");l.length===0||l.startsWith(":")||(l.startsWith("id:")?r=l.slice(3).trim():l.startsWith("data:")&&n.push(l.slice(5).replace(/^ /,"")));}if(n.length===0)return null;let o;try{o=JSON.parse(n.join(`
5
- `));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let a=gf.safeParse(o);return a.success?bf(a.data,r,t):null}i(Ta,"parseBlock");function bf(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return pe({code:le(e.code)??"unknown",retryable:e.retryable===true,wireMessage:le(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return ha({conversationId:le(e.conversation_id)??"",messageId:le(e.message_id),title:le(e.title),followUpQuestions:Cf(e.follow_up_questions),citations:ka(e.citations),citationStatus:le(e.citation_status),urgencyLevel:Pa(e.urgency_level),urgencyReason:le(e.urgency_reason),urgencyProvided:Ef(e),resultId:le(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return ma(le(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return ya(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let a=le(e.delta)??le(e.token)??"";return ga(a,t,r)}return o==="analysis_started"?ba(le(e.request_id),t,r):o==="analysis_complete"?va({resultId:le(e.result_id),analysisType:le(e.analysis_type),modelVersion:le(e.model_version),confidence:vf(e.confidence),detections:ka(e.detections),interpretation:le(e.interpretation),lastEventId:t},r):Ea(e,t,r)}i(bf,"frameFromWire");function le(e){return typeof e=="string"?e:null}i(le,"asString");function vf(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(vf,"asNumber");function Pa(e){return typeof e=="string"&&hf.includes(e)?e:null}i(Pa,"asUrgency");function Ef(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Pa(t)!==null}i(Ef,"urgencySlotProvided");function Cf(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(Cf,"asStringList");function Sf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(Sf,"isPlainObject");function ka(e){return Array.isArray(e)?e.filter(Sf):[]}i(ka,"asMapList");var Rf="0.5.0",xf="react-native",Tf="2026-09-19",_a="EVERFUR_API_BASE_URL";function $t(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i($t,"configFailure");function Qn(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(Qn,"checkPublishableKey");function wa(e,t){let r=Qn(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=kf(e.apiBaseUrl);if(!o.ok)return o;let a=e.contractVersion?.trim()||Tf;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:a,sdkVersion:Rf,platform:t?.platform??xf,debug:e.debug===true})})}i(wa,"tryResolveClientConfig");function kf(e){let t=e?.trim(),r=t&&t.length>0?t:Mf(_a);return r?Of(r):$t("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${_a}. The SDK never ships a hardcoded host.`)}i(kf,"tryResolveApiBaseUrl");function Ia(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(Ia,"buildBaseHeaders");var Pf=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function _f(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(_f,"hostOf");function wf(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(wf,"isPrintableHost");function If(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:wf(t)}i(If,"canEchoOrigin");function Af(e,t){return `${e}://${t}`}i(Af,"safeOrigin");function Of(e){let t=e.trim(),r=Pf.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return $t("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=_f(r[2]);if(o.length===0)return $t("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let a=If(t,o)?`: ${Af(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&Ff(o)))return n==="http"?$t("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${a}`):$t("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${a}`)}let s=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:s})}i(Of,"normalizeBaseUrl");function Ff(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(Ff,"isLoopbackHost");function Mf(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i(Mf,"readEnv");var Df=3e4,Ma="x-request-id";async function*Aa(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(Aa,"fetchByteSource");function Lf(e){let t=new TextEncoder,r=Uf(),n=false,o=i(u=>{let d="";u.lastEventId&&(d+=`id: ${u.lastEventId}
6
- `);let c=u.data??"";for(let p of c.split(`
7
- `))d+=`data: ${p}
8
- `;d+=`
9
- `,r.push(t.encode(d));},"onMessage"),a=i(()=>{l(),r.end();},"onDone"),s=i(u=>{let d=typeof u.xhrStatus=="number"?u.xhrStatus:0;if(d>=400){let c=Na(d),p=je(Ie(c));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:c,retryable:p})}
5
+ `));}catch{return null}if(typeof o!="object"||o===null||Array.isArray(o))return null;let a=Sf.safeParse(o);return a.success?Tf(a.data,r,t):null}i(_a,"parseBlock");function Tf(e,t,r){let n=e.type,o=e.event;if(n==="error"||"error"in e)return pe({code:le(e.code)??"unknown",retryable:e.retryable===true,wireMessage:le(e.error),synthesized:false,lastEventId:t,serverRequestId:r});if(n==="done"||e.done===true)return Ea({conversationId:le(e.conversation_id)??"",messageId:le(e.message_id),title:le(e.title),followUpQuestions:_f(e.follow_up_questions),citations:wa(e.citations),citationStatus:le(e.citation_status),urgencyLevel:Ia(e.urgency_level),urgencyReason:le(e.urgency_reason),urgencyProvided:Pf(e),resultId:le(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return ha(le(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return ba(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let a=le(e.delta)??le(e.token)??"";return va(a,t,r)}return o==="analysis_started"?Ca(le(e.request_id),t,r):o==="analysis_complete"?Ra({resultId:le(e.result_id),analysisType:le(e.analysis_type),modelVersion:le(e.model_version),confidence:kf(e.confidence),detections:wa(e.detections),interpretation:le(e.interpretation),lastEventId:t},r):Sa(e,t,r)}i(Tf,"frameFromWire");function le(e){return typeof e=="string"?e:null}i(le,"asString");function kf(e){return typeof e=="number"&&Number.isFinite(e)?e:null}i(kf,"asNumber");function Ia(e){return typeof e=="string"&&xf.includes(e)?e:null}i(Ia,"asUrgency");function Pf(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||Ia(t)!==null}i(Pf,"urgencySlotProvided");function _f(e){return Array.isArray(e)?e.map(t=>typeof t=="string"?t:String(t)):[]}i(_f,"asStringList");function wf(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(wf,"isPlainObject");function wa(e){return Array.isArray(e)?e.filter(wf):[]}i(wa,"asMapList");var If="0.5.2",Af="react-native",Of="2026-09-19",Aa="EVERFUR_API_BASE_URL";function Kt(e,t){return Object.freeze({ok:false,failure:Object.freeze({reason:e,message:t})})}i(Kt,"configFailure");function Zn(e){let t=typeof e=="string"?e.trim():"";return t.length===0?{reason:"missing-publishable-key",message:"publishableKey is required"}:/^sk[_-]/i.test(t)?{reason:"secret-key-as-publishable-key",message:"publishableKey looks like a SECRET key (sk_...). A device must never hold a partner secret key: use the pk_ publishable key here, and keep the secret key on your server."}:null}i(Zn,"checkPublishableKey");function Oa(e,t){let r=Zn(e?.publishableKey);if(r!==null)return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=Ff(e.apiBaseUrl);if(!o.ok)return o;let a=e.contractVersion?.trim()||Of;return Object.freeze({ok:true,config:Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:a,sdkVersion:If,platform:t?.platform??Af,debug:e.debug===true})})}i(Oa,"tryResolveClientConfig");function Ff(e){let t=e?.trim(),r=t&&t.length>0?t:Bf(Aa);return r?Uf(r):Kt("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${Aa}. The SDK never ships a hardcoded host.`)}i(Ff,"tryResolveApiBaseUrl");function Fa(e){return {"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion}}i(Fa,"buildBaseHeaders");var Mf=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function Df(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}i(Df,"hostOf");function Lf(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}i(Lf,"isPrintableHost");function Nf(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:Lf(t)}i(Nf,"canEchoOrigin");function Hf(e,t){return `${e}://${t}`}i(Hf,"safeOrigin");function Uf(e){let t=e.trim(),r=Mf.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return Kt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=Df(r[2]);if(o.length===0)return Kt("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let a=Nf(t,o)?`: ${Hf(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&zf(o)))return n==="http"?Kt("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${a}`):Kt("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${a}`)}let s=t.endsWith("/")?t.slice(0,-1):t;return Object.freeze({ok:true,value:s})}i(Uf,"normalizeBaseUrl");function zf(e){let t=e.toLowerCase();return t==="localhost"||t==="127.0.0.1"||t==="[::1]"||t==="::1"}i(zf,"isLoopbackHost");function Bf(e){let r=globalThis.process?.env?.[e];return typeof r=="string"&&r.trim().length>0?r.trim():void 0}i(Bf,"readEnv");var jf=3e4,Na="x-request-id";async function*Ma(e){if(!e)return;let t=e.getReader();try{for(;;){let{done:r,value:n}=await t.read();if(r)break;n&&n.length>0&&(yield n);}}finally{await t.cancel?.();}}i(Ma,"fetchByteSource");function Vf(e){let t=new TextEncoder,r=Wf(),n=false,o=i(u=>{let c="";u.lastEventId&&(c+=`id: ${u.lastEventId}
6
+ `);let d=u.data??"";for(let p of d.split(`
7
+ `))c+=`data: ${p}
8
+ `;c+=`
9
+ `,r.push(t.encode(c));},"onMessage"),a=i(()=>{l(),r.end();},"onDone"),s=i(u=>{let c=typeof u.xhrStatus=="number"?u.xhrStatus:0;if(c>=400){let d=za(c),p=je(Ie(d));r.push(t.encode(`data: ${JSON.stringify({type:"error",code:d,retryable:p})}
10
10
 
11
- `));}l(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",a),e.addEventListener("error",s);function l(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",a),e.removeEventListener("error",s);try{e.close();}catch{}}}return i(l,"cleanup"),Nf(r.source,l)}i(Lf,"eventSourceByteSource");async function*Nf(e,t){try{yield*e;}finally{t();}}i(Nf,"sourceWithCleanup");function Uf(){let e=[],t=false,r=null,n=i(()=>{if(r){let a=r;r=null,a();}},"signal");async function*o(){for(;;){let a=e.shift();if(a!==void 0){yield a;continue}if(t)return;await new Promise(s=>{r=s;});}}return i(o,"gen"),{source:o(),push:i(a=>{e.push(a),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(Uf,"createByteQueue");async function Hf(e,t){let r=t.fetchImpl??Ua(),n=Ha(t.config.apiBaseUrl,e.path,e.query),o=za(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),a=Wf(Df),s=Kf(a.signal,e.signal),l;try{l=await r(n,Ba({...e,signal:s},o));}catch(d){return E(Zn(d))}finally{a.cancel();}let u=await ja(l);return l.ok?M(u):E(jf(l.status,u,La(l)))}i(Hf,"requestJson");function Da(e){return {request:i(t=>Hf(t,e),"request"),stream:i((t,r)=>zf($f(t,r),e),"stream")}}i(Da,"createHttpTransport");async function*zf(e,t){let r=Ha(t.config.apiBaseUrl,e.path,e.query),n=za(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,Bf(e,n));yield*Mr(Lf(l),()=>Vf(l));return}let o=t.fetchImpl??Ua(),a;try{a=await o(r,Ba(e,n));}catch(l){yield Oa("",true,Ka(l));return}let s=La(a);if(!a.ok){let l=await ja(a),u=Va(l)??Na(a.status),d=Wa(l)||je(Ie(u));yield Oa(u,d,$a(l),s);return}if(a.body){yield*Mr(Aa(a.body),s);return}yield*Mr(Aa(null),s);}i(zf,"streamFrames");function Bf(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(Bf,"buildEventSourceInit");function jf(e,t,r){let n=Va(t),o=n?Ie(n):da(e),a=$a(t);return D(o,{httpStatus:e,...Wa(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...Fa(t)?{reasonCode:Fa(t)}:{},...a?{wireMessage:a}:{},...t!=null?{raw:t}:{}})}i(jf,"errorFromResponse");function Zn(e){return D("internalError",{retryable:true,wireMessage:Ka(e)})}i(Zn,"networkError");function La(e){let t=e.headers.get(Ma);return typeof t=="string"&&t.length>0?t:null}i(La,"requestIdOf");function Vf(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Ma);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(Vf,"eventSourceRequestId");function Na(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(Na,"statusToWireCode");function Oa(e,t,r,n=null){return pe({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(Oa,"syntheticErrorFrame");function Ua(){let e=globalThis.fetch;if(typeof e!="function")throw new J("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Ua,"getGlobalFetch");function Ha(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let a=Object.entries(r).filter(s=>s[1]!==void 0).map(([s,l])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(l))}`).join("&");a&&(o+=`?${a}`);}return o}i(Ha,"buildUrl");function za(e,t,r,n){let o={...Ia(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(za,"mergeHeaders");function Ba(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i(Ba,"buildInit");function $f(e,t){return e.signal?e:{...e,signal:t}}i($f,"withSignal");function Wf(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(Wf,"timeoutSignal");function Kf(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Kf,"mergeAbortSignals");async function ja(e){try{return await e.json()}catch{return null}}i(ja,"safeJson");function Fa(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(Fa,"extractReasonCode");function Va(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Va,"extractWireCode");function $a(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i($a,"extractWireMessage");function Wa(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(Wa,"extractRetryable");function Ka(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Ka,"describeCause");var Gf=3e4,qf=Gn*2,Yf="idempotency-key",Xf=new Set(["POST","PUT","PATCH","DELETE"]),Qf=Object.freeze({onEvent(){}}),Zf=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Jf(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(Jf,"seededIdempotencyKey");function Te(e){let t=e.observer??Qf,r=e.timers??Zf,n=e.rng??Math.random,o=e.sleep??((f,m)=>pm(f,r,m)),a=e.maxAttempts??jt,s=e.unaryTimeoutMs??Gf,l=e.newIdempotencyKey??tm(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function d(f,m,y){let S=y?.maxAttempts,g=Math.max(1,S??a),T=y?.idempotent??Xf.has(m.method),R=y?.idempotencyKey===void 0?null:Jf(y.idempotencyKey),_=T?R??l():null,w=em(m,_),b=0;for(;;){let x=i(O=>Object.freeze({call:f,method:m.method,path:m.path,attempt:b,..._?{idempotencyKey:_}:{},...O}),"stamp");u(x({phase:"attempt"}));let A=dm(s,r),F=cm(A.signal,m.signal),P;try{P=await Ra({...w,signal:F.signal},e.auth);}catch(O){P=E(Zn(O));}finally{F.dispose(),A.cancel();}if(P.ok)return u(x({phase:"settled",ok:true,reason:"ok"})),P;let v=P.error,C=nm(v,b,{maxAttempts:g,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...S!==void 0?{perCallMaxAttempts:S}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),I={ok:false,code:v.code,reason:C.reason,...v.httpStatus!==void 0?{httpStatus:v.httpStatus}:{},...v.requestId!==void 0?{requestId:v.requestId}:{}};if(!C.retry)return u(x({phase:"settled",...I})),E(v);if(u(x({phase:"retry",...I,delayMs:C.delayMs})),await o(C.delayMs,m.signal),m.signal?.aborted===true)return u(x({phase:"settled",...I,reason:"aborted"})),E(v);b+=1;}}i(d,"send");async function c(f){return Vt(f,await um(e.auth))}i(c,"authorize");async function*p(f,m,y){u(Object.freeze({call:f,phase:"stream.open",method:m.method,path:m.path,attempt:0}));try{yield*e.auth.transport.stream(m,y);}catch{yield pe({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:d,authorize:c,stream:p})}i(Te,"createRequestFunnel");function em(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==Yf&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(em,"assembleHeaders");function tm(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(tm,"defaultIdempotencyKeyFactory");var rm=10;function nm(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=om(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!je(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let s=i(()=>{if(r.policy===void 0)return null;let d;try{d=r.policy.maxAttempts(e.code);}catch{return null}return typeof d!="number"||!Number.isFinite(d)?null:Math.max(1,Math.min(rm,Math.floor(d)))},"policyCeiling"),l=r.perCallMaxAttempts??s()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=im(e,r.now);return u!==null?u>qf?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Fr(t,r.rng)}}i(nm,"decideRetry");function om(e){let t=e.code==="unknown"?Ie(lm(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(om,"throttleKind");function im(e,t){let r=am(e.raw);if(r===null)return null;let n=r-t;return n>0?n:0}i(im,"retryOverrideMs");function am(e){for(let t of qa(e)){let r=t.resets_at,n=sm(r);if(n!==null)return n}return null}i(am,"findResetsAt");function qa(e){if(!Ga(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Ga(n)&&t.push(n);}return t}i(qa,"candidateScopes");function sm(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(sm,"parseInstantMs");function lm(e){for(let t of qa(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(lm,"rawWireCode");function Ga(e){return typeof e=="object"&&e!==null}i(Ga,"isRecord");async function um(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(um,"resolveDeviceAuth");function dm(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(dm,"boundedSignal");function cm(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(cm,"mergeSignals");function pm(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",a),n();},e),a=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",a,{once:true});})}i(pm,"delayAbortable");function Ee(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(Ee,"hasLoneSurrogate");function ct(e){return [...e].length}i(ct,"serverLength");var Dr=Object.freeze(["better","same","worse"]),eo=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Ya(e){return E(D("validationFailed",{retryable:false,wireMessage:e}))}i(Ya,"invalid");function Jn(){return E(D("internalError",{retryable:false}))}i(Jn,"malformed");function Xa(e){return typeof e!="string"||e.trim().length===0?D("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Ee(e)?D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(Xa,"petPath");var Ve=i(e=>typeof e=="string"?e:null,"str"),Qa=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function Za(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ve(t.case_id),n=Ve(t.status);if(r===null||n===null)return null;let o=Ve(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:Ve(t.body_location),lastResponse:o!==null&&Dr.includes(o)?o:null,checkInDueAt:Ve(t.check_in_due_at),openedAt:Ve(t.opened_at),resolvedAt:Ve(t.resolved_at),resolutionText:Ve(t.resolution_text),checkinAskCount:Qa(t.checkin_ask_count),checkinAnswerCount:Qa(t.checkin_answer_count)})}i(Za,"caseFromWire");function Ja(e){return {async list(t,r){let n=Xa(t);if(typeof n!="string")return E(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return E(o.error);let a=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(a))return Jn();let s=a.map(Za);return s.every(l=>l!==null)?M(Object.freeze(s)):Jn()},async checkin(t,r,n,o){let a=Xa(t);if(typeof a!="string")return E(a);if(typeof r!="string"||!eo.test(r))return Ya("case_id must be a UUID");if(!Dr.includes(n))return Ya("response must be one of better, same, worse");let s=await e.send("cases.checkin",{method:"POST",path:`${a}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!s.ok)return E(s.error);let l=typeof s.value=="object"&&s.value!==null?s.value:{},u=Za(l.case);return u===null?Jn():M(Object.freeze({case:u,ctaDeepLink:Ve(l.cta_deep_link)}))}}}i(Ja,"createCasesRepositoryOver");var es=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var ts=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Nr(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},a=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",a),n();},"done");o.handle=r.setTimeout(a,e),t.addEventListener("abort",a,{once:true});})}i(Nr,"delayAbortable");function Ur(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Ur,"mergeSignals");var to=class to{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?Ur(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(to,"MediaStore");var Lr=to;function no(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(no,"makeUser");function oo(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(oo,"makeAssistant");function Kt(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(Kt,"stripPending");function rs(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(rs,"appendText");function io(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(io,"finalizeAssistant");function ns(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(ns,"freezeSnapshot");function L(e,t,r){return D(e,{retryable:t,...r?{wireMessage:r}:{}})}i(L,"makeError");function ao(e){let t=Ie(e.code);return D(t,{retryable:e.retryable||Or(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(ao,"errorFromFrame");function Ae(e){return pe({code:fm(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Ae,"synthErrorFrame");function fm(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return Je(e)}}i(fm,"canonicalWireCode");function os(e){let t=Array.isArray(e)?e:ro(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!ro(n))continue;let o=Wt(n.category)??Wt(n.title)??"",a=mm(n.prompts??n.questions);o.length===0&&a.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(a)}));}return Object.freeze(r)}i(os,"parsePromptCategories");function so(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let a=o.trim();a.length===0||t.has(a)||(t.add(a),r.push(a));}return r}i(so,"flattenPrompts");function ro(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(ro,"isPlainObject");function Wt(e){return typeof e=="string"?e:null}i(Wt,"asStr");function mm(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(ro(r)){let n=Wt(r.text)??Wt(r.prompt)??Wt(r.title);n!==null&&t.push(n);}return t}i(mm,"asPromptTextList");function is(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(is,"defaultIdFactory");function as(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(as,"defaultIdempotencyFactory");var ls={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*us(e,t,r,n){let o=e[Symbol.asyncIterator](),a=ss(t.overallMs,n),s=ss(t.idleMs,n),l=hm(r);try{for(;;){if(r.aborted)return;let u=o.next().then(p=>({tag:"next",value:p}),()=>({tag:"streamError"})),d=await Promise.race([u,s.promise.then(()=>({tag:"idle"})),a.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(d.tag==="abort")return;if(d.tag==="streamError"){if(r.aborted)return;yield gm();return}if(d.tag==="idle"||d.tag==="overall"){yield ym();return}let c=d.value;if(c.done||(s.reset(t.idleMs),yield c.value,c.value.terminal))return}}finally{s.cancel(),a.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(us,"withWatchdog");function ym(){return pe({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(ym,"synthTimeoutFrame");function gm(){return pe({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(gm,"synthStreamErrorFrame");function ss(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(a=>{r=a;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(a){t.clearTimeout(o),o=t.setTimeout(()=>r(),a);},cancel(){t.clearTimeout(o);}}}i(ss,"deadline");function hm(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(hm,"abortPromise");var ds=128,cs=128,ps=/[\u0000-\u001F\u007F]/,bm=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function vm(e){let t=e,r=ct(t);if(r===0||r>cs)throw new J("invalid-argument",`petRef must be 1..${cs} characters`);if(ps.test(t))throw new J("invalid-argument","petRef must be printable (no control characters)");return t}i(vm,"petRef");function Em(e){let t=e,r=ct(t);if(r===0||r>ds)throw new J("invalid-argument",`userRef must be 1..${ds} characters`);if(t.includes("@"))throw new J("invalid-argument","userRef must not contain '@'");if(ps.test(t))throw new J("invalid-argument","userRef must be printable (no control characters)");return t}i(Em,"userRef");function Cm(e){if(!bm.test(e))throw new J("invalid-argument","conversationId must be a UUID");return e}i(Cm,"conversationId");var Sm="checkin",Rm=/^\d{4}-\d{2}-\d{2}$/,Hr="watching";function fs(e){return e.status!=null&&e.status!==Hr}i(fs,"isCheckinSettled");function ms(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(ms,"isLiveAskAnswered");function lo(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Sm||n===void 0||o===void 0||!eo.test(n)||!Rm.test(o)?null:{caseId:n,dueDay:o}}i(lo,"parseCheckinOrigin");function ys(e){return lo(e)?.caseId??null}i(ys,"parseCheckinOriginRef");function uo(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return E(D("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||Ee(o))return E(D("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),M(r.length?`?${r.join("&")}`:"")}i(uo,"historyQuery");function Yt(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(Yt,"validConversationId");function qt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(qt,"object");function gs(e){return e==null||typeof e=="string"&&e.length>0&&!Ee(e)}i(gs,"cursor");function Gt(){return E(D("internalError",{retryable:false}))}i(Gt,"malformed");function hs(e){let t=qt(e);if(!t||!Array.isArray(t.conversations)||!gs(t.next_cursor))return Gt();let r=[];for(let n of t.conversations){let o=qt(n);if(!o||typeof o.conversation_id!="string"||!Yt(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return Gt();let a=o.unread_message_count;if(!(a==null||Number.isInteger(a)&&a>=0))return Gt();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:a??null}));}return M(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(hs,"mapConversationPage");function bs(e){let t=qt(e);if(!t||!Array.isArray(t.messages)||!gs(t.next_cursor))return Gt();let r=[],n=new Set;for(let o of t.messages){let a=qt(o);if(!a||typeof a.message_id!="string"||!Yt(a.message_id)||typeof a.role!="string"||typeof a.content!="string"||typeof a.created_at!="string")return Gt();if(a.role!=="user"&&a.role!=="assistant"||n.has(a.message_id))continue;n.add(a.message_id);let s=typeof a.proactive_origin_ref=="string"?a.proactive_origin_ref:null,l=a.role==="assistant"?ys(s):null;r.push(Object.freeze({id:a.message_id,role:a.role,text:a.content,createdAt:a.created_at,...a.role==="assistant"?{responseId:a.message_id}:{},...a.urgency_level!==void 0?{urgencyLevel:xm(a.urgency_level)}:{},...Array.isArray(a.citations)?{citations:Tm(a.citations)}:{},...s!==null?{proactiveOriginRef:s}:{},...l!==null?{checkin:Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}));}return M(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(bs,"mapMessagePage");function xm(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(xm,"normalizeUrgency");function Tm(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=qt(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let a of t){let s=n[a];(typeof s=="string"||s===null)&&(o[a]=s);}return [Object.freeze(o)]}))}i(Tm,"historyCitations");var co=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Xt=4e3;var pt=4e3;function vs(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:L("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:L("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(vs,"validateImageKeys");function fo(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:L("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>pt?{reason:"too_long",error:L("validationFailed",false,`message is ${r} characters; the server accepts at most ${pt}`)}:null}i(fo,"validateMessageText");function Es(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Es,"urgencyTier");async function*Qt(e){yield e;}i(Qt,"singleFrameStream");async function*Cs(){}i(Cs,"emptyStream");var km=6e4,Pm=18e4,_m=24,wm=512,Im=false;function Ss(e){return new mo(e)}i(Ss,"createChatController");var yo=class yo extends Lr{constructor(r){super(ns({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??Te({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=Ja(this.funnel),this.telemetry=r.telemetry??Ir,this.errorPolicy=r.errorPolicy??pa,this.timers=r.timers??ls,this.rng=r.rng??Math.random,this.newId=r.newId??is(),this.makeIdempotencyKey=r.makeIdempotencyKey??as(),this.budget={idleMs:r.budget?.idleMs??km,overallMs:r.budget?.overallMs??Pm};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let a=n??{};if(this.disposed||this.snapshot.isBootstrapping){let u=L(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(u),()=>{}):Qt(Ae(u))}let s=fo(r)??vs(a.imageS3Keys);if(s!==null)return this.telemetry.track("chat.send.rejected",{reason:s.reason}),this.patch({status:"error",isStreaming:false,error:s.error}),o?(o.onError(s.error),()=>{}):Qt(Ae(s.error));if(o)return this.driveWithHandlers(r,a,o);let l=this.beginTurn(r,a);return this.runTurn(l,a.signal)}askEverfur(r,n){if(this.disposed)return Qt(Ae(L("accessDenied",false)));let o=fo(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),Qt(Ae(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let a=this.snapshot.conversationId;return a!==null&&this.snapshot.status==="error"?this.retryHistory(a):Cs()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(a=>a.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,no(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?Kt(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=[],this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:[],historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(so(r));this.bootstrapPrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=uo(r,100);if(!o.ok)return o;let a=this.epoch;if(this.disposed)return E(L("accessDenied",false));let s=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(a)||this.disposed)return E(L("accessDenied",false));if(!s.ok)return s;let l=hs(s.value);if(l.ok){for(let c of l.value.conversations)c.unreadCount!==null&&this.unreadByConversation.set(c.id,c.unreadCount);let u=this.snapshot.conversationId,d=u===null?void 0:this.unreadByConversation.get(u);d!==void 0&&d!==this.snapshot.unreadCount&&this.patch({unreadCount:d}),this.reflectUnreadDot();}return l}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return E(L("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?M(n):E(u.error)}let o=r?.petRef??this.petRef,a=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!a.ok)return E(a.error);let s=a.value.conversations[0];if(s===void 0)return M(null);let l=await this.resumeConversation(s.id);return l.ok?M(s.id):E(l.error)}async markRead(r){if(this.disposed)return E(L("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return M(void 0);let o=this.epoch,a=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?E(L("accessDenied",false)):a.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),M(void 0)):E(a.error)}async submitFeedback(r,n,o,a){if(this.disposed)return E(L("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Ee(r))return E(L("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!co.includes(n))return E(L("validationFailed",false,`feedback_type must be one of ${co.join(", ")}`));let s=typeof o=="string"?o.trim():"";if([...s].length>Xt)return E(L("validationFailed",false,`notes is over ${Xt} characters`));let l={feedback_type:n};s.length>0&&(l.notes=s);let u=this.epoch,d=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:l},a?.signal);if(!this.alive(u)||this.disposed)return E(L("accessDenied",false));if(!d.ok)return E(d.error);let c=d.value?.feedback_id;return M(Object.freeze({feedbackId:typeof c=="string"?c:""}))}async answerCheckin(r,n,o){if(this.disposed)return E(L("accessDenied",false));let a=o?.petRef??this.petRef;if(a===null)return E(L("validationFailed",false,"a check-in needs the pet the case belongs to"));let s=this.epoch,l=await this.cases.checkin(a,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(s)||this.disposed)return E(L("accessDenied",false));if(!l.ok)return l;let u=l.value.case.openedAt,d=Object.freeze({caseId:r,answer:n,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...u!==null?{openedAt:u}:{}}),c=i(p=>p.checkin?.caseId===r,"carries");return this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,checkin:d}):p)}),l}async getMessages(r,n){if(!Yt(r))return E(L("validationFailed",false));let o=uo(n,200);if(!o.ok)return o;let a=this.epoch;if(this.disposed)return E(L("accessDenied",false));let s=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(a)||this.disposed?E(L("accessDenied",false)):s.ok?bs(s.value):s}async resumeConversation(r){if(this.disposed)return E(L("accessDenied",false));if(!Yt(r))return E(L("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return E(L("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let a=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:a}),this.stampCheckinStatuses(n),a!==null&&a>0&&this.markRead(),M(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(d=>d.checkin!==void 0&&d.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let a=new Set(o.value.filter(d=>d.status===Hr).map(d=>d.caseId)),s=new Map(o.value.map(d=>[d.caseId,d])),l=false,u=this.snapshot.messages.map(d=>{let c=d.checkin;if(c===void 0||c.status!==null)return d;l=true;let p=s.get(c.caseId),f=c.openedAt??p?.openedAt??null,m=a.has(c.caseId),y=p!==void 0&&(!m||ms({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...d,checkin:Object.freeze({...c,status:m?Hr:p?.status??"resolved",answer:c.answer??y,resolutionText:c.resolutionText??p?.resolutionText??null,...f!==null?{openedAt:f}:{}})})});l&&this.patch({messages:u});}async refreshActiveThread(){if(this.disposed)return E(L("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return M(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return E(L("accessDenied",false));if(!o.ok)return E(o.error);let a=new Set(this.snapshot.messages.map(l=>l.id)),s=o.value.messages.filter(l=>!a.has(l.id));return s.length>0&&this.patch({messages:[...this.snapshot.messages,...s]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),M(void 0)}async loadOlderMessages(){if(this.disposed)return E(L("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return M(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let a=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return E(L("accessDenied",false));if(this.patch({isLoadingHistory:false}),!a.ok)return a;let s=new Set(this.snapshot.messages.map(u=>u.id)),l=a.value.messages.filter(u=>!s.has(u.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:a.value.nextCursor===n?null:a.value.nextCursor}),M(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield Ae(n.error));}async primeConversation(r){if(this.disposed)return E(L("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let a=await o.settled;return this.disposed?E(L("accessDenied",false)):(!a.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),a)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return M(n);let o=this.snapshot.conversationId;return o!==null?M(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return E(L("accessDenied",false));let o=r?.petRef??null,a={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=a;let s=await a.settled;return !this.alive(n)||this.disposed?E(L("accessDenied",false)):(!s.ok&&this.unadoptedCreate===a&&(this.unadoptedCreate=null),s)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},a=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!a.ok)return E(a.error);let s=a.value?.conversation_id??a.value?.id;return typeof s!="string"||s.length===0?E(L("internalError",true)):M(s)}async getPrompts(r){let n=this.epoch;if(this.disposed)return E(L("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Ee(o))return E(D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let a=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",s=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${a}`});return !this.alive(n)||this.disposed?E(L("accessDenied",false)):s.ok?M(os(s.value)):E(s.error)}async authedUnary(r,n,o,a){return this.funnel.send(r,o?{...n,signal:o}:n,a)}driveWithHandlers(r,n,o){let a=new AbortController,s=Ur(a.signal,n.signal),l=this.beginTurn(r,n),u=this.runTurn(l,s),d=false,c=i(()=>{d||(d=true,a.abort(),this.handlerTeardowns.delete(c));},"teardown");return this.handlerTeardowns.add(c),(async()=>{for await(let p of u){if(d)break;o.onFrame(p),p.kind==="done"&&o.onDone(this.lastResponseIdValue);}!d&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(c);})(),c}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,no(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let a=0,s=false,l=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let u=r.conversationIdOverride===null&&this.snapshot.conversationId===null,d=u?this.unadoptedCreate:null;if(d!==null&&(r.petRef===null||r.petRef===d.petRef)){let g=await d.settled;if(o.signal.aborted||!this.alive(o.epoch))return;g.ok&&this.snapshot.conversationId===null&&this.adoptConversation(g.value);}if(u&&this.snapshot.conversationId===null){let g=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!g.ok){yield*this.emitTerminal(r,g.error,Ae(g.error));return}this.adoptConversation(g.value);}let c=r.conversationIdOverride??this.snapshot.conversationId;if(c===null){let g=L("internalError",!0);yield*this.emitTerminal(r,g,Ae(g));return}this.clearAssistantInProgress(r);let p=new AbortController,f=Ur(o.signal,p.signal),m=null;try{let g;try{g=await this.funnel.authorize(this.buildSendRequest(r,c));}catch{let R=this.authRejected();yield*this.emitTerminal(r,R,Ae(R));return}if(o.signal.aborted||!this.alive(o.epoch))return;let T=this.funnel.stream("chat.send",g,f);for await(let R of us(T,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(R.kind==="error"&&R.terminal){m=R;break}if(this.applyFrame(R,r),yield R,R.terminal){o.settle();return}}}finally{p.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(m===null){if(this.snapshot.status==="complete")return;let g=L("streamIncomplete",!0);yield*this.emitTerminal(r,g,Ae(g));return}let y=Ie(m.code);if(y==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let g=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!g){let T=this.authRejected();yield*this.emitTerminal(r,T,m);return}this.patch({reconnecting:!0});continue}if(y==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let g=this.authRejected();yield*this.emitTerminal(r,g,m);return}if(y==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,ao(m),m);return}if(ca(y)&&!s){s=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let S=m.retryable&&Or(y,!0);if(Im&&S&&a+1<this.errorPolicy.maxAttempts(y));yield*this.emitTerminal(r,ao(m),m);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return Je(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let a=this.snapshot.messages.map(s=>s.id===n.userMessageId&&s.pending===true?Kt(s):s);this.patch({status:"streaming",isStreaming:true,messages:[...a,oo(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=wm){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},_m);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let a=this.snapshot.messages.map(s=>s.id===o?rs(s,n):s);this.patch({messages:a});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,a;if(n.assistantMessageId!==null)a=this.snapshot.messages.map(l=>l.id===n.assistantMessageId?io(l,r):l);else {let l=this.newId();n.assistantMessageId=l,n.sawDelta=true,a=[...this.snapshot.messages.map(d=>d.id===n.userMessageId&&d.pending===true?Kt(d):d),io(oo(l,"",this.stamp()),r)];}let s=so([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=s.length>0?Object.freeze(s):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:a,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let a=this.epoch,s=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!l.ok||!this.alive(a)||this.disposed||s!==this.historyGeneration||this.snapshot.conversationId!==r)return;let u=Es(l.value?.urgency),d=typeof l.value?.reason=="string"?l.value.reason:null,c=i(p=>p.responseId===n,"carries");this.snapshot.messages.some(c)&&this.patch({messages:this.snapshot.messages.map(p=>c(p)?Object.freeze({...p,urgencyLevel:u,urgencyReason:d,urgencyProvided:true}):p)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(a=>a.id===r.userMessageId&&a.pending===true?Kt(a):a);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(a=>a.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return L("authRejected",false)}};i(yo,"ChatControllerImpl");var mo=yo;async function Ts(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,a=[],s=false,l=false,u=false,d=null,c=null,p=o?r.resumeConversation(o).then(w=>w.ok?M(o):w):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[m,y]=await Promise.all([p,f]),S=null;if(m.ok)S=m.value,a.push(m.value),r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let w=m.error;c=w,Rs(w)?(l=true,d=w):(xs(w)&&(s=true),u=true);}let g=[];y.ok?g=y.value:T(y.error);function T(w){Rs(w)?(l=true,d===null&&(d=w)):xs(w)&&(s=true);}i(T,"recordAuthSignals");let R=d!==null?d.displayMessage:null;return Object.freeze({conversationId:S,petRef:n,suggestedPrompts:g,error:R,warning:R===null&&S===null&&u?Am:null,cause:d??c,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...a]),sawForbidden:s,sawUnauthorized:l,sawConversationInitFailure:u})})}i(Ts,"bootstrapChat");var Am="Chat is ready. Your first message will start the conversation.";function Rs(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(Rs,"isUnauthorized");function xs(e){return e.httpStatus===403||e.code==="accessDenied"}i(xs,"isForbidden");var go=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function ks(e){return e!==go}i(ks,"isUploadTransportAvailable");var Om=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),_s="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",zr=10*1024*1024,Br=5,Zt=120,Fm="/widget/v1/uploads/initiate";function Mm(e){return typeof e=="string"&&Om.includes(e.trim().toLowerCase())}i(Mm,"isAttachmentMime");function Dm(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=Zt)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,Zt);let n=t.slice(r);return n.length>=Zt?t.slice(0,Zt):`${t.slice(0,r).slice(0,Zt-n.length)}${n}`}i(Dm,"sanitizeFilename");function ho(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(ho,"formatBytes");var Jt=i(e=>Object.freeze({ok:true,value:e}),"ok"),ke=i(e=>Object.freeze({ok:false,error:e}),"err");function ie(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(ie,"failure");function Lm(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i(Lm,"attachmentSize");function Nm(e){let t=Dm(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!Mm(r))return ke(ie("unsupported_type",false,t));let n=Lm(e);return n===null?ke(ie("unknown",false,t)):n>zr?ke(ie("too_large",false,t,{sizeBytes:n})):Jt(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Nm,"validateAttachment");function Um(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(d=>typeof d=="string"&&d.length>0?d:null,"str"),n=i(d=>typeof d=="number"&&Number.isFinite(d)?d:null,"num"),o=r(t.upload_id),a=r(t.upload_url),s=r(t.s3_key);if(o===null||a===null||s===null)return null;let l={},u=t.upload_fields;if(typeof u=="object"&&u!==null)for(let[d,c]of Object.entries(u))typeof c=="string"&&(l[d]=c);return Object.freeze({upload_id:o,upload_url:a,upload_fields:Object.freeze(l),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??zr,s3_key:s,purpose:r(t.purpose)})}i(Um,"parsePolicy");function Hm(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return ie("quota_exceeded",false,t,{cause:e});case "rateLimited":return ie("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return ie("idempotency_conflict",true,t,{cause:e});case "validationFailed":return ie("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return ie("network",true,t,{cause:e});default:return r===429?ie("rate_limited",true,t,{cause:e}):r===503?ie("network",true,t,{cause:e}):r===void 0?ie("network",true,t,{cause:e}):ie("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Hm,"initiateFailure");async function zm(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Fm,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return ke(Hm(n.error,t.filename));let o=Um(n.value);return o===null?ke(ie("server",false,t.filename)):Jt(o)}i(zm,"initiateAttachmentUpload");async function Bm(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return ke(ie("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),Jt(void 0)}catch{return o()?ke(ie("cancelled",true,r.filename)):ke(ie("server",true,r.filename))}}i(Bm,"uploadAttachmentBytes");var jm=2,Vm=3,$m=Object.freeze([1e3,2e3,4e3]),Ps=0;function Wm(){return Ps+=1,`attachment-${Ps}`}i(Wm,"defaultNewId");function ws(e){let t=Math.max(1,e.concurrency??jm),r=Math.max(1,e.maxAttempts??Vm),n=e.backoffMs??$m,o=Math.max(1,e.maxPerMessage??Br),a=e.timers??ts,s=e.newId??Wm,l=ks(e.transport),u=new Map,d=[],c=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),y=false,S=i(()=>{m=Object.freeze({attachments:Object.freeze(d.flatMap(b=>{let x=u.get(b);return x===void 0?[]:[x.state]}))});for(let b of f)b();},"publish"),g=i((b,x)=>{b.state=Object.freeze({...b.state,...x}),S();},"patch"),T=i(()=>{for(;!y&&p.size<t&&c.length>0;){let b=c.shift(),x=u.get(b);x!==void 0&&(p.add(b),R(x).finally(()=>{p.delete(b),T();}));}},"pump"),R=i(async b=>{let{attachment:x}=b;for(;b.attempts<r;){if(y||b.controller.signal.aborted)return;b.attempts+=1;let A=b.controller.signal;g(b,{status:"uploading",error:null,progress:0});let F=await zm(e.funnel,x,{signal:A});if(y||A.aborted)return;let P;if(!F.ok)P=ke(F.error);else {let O=await Bm(e.transport,F.value,x,{signal:A,onProgress:i(B=>{!A.aborted&&b.state.status==="uploading"&&g(b,{progress:Km(B)});},"onProgress")});if(y||A.aborted)return;P=O.ok?Jt(F.value.s3_key):ke(O.error);}if(P.ok){g(b,{status:"uploaded",s3Key:P.value,error:null,progress:1});return}let v=P.error,C=v.retryable&&b.attempts<r;if(g(b,{status:C?"uploading":"failed",error:v,progress:0}),!C)return;let I=n[Math.min(b.attempts-1,n.length-1)]??0;await Nr(I,A,a);}},"run"),_=i(b=>{c.push(b.state.id),T();},"enqueue"),w={available:l,subscribe(b){return f.add(b),()=>{f.delete(b);}},getSnapshot:i(()=>m,"getSnapshot"),get uploading(){return m.attachments.some(b=>b.status==="uploading")},get s3Keys(){return m.attachments.flatMap(b=>b.status==="uploaded"&&b.s3Key!==null?[b.s3Key]:[])},add(b){let x=Nm(b);if(!x.ok)return x;if(y||d.length>=o)return ke(ie("too_many",false,x.value.filename));let A=s(),F={attachment:x.value,controller:new AbortController,attempts:0,state:Object.freeze({id:A,filename:x.value.filename,previewUri:b.uri,contentType:x.value.contentType,sizeBytes:x.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(A,F),d.push(A),S(),_(F),Jt(F.state)},retry(b){let x=u.get(b);x===void 0||y||x.state.status!=="failed"||(x.controller=new AbortController,x.attempts=0,g(x,{status:"uploading",error:null,progress:0,s3Key:null}),_(x));},remove(b){let x=u.get(b);if(x===void 0)return;x.controller.abort(),u.delete(b);let A=d.indexOf(b);A>=0&&d.splice(A,1);let F=c.indexOf(b);F>=0&&c.splice(F,1),S();},clear(){for(let b of [...d])w.remove(b);},dispose(){y=true;for(let b of u.values())b.controller.abort();u.clear(),d.length=0,c.length=0,f.clear(),m=Object.freeze({attachments:Object.freeze([])});}};return w}i(ws,"createAttachmentQueue");function Km(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(Km,"clamp");var Is=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function er(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Is,t)?Is[t]:null}i(er,"canonicalPetSpecies");var As=50,Gm=128,bo=120,Os=120,qm=2e3,Fs=120,Ym=80,Ls=new Set(["male","female","unknown"]),Ns=new Set(["day","month","year"]),Us=new Set(["low","medium","high","athletic"]),Hs=new Set(["indoor","outdoor","both"]),zs=new Set(["mild","moderate","severe"]),Xm=/^(\d{4})-(\d{2})-(\d{2})$/,Bs=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],js=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Bs,...js].map(([e])=>e));function Qm(e){let t=Xm.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],a=new Date(Date.UTC(r,n-1,o));return a.getUTCFullYear()===r&&a.getUTCMonth()===n-1&&a.getUTCDate()===o}i(Qm,"isRealDate");var rr=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),Zm=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),Vr=i((e,t)=>typeof t=="string"&&Qm(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Oe=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Ee(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let a=ct(o);return a<=e?null:`${r} is ${a} characters; the server accepts at most ${e}`},"text"),Jm={sex:rr(Ls),spayedNeutered:Zm,birthDate:Vr,birthDatePrecision:rr(Ns),activityLevel:rr(Us),indoorOutdoor:rr(Hs),foodBrand:Oe(Fs),foodType:Oe(Fs),microchipId:Oe(Ym)},vo=["ref","ref",false,Oe(Gm,{required:true,trimmed:true})],Eo=["notes","notes",false,Oe(qm,{trimmed:true})],Ms=[vo,["name","name",true,Oe(bo,{required:true,trimmed:true})],["dose","dose",false,Oe(Os,{trimmed:true})],["frequency","frequency",false,Oe(Os,{trimmed:true})],["startDate","start_date",false,Vr],["endDate","end_date",false,Vr],Eo],ey={allergies:[vo,["allergen","allergen",true,Oe(bo,{required:true,trimmed:true})],["severity","severity",false,rr(zs)],Eo],medications:Ms,supplements:Ms,conditions:[vo,["conditionName","condition_name",true,Oe(bo,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,Vr],Eo]};function ty(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,a={};for(let[u,d,c,p]of ey[e]){let f=o[u];if(f==null){if(c)return {error:`${n}.${u} is required`};f===null&&(a[d]=null);continue}let m=p(`${n}.${u}`,f);if(m!==null)return {error:m};a[d]=f;}let s=a.start_date,l=a.end_date;return typeof s=="string"&&typeof l=="string"&&l<s?{error:`${n}.endDate must not be before startDate`}:{item:a}}i(ty,"itemToWire");function ry(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>As)return {error:`${e} has ${t.length} items; the server accepts at most ${As}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let a=ty(e,o,t[o]);if("error"in a)return a;let s=a.item.ref;if(typeof s=="string"){let l=s.trim();if(n.has(l))return {error:`${e}: ref ${JSON.stringify(l)} is used twice; a ref names one item`};n.add(l);}r.push(a.item);}return {items:r}}i(ry,"listToWire");function Vs(e,t){let r=e,n={};for(let[s,l]of Bs){let u=r[s];if(u!==void 0){if(u!==null){let d=Jm[s](s,u);if(d!==null)return {error:d}}n[l]=u;}}let o=r.birthDate!==void 0,a=r.birthDatePrecision!==void 0;if(o!==a||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[s,l]of js){let u=r[s];if(u===void 0)continue;let d=ry(s,u);if("error"in d)return d;n[l]=d.items;}return Object.keys(n).length>0&&t!==void 0&&er(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(Vs,"petHealthToWire");var te=i(e=>typeof e=="string"?e:null,"str"),tr=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),ny=i(e=>typeof e=="boolean"?e:null,"bool");function jr(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i(jr,"itemsFromWire");function Ds(e){let t=te(e.name);return t===null||t.length===0?null:Object.freeze({ref:te(e.ref),name:t,dose:te(e.dose),frequency:te(e.frequency),startDate:te(e.start_date),endDate:te(e.end_date),notes:te(e.notes)})}i(Ds,"medicationFromWire");function $s(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:tr(Ls,e.sex),spayedNeutered:ny(e.spayed_neutered),birthDate:te(e.birth_date),birthDatePrecision:tr(Ns,e.birth_date_precision),activityLevel:tr(Us,e.activity_level),indoorOutdoor:tr(Hs,e.indoor_outdoor),foodBrand:te(e.food_brand),foodType:te(e.food_type),microchipId:te(e.microchip_id),allergies:jr(e.allergies,r=>{let n=te(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:te(r.ref),allergen:n,severity:tr(zs,r.severity),notes:te(r.notes)})}),medications:jr(e.medications,Ds),supplements:jr(e.supplements,Ds),conditions:jr(e.conditions,r=>{let n=te(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:te(r.ref),conditionName:n,diagnosedDate:te(r.diagnosed_date),notes:te(r.notes)})})})}i($s,"petHealthFromWire");var Gs=100,qs=50,Ys=100,Xs=50,Qs=500,oy=128,iy=6e4;function Me(e){return D("validationFailed",{retryable:false,wireMessage:e})}i(Me,"invalid");function ft(e,t,r){if(typeof t!="string")return Me(`${e} must be a string`);let n=ct(t);return n<=r?null:Me(`${e} is ${n} characters; the server accepts at most ${r}`)}i(ft,"checkString");function $r(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Me(`${e} must be a finite number between 0 and ${r}`)}i($r,"outOfRange");function Ws(e,t){if(typeof e!="string")return Me("pet_ref must be a string");if(e.trim().length===0)return Me("pet_ref must not be blank");if(Ee(e))return Me("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Me("profile must be an object");let r=[ft("pet_ref",e,oy)];return t?.name!==void 0&&r.push(ft("name",t.name,Gs)),t?.species!==void 0&&r.push(ft("species",t.species,qs)),t?.breed!==void 0&&r.push(ft("breed",t.breed,Ys)),t?.ageYears!==void 0&&r.push($r("age_years",t.ageYears,Xs)),t?.weightKg!==void 0&&r.push($r("weight_kg",t.weightKg,Qs)),r.find(n=>n!==null)??null}i(Ws,"validate");function Zs(e,t){let r=Vs(e,t);return "error"in r?{error:Me(r.error)}:r}i(Zs,"healthToWire");function ay(e){if(typeof e!="object"||e===null)return {error:Me("patch must be an object")};let t=e,r=[["name","name",a=>ft("name",a,Gs)],["species","species",a=>ft("species",a,qs)],["breed","breed",a=>ft("breed",a,Ys)],["ageYears","age_years",a=>$r("age_years",a,Xs)],["weightKg","weight_kg",a=>$r("weight_kg",a,Qs)]],n={};for(let[a,s,l]of r){let u=t[a];if(u!==void 0){if(u!==null){let d=l(u);if(d!==null)return {error:d}}n[s]=u;}}let o=Zs(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Me("patch must change at least one field")}:{body:n})}i(ay,"patchToWire");function sy(e){if(e==null)return {body:{}};let t=Zs(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(sy,"toWire");var Fe=i(e=>typeof e=="string"?e:null,"str"),Wr=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function Ks(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Fe(r.pet_ref)??t,name:Fe(r.name),species:Fe(r.species),breed:Fe(r.breed),ageYears:Wr(r.age_years),weightKg:Wr(r.weight_kg)})}i(Ks,"fromWire");function Js(e){if(typeof e!="object"||e===null)return null;let t=e,r=Fe(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Fe(t.pet_id),petRef:r,name:Fe(t.name),species:Fe(t.species),breed:Fe(t.breed),ageYears:Wr(t.age_years),weightKg:Wr(t.weight_kg),updatedAt:Fe(t.updated_at)})}i(Js,"widgetPetFromWire");function ly(e){let t=Js(e);return t===null?null:Object.freeze({...t,...$s(e)})}i(ly,"widgetPetProfileFromWire");function uy(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=Js(r);return n===null?[]:[n]}))}i(uy,"petListFromWire");function et(e){return dy(Te({auth:e}),Te({auth:e,unaryTimeoutMs:iy}))}i(et,"createPetsRepository");function dy(e,t=e){let r=i((o,a)=>a?{...o,signal:a}:o,"withSignal"),n=i(o=>Ws(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let a=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return a.ok?M(uy(a.value)):E(a.error)},async registerPet(o,a,s){let l=Ws(o,a);if(l!==null)return E(l);let u=sy(a);if("error"in u)return E(u.error);let c={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:u.body},p=await e.send("pets.registerPet",s?.signal?{...c,signal:s.signal}:c);return p.ok?M(Ks(p.value,o)):E(p.error)},async updatePet(o,a,s){let l=n(o);if(typeof l!="string")return E(l);let u=ay(a);if("error"in u)return E(u.error);let d=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},s?.signal));return d.ok?M(Ks(d.value,o)):E(d.error)},async getPetProfile(o,a){let s=n(o);if(typeof s!="string")return E(s);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${s}/profile`},a?.signal));if(!l.ok)return E(l.error);let u=ly(l.value);return u===null?E(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):M(u)},async deletePet(o,a){let s=n(o);if(typeof s!="string")return E(s);let l=await e.send("pets.deletePet",r({method:"DELETE",path:s},a?.signal));return l.ok?M(void 0):E(l.error)},async eraseUserData(o){let a=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return a.ok?M(void 0):E(a.error)}}}i(dy,"createPetsRepositoryOver");var So=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function cy(e){return So[e]}i(cy,"requires");function el(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let a of Object.keys(So))for(let s of So[a])o.has(s)||(o.add(s),n.push(Object.freeze({resource:s,granted:false,disabled:r})));return Object.freeze(n)}i(el,"deniedDecisionsFor");function tl(e,t,r){let n=cy(e),o=new Map;for(let l of t)o.set(l.resource,l);if(r?.isPending===true&&n.some(l=>!o.has(l)))return Co({name:e,enabled:false,isPending:true,limits:{}});let a=py(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?Co({name:e,enabled:true,isPending:false,limits:a}):Co({name:e,enabled:false,isPending:false,limits:a,disabled:fy(n,o)})}i(tl,"decideCapability");function py(e,t){let r={};for(let n of e){let o=t.get(n)?.limits;if(o)for(let[a,s]of Object.entries(o)){let l=r[a];r[a]=l===void 0?s:Math.min(l,s);}}return r}i(py,"mergeLimits");function fy(e,t){for(let r of e){let n=t.get(r)?.disabled;if(n)return Object.freeze({reason:n.reason,level:n.level,recoverable:n.recoverable})}return Object.freeze({reason:At("accessDenied"),level:"user_entitlement",recoverable:false})}i(fy,"disabledFor");function Co(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(Co,"freezeDecision");function ye(e){let t=ae(e);return t===null?null:yy(t)}i(ye,"parseColor");function ae(e){if(typeof e=="number")return rl(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return Ro(t.slice(1));if(t.toLowerCase().startsWith("0x"))return Ro(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return my(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=Ro(t);if(r!==null)return r}return /^\d+$/.test(t)?rl(Number.parseInt(t,10)):null}i(ae,"toRgba");function Ro(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:xo(t[0]),g:xo(t[1]),b:xo(t[2]),a:1};if(t.length===6)return {r:mt(t,0),g:mt(t,2),b:mt(t,4),a:1};if(t.length===8){let r=mt(t,0);return {r:mt(t,2),g:mt(t,4),b:mt(t,6),a:r/255}}return null}i(Ro,"fromHex");function my(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(u=>u.trim());if(n.length<3)return null;let o=To(Number(n[0])),a=To(Number(n[1])),s=To(Number(n[2]));if(o===null||a===null||s===null)return null;let l=1;if(n.length>=4){let u=Number(n[3]);if(!Number.isFinite(u))return null;l=Math.min(1,Math.max(0,u));}return {r:o,g:a,b:s,a:l}}i(my,"fromRgbFunc");function rl(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(rl,"argbIntToRgba");function mt(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(mt,"byte");function xo(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(xo,"dup");function To(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(To,"clampByte");function yy(e){if(e.a>=1)return gt(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(yy,"normalizeRgba");function gt(e,t,r){return `#${ko(e)}${ko(t)}${ko(r)}`.toUpperCase()}i(gt,"rgbToHex");function ko(e){return e.toString(16).padStart(2,"0")}i(ko,"hex2");var gy="#111111",Ot="#FFFFFF",Kr="#000000";function ol(e){let t=ae(e);if(t===null)return Ot;let r=yt(t),n=yt({r:17,g:17,b:17}),o=yt({r:255,g:255,b:255});return wo(r,o)>=wo(r,n)?Ot:gy}i(ol,"readableOn");function nr(e,t){let r=ol(e);return ue(r,e)>=t?r:ue(Ot,e)>=ue(Kr,e)?Ot:Kr}i(nr,"legibleOn");function or(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,ue(r,o)),Number.POSITIVE_INFINITY),"worst");return t(Ot)>=t(Kr)?Ot:Kr}i(or,"poleForGrounds");function yt(e){let t=Po(e.r/255),r=Po(e.g/255),n=Po(e.b/255);return .2126*t+.7152*r+.0722*n}i(yt,"relativeLuminance");function Po(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(Po,"linearize");function wo(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(wo,"luminanceContrast");function ue(e,t){let r=ae(e),n=ae(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},a=r.a>=1?r:il(r,o);return wo(yt(a),yt(o))}i(ue,"contrastRatio");function il(e,t){let r=e.a,n=i((o,a)=>Math.round(o*r+a*(1-r)),"mix");return {r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}i(il,"composite");function ht(e,t){let r=ae(e),n=ae(t);if(r===null||n===null)return null;let o=r.a>=1?r:il(r,{...n});return gt(o.r,o.g,o.b)}i(ht,"flattenOnto");function $e(e,t){let r=ae(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return `rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}i($e,"withAlpha");var nl=.05;function tt(e,t,r,n){let o=t[0];if(o===void 0)return r;let a=i(d=>t.every(c=>ue(d,c)>=n),"reads");if(ae(e)===null)return r;if(a(e))return e;let s=ht(e,o),l=s===null?null:ae(s),u=ae(r);if(l===null||u===null)return r;for(let d=1;d<1/nl;d+=1){let c=d*nl,p=i((m,y)=>Math.round(m+(y-m)*c),"mix"),f=gt(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(a(f))return f}return r}i(tt,"pushToContrast");function al(e,t,r){let n=e/255,o=t/255,a=r/255,s=Math.max(n,o,a),l=Math.min(n,o,a),u=(s+l)/2;if(s===l)return {h:0,s:0,l:u};let d=s-l,c=d/(1-Math.abs(2*u-1)),p;return s===n?(p=(o-a)/d*60,p<0&&(p=p+360)):s===o?p=((a-n)/d+2)*60:p=((n-o)/d+4)*60,{h:p,s:c,l:u}}i(al,"rgbToHsl");function Io(e){let{h:t,s:r,l:n}=e,o=(1-Math.abs(2*n-1))*r,a=t/60,s=o*(1-Math.abs(a%2-1)),l=n-o/2,u=Math.floor(a)%6,d=[[o,s,0],[s,o,0],[0,o,s],[0,s,o],[s,0,o],[o,0,s]],[c,p,f]=d[u];return {r:_o(c+l),g:_o(p+l),b:_o(f+l)}}i(Io,"hslToRgb");function _o(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(_o,"channel");function We(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))We(e[t]);}return e}i(We,"deepFreeze");var Gr=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),ll={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},ul={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},sl={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},hy={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},by={regular:"400",medium:"500",bold:"700"},vy={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Ao=0,bt="System",rt="monospace",Ey=["content","heading","control","compact","badge"];function Cy(e){let t={};for(let r of Ey)t[r]=e;return t}i(Cy,"authoredTierSizes");function dl(){return {family:bt,mono:rt,fontUrl:null,families:{regular:bt,medium:bt,bold:bt,mono:rt,monoMedium:rt,monoBold:rt},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:sl,tierSizes:Cy(sl),lineHeight:hy,weight:by,letterSpacing:vy,scale:1,maxScale:Ao,scaleCaps:Gr}}i(dl,"baseType");var cl={},vt=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function ir(e){return `cubic-bezier(${e.join(", ")})`}i(ir,"cssCubicBezier");var pl={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:ir(vt.standard),emphasized:ir(vt.emphasized),exit:ir(vt.exit)},reducedMotion:false},Sy={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#B91C1C",errorRed:"#FF1B00",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},Et=We({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Sy,space:ll,radius:ul,type:dl(),motion:pl,slots:cl}),Ry={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A938C",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},qr=We({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Ry,space:ll,radius:ul,type:dl(),motion:pl,slots:cl});var xy="#23272C",fl=4.5,Ty=.6,Oo=.9,ky=.02,Py="#FFFFFF",_y="#111111";function wy(e){return ue(e,xy)>=fl&&Math.max(ue(e,Py),ue(e,_y))>=fl}i(wy,"readsOnDark");function gl(e){let t=ae(e);if(t===null)return null;let{h:r,s:n,l:o}=al(t.r,t.g,t.b),a=Math.min(Math.max(o,Ty),Oo);for(let l=0;;l+=1){let u=a+l*ky;if(u>Oo)break;let d=Io({h:r,s:n,l:u}),c=gt(d.r,d.g,d.b);if(wy(c))return c}let s=Io({h:r,s:n,l:Oo});return gt(s.r,s.g,s.b)}i(gl,"deriveDarkVariant");var Iy=7,ml=.05,Ay="#000000",Oy="#FFFFFF";function Fy(e,t,r,n){let o=ht(e,t);if(o===null)return r;if(ue(o,t)>=n)return o;let a=ae(o),s=ae(r);if(a===null||s===null)return r;for(let l=1;l<1/ml;l+=1){let u=l*ml,d=i((p,f)=>Math.round(p+(f-p)*u),"mix"),c=gt(d(a.r,s.r),d(a.g,s.g),d(a.b,s.b));if(ue(c,t)>=n)return c}return r}i(Fy,"pushContrast");function My(e,t){let r=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],n=r[0],o=yl(n);for(let a of r){let s=yl(a);(t?s>o:s<o)&&(n=a,o=s);}return n}i(My,"hardestGround");function yl(e){let t=ae(e);return t===null?0:yt(t)}i(yl,"luminanceOf");function nt(e,t){return ht(e,t)??ye(e)??t}i(nt,"solid");function hl(e){let t=e.color,r=e.brightness==="dark",n=r?Oy:Ay,o=My(t,r),a=i(l=>Fy(l,o,n,Iy),"text"),s={...t,brandSoft:nt(t.brandSoft,t.surface),brandSofter:nt(t.brandSofter,t.surface),brandBorder:a(t.brandBorder),borderHairlineGreen:a(t.borderHairlineGreen),brandBorderStrong:a(t.brandBorderStrong),brandInk:a(t.brandInk),linkInk:a(t.linkInk),borderRingCream:a(t.borderRingCream),composerBorder:a(t.composerBorder),text:{primary:a(t.text.primary),secondary:a(t.text.secondary),muted:a(t.text.muted),placeholder:a(t.text.placeholder),onBrand:t.text.onBrand,metaCool:a(t.text.metaCool),timestamp:a(t.text.timestamp)},badgeBgPositive:nt(t.badgeBgPositive,t.surface),badgeBgCaution:nt(t.badgeBgCaution,t.surface),badgeBgCritical:nt(t.badgeBgCritical,t.surface),badgeBgNeutral:nt(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:nt(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:nt(t.checkupCardConcernBg,t.surface)};return We({...e,highContrast:true,color:s})}i(hl,"deriveHighContrast");var Ct=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),Dy=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Pe=4.5,Ly=Object.freeze({});function Ny(e){return Ct.includes(e)}i(Ny,"isSlotName");function Uy(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Uy,"parseRadius");function bl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!Ny(n)||o===null||typeof o!="object")continue;let a=Hy(o);a!==null&&(t[n]=a,r=true);}return r?Object.freeze(t):null}i(bl,"parseThemeSlots");function Yr(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(Yr,"pick");function Hy(e){let t={},r=ye(Yr(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=ye(Yr(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Uy(Yr(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let a=ye(Yr(e,"text_color","textColor"));return a!==null&&(t.textColor=a),Object.keys(t).length===0?null:Object.freeze(t)}i(Hy,"parseSlot");function vl(e,t){return t===null||Object.keys(t).length===0?e??Ly:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(vl,"mergeThemeSlots");var Fo=3;function zy(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>ht(e,r)??r)}i(zy,"seatsOf");function By(e,t){let r=or(e);return e.every(n=>ue(r,n)>=t)}i(By,"someInkReads");function jy(e,t){let r=t[0];return r===void 0?null:ht(e,r)}i(jy,"collapseUnsatisfiableFill");function Vy(e){let t=nr(e[0],Pe);return e.every(r=>ue(t,r)>=Pe)?t:or(e)}i(Vy,"inkFor");function El(e,t){let r=false,n={};for(let o of Ct){let a=e[o];if(a===void 0)continue;let s=a.backgroundColor,l=t?.[o]??[],u=zy(s,l),d={...a},c=false;if(s!==void 0&&u.length>1&&!By(u,Pe)){let p=jy(s,l);p!==null&&(d.backgroundColor=p,u=[p],c=true);}if(u.length>0){let p=a.textColor;if(s!==void 0)(p===void 0||u.some(f=>ue(p,f)<Pe))&&(d.textColor=Vy(u),c=true);else if(p!==void 0){let f=tt(p,u,or(u),Pe);f!==p&&(d.textColor=f,c=true);}if(a.borderColor!==void 0){let f=tt(a.borderColor,u,or(u),Fo);f!==a.borderColor&&(d.borderColor=f,c=true);}}n[o]=c?Object.freeze(d):a,r=r||c;}return r?Object.freeze(n):e}i(El,"guardSlotContrast");var Rl=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),ar="slots.",xl=Object.freeze([1,2]);function Xr(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(Xr,"isEmptyBranding");function Tl(e){let t=e?.schemaVersion??null;return t===null||xl.includes(t)}i(Tl,"isKnownBrandingSchema");function kl(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(kl,"lockedFieldsOf");function $y(e){return e==="hide_powered_by"||Rl.includes(e)?true:e.startsWith(ar)&&Ct.includes(e.slice(ar.length))}i($y,"isThemeLockName");function Ke(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:St(Y(t,"display_name","displayName")),logoUrl:St(Y(t,"logo_url","logoUrl")),primaryColor:ye(Y(t,"primary_color","primaryColor")),accentColor:ye(Y(t,"accent_color","accentColor")),brightness:qy(Y(t,"brightness","color_scheme","colorScheme")),fontFamily:St(Y(t,"font_family","fontFamily")),fontUrl:St(Y(t,"font_url","fontUrl")),fonts:Cl(Y(t,"fonts")),fontUrls:Cl(Y(t,"font_urls","fontUrls")),placeholder:St(Y(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Wy(Y(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:ye(Y(t,"primary_color_dark","primaryColorDark")),accentColorDark:ye(Y(t,"accent_color_dark","accentColorDark")),surfaceStyle:Sl(Y(t,"surface_style","surfaceStyle"),Ky),radiusScale:Sl(Y(t,"radius_scale","radiusScale"),Gy),logoUrlDark:St(Y(t,"logo_url_dark","logoUrlDark")),slots:bl(Y(t,"slots")),accessibilityMaxFontScale:Xy(Y(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:Zy(Y(t,"locked_fields","lockedFields")),schemaVersion:Qy(Y(t,"schema_version","schemaVersion"))};return Xr(r)?null:Object.freeze(r)}i(Ke,"parseClientBranding");function Wy(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(Wy,"parseBool");function Y(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i(Y,"pick");function St(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(St,"parseNonEmptyString");var sr=["regular","medium","bold","mono","monoMedium","monoBold"];function Cl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of sr){let o=St(Y(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(Cl,"parseFaceMap");var Ky=["white","cream","subtle"],Gy=["sharp","default","round"];function Sl(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(Sl,"parseEnum");function qy(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(qy,"parseBrightness");function Pl(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(Pl,"parseNumber");var Yy=1,_l=3.1;function Xy(e){let t=Pl(e);return t===null?null:t<=0?0:Math.min(_l,Math.max(Yy,t))}i(Xy,"parseMaxFontScale");function Qy(e){if(e==null)return null;let t=Pl(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(Qy,"parseSchemaVersion");function Mo(e){let t=e.trim();return t.startsWith(ar)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Mo,"toWireName");function Zy(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Mo(r);$y(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(Zy,"parseLockedFields");function Do(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(Do,"hardenHttpsUrl");function wl(e,t){if(t===null||Xr(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?qr:Et:e,n=r.brightness==="dark"?qr:Et,o=r.brightness==="dark",a=o?t.primaryColorDark??Il(t.primaryColor):t.primaryColor,s=o?t.accentColorDark??Il(t.accentColor):t.accentColor,l=a??r.color.primary,u=s??r.color.accent,d=a!==null&&ng(t,l,n,o),c=d?n.color.primary:l,p=a!==null&&!d?ae(c):null,f=i(S=>Math.round(S+(255-S)*.4),"lift"),m=p!==null?{brand:c,bubbleUser:c,brandInk:c,text:{...r.color.text,secondary:c},brandSoft:`rgba(${p.r}, ${p.g}, ${p.b}, 0.10)`,brandSofter:`rgba(${p.r}, ${p.g}, ${p.b}, 0.15)`,brandBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.20)`,borderHairlineGreen:`rgba(${p.r}, ${p.g}, ${p.b}, 0.28)`,brandBorderStrong:`rgba(${p.r}, ${p.g}, ${p.b}, 0.55)`,composerBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.75)`,accentEdge:`rgb(${f(p.r)}, ${f(p.g)}, ${f(p.b)})`}:d?og(n,r.color.text):{},y={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(o?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy},color:{...r.color,...m,...rg(t.surfaceStyle??null,n),primary:c,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:r.space,radius:ag(t.radiusScale??null,r.radius,n),type:{...r.type,...tg(r.type,t),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:vl(r.slots,t.slots??null)};return We(y)}i(wl,"withServerBranding");var Jy={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},eg=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Lo(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(Lo,"isMonoFace");function tg(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},a={...e.namedFaces},s={...e.fontUrls};for(let l of sr){let u=Jy[l].map(p=>r[p]).find(p=>p!==void 0),d=Lo(l)?null:t.fontFamily;u!==void 0?(o[l]=u,a[l]=true):d!==null&&(o[l]=d,a[l]=false);let c=n[l]??(l==="regular"?t.fontUrl:null)??null;c!==null?s[l]=c:u!==void 0&&delete s[l];}for(let l of eg)for(let u of l)a[u]&&l.some(d=>d!==u&&o[d]===o[u])&&(a[u]=false);return {family:o.regular,mono:o.mono,fontUrl:s.regular??null,families:o,namedFaces:a,fontUrls:s}}i(tg,"mergeFaces");function Il(e){return e===null?null:gl(e)}i(Il,"darkVariantOf");function rg(e,t){if(e===null)return {};let r=t.color;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(rg,"surfaceOf");function Al(e,t){return e==null?false:ye(e)===ye(t)}i(Al,"sameColor");function ng(e,t,r,n){return Al(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Al(e.primaryColor,Et.color.primary)}i(ng,"isCompiledPrimary");function og(e,t){let r=e.color;return {text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}i(og,"compiledBrandFamily");var ig={sharp:.5,default:1,round:1.5};function ag(e,t,r){if(e===null)return t;let n=ig[e],o=r.radius,a=i(s=>Math.round(s*n),"s");return {tile:a(o.tile),xs:a(o.xs),sm:a(o.sm),md:a(o.md),lg:a(o.lg),xl:a(o.xl),pill:o.pill}}i(ag,"radiusOf");var sg="Everfur",lg=.5;function No(e){let t=e?.branding??null,r=Tl(t)?t:null,n=fg(e?.clientOverride??null,kl(r)),o=e?.colorScheme==="dark"?"dark":"light",a=n?.brightness??r?.brightness??"light",u=wl((a==="auto"?o:a)==="dark"?qr:Et,Ol(r)),d=wl(u,Ol(n));return Tg(d,e)}i(No,"resolveTheme");function ug(e,t,r){return No({...r,branding:Ke(t),clientOverride:Ke(e)})}i(ug,"previewTheme");function dg(e){return e==="placeholder"?"chat_placeholder":Mo(e)}i(dg,"wireNameOf");var cg={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function pg(e,t){return t.has(dg(e))?true:(cg[e]??[]).some(r=>t.has(r))}i(pg,"isLocked");function fg(e,t){if(e===null)return null;let r=false,n={...e};for(let s of Object.keys(e))(e[s]??null)!==null&&(pg(s,t)||s==="lockedFields")&&(n[s]=null,r=true);let o=n.slots??null;if(o!==null){let s={},l=false;for(let u of Ct){let d=o[u];d!==void 0&&(t.has(`${ar}${u}`)?l=true:s[u]=d);}l&&(n.slots=Object.keys(s).length===0?null:Object.freeze(s),r=true);}if(!r)return e;let a=Object.freeze(n);return Xr(a)?null:a}i(fg,"withoutFields");function Ol(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(Ol,"withoutBrightness");function mg(e,t){if(t===1)return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Math.round(o*t*10)/10;return r}i(mg,"scaledSizes");function yg(e){return e===void 0||!Number.isFinite(e)?1:Math.max(lg,e)}i(yg,"effectiveScale");var Fl=["content","heading","control","compact","badge"];function gg(e){if(!(e>0))return Gr;let t={};for(let r of Fl){let n=Gr[r];t[r]=n===0?0:Math.min(n,e);}return t}i(gg,"tierCaps");function hg(e,t){return t>0?Math.min(e,t):e}i(hg,"capped");function bg(e,t,r,n){let o={};for(let a of Fl)o[a]=n?mg(e,hg(t,r[a])):e;return o}i(bg,"sizesByTier");function vg(e){return e==="dark"?"#FFFFFF":"#000000"}i(vg,"inkPole");function Eg(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(Eg,"textGrounds");function Cg(e){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}i(Cg,"controlGrounds");function Ml(e){return [e.chatGround,e.surface,e.surfaceCream]}i(Ml,"linkGrounds");function Sg(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Ml(e)}}i(Sg,"slotGrounds");function Rg(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(Rg,"registration");function xg(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return {family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces};let o={...e.families},a={...e.namedFaces};for(let s of sr)!(o[s]===bt||o[s]===rt)&&r!==void 0&&Rg(r,o[s])===false&&(o[s]=Lo(s)?rt:bt,a[s]=false),n!==null&&Lo(s)&&o[s]===rt&&(o[s]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:a}}i(xg,"platformFaces");function Tg(e,t){let r=e.color.primary,n=e.color.accent,o=e.meta.displayName.trim().length===0?sg:e.meta.displayName,a=Do(e.meta.logoUrl),s={};for(let _ of sr){let w=e.type.fontUrls[_];w!==void 0&&(s[_]=Do(w));}let l=s.regular??null,d=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,c=Number.isFinite(e.type.maxScale)?e.type.maxScale:Ao,p=yg(t?.textScale),f=gg(c),m=bg(e.type.size,p,f,t?.scaleTypeSizes===true),y=e.color,S=vg(e.brightness),g=Eg(y),T={...y,primary:r,accent:n,onPrimary:nr(r,Pe),onAccent:nr(n,Pe),brandInk:tt(y.brandInk,g,S,Pe),linkInk:tt(e.slots.link?.textColor??n,Ml(y),S,Pe),text:{...y.text,secondary:tt(y.text.secondary,g,S,Pe)},brandBorderStrong:tt(y.brandBorderStrong,Cg(y),S,Fo)},R={brightness:e.brightness,highContrast:false,meta:{displayName:o,logoUrl:a,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:T,space:e.space,radius:e.radius,type:{...e.type,...xg(e.type,t),fontUrl:l,fontUrls:s,size:m.content,tierSizes:m,scale:p,maxScale:c,scaleCaps:f},motion:d,slots:El(e.slots,Sg(T))};return t?.highContrast===true?hl(We(R)):We(R)}i(Tg,"finalize");var Dl="/widget/v1/entitlements",kg=304,Pg=Object.freeze({kind:"notModified"});async function Nl(e,t={},r=Te({auth:e})){let n=await r.send("entitlements.fetch",wg(t));return n.ok?Ig(n.value):n.error.httpStatus===kg?Pg:{kind:"failed",error:n.error}}i(Nl,"fetchEntitlements");var _g=64;function wg(e){let t={};return Uo(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=_g?{method:"GET",path:Dl,headers:t,query:{region:e.region}}:{method:"GET",path:Dl,headers:t}}i(wg,"buildRequest");function Ig(e){if(e===null||typeof e!="object"||!Uo(e.revision))return Ll();let t=typeof e.region=="string"?e.region:"",r=Uo(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:Og(e.capabilities),branding:Ag(e)})}i(Ig,"parseUpdated");function Ag(e){let t=Ke(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=Ke(r.branding);return n!==null?n:Ke(r)}return null}i(Ag,"parseBranding");function Og(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Fg(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(Og,"mapCapabilities");function Fg(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Fg,"isEnabled");function Ll(){return {kind:"failed",error:D("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(Ll,"malformed");function Uo(e){return typeof e=="number"&&Number.isFinite(e)}i(Uo,"isFiniteNumber");var Mg=30;function Ul(e){let t=e.scheduler??Dg,r=e.resolve??Nl,n=Math.max(1,e.floorSeconds??Mg),o=e.rng??Math.random,a=i(()=>n+o()*n,"jitteredFloorSeconds"),s=false,l=false,u=null,d=null,c=n,p=0,f=i(()=>{u!==null&&(t.clear(u),u=null);},"clearTimer"),m=i(T=>{l||!s||(c=Math.max(n,T),u=t.set(()=>{u=null,g();},c*1e3));},"schedule"),y=null,S=i(async()=>{if(l)return null;let T=p;e.onFetch?.();let R=e.region?{cachedRevision:d,region:e.region}:{cachedRevision:d},_;try{_=await r(e.authFor(),R);}catch(w){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:Lg(w)}),!l&&T===p&&(e.onSettled?.(),m(a())),null}if(l||T!==p)return null;switch(_.kind){case "updated":d=_.revision,e.update(_.decisions,_.branding??null),m(_.ttlSeconds);break;case "notModified":m(c);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:_.error.code}),m(a());break;default:m(a());}return e.onSettled?.(),_},"tick"),g=i(()=>{let T=S().finally(()=>{y===T&&(y=null);});return y=T,T},"run");return {start(){s||l||(s=true,g());},prime(){return l?Promise.resolve(null):y??g()},stop(){l||(l=true,p++,f());},refresh(){l||!s||(p++,d=null,f(),g());}}}i(Ul,"createEntitlementPoller");var Dg={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function Lg(e){return e instanceof Error?e.message:"poll failed"}i(Lg,"describe");var Hl="everfur.notifications.device";var Ng=3e3,zl=Object.freeze([Hl]);function Bl(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let a=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),s=[...n].map(d=>{try{return Promise.resolve(d(a))}catch(c){return Promise.reject(c)}}),l=i((d,c)=>{try{o.track("sdk.logout.hookFailed",{reason:d,count:c,totalCount:s.length});}catch{}},"report"),u=Promise.allSettled(s).then(d=>{let c=d.filter(p=>p.status==="rejected").length;c>0&&l("failed",c);});return new Promise(d=>{let c=false,p=i(()=>{c||(c=true,clearTimeout(f),d());},"finish"),f=setTimeout(()=>{c||l("timeout",s.length),p();},Ng);u.then(p,p);})}i(Bl,"startBeforeLogoutHooks");function jl(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,a=r.currentToken();a.catch(()=>{});let s={userRef:t.userRef,currentToken:i(()=>a,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:s,userRef:t.userRef,sessionId:o}}i(jl,"graceAuth");async function Vl(e,t){if(zl.length===0)return;let r=await Promise.allSettled(zl.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(Vl,"sweepPerUserKv");function Ug(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Ug,"compiledDefaultDecisions");function Ho(e=Ug){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(Ho,"createEntitlementStore");function zo(e){return D("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(zo,"notConfiguredError");function $l(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return wa(r,t===void 0?void 0:{platform:t})}i($l,"tryResolveClient");function Wl(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Wl,"guardTelemetry");function Kl(e,t){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
12
- [everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(Kl,"reportConfigFailure");function Bo(e){return Object.freeze({request(){return Promise.resolve(E(zo(e)))},stream(t,r){let n=pe({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(Bo,"refusingTransport");function Gl(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(Gl,"createInMemoryKv");var ql=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function Ql(e,t){return new Vo(e,t)}i(Ql,"createEverfurRuntime");var Hg=6e4,$o=class $o{constructor(t,r){this.sessionId=Yn();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new J("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?Wl(n.telemetry):Ir;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",a=Qn(n?.publishableKey),s=n.transport!==void 0,l,u=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(a!==null)l=Bo(a);else if(n.transport!==void 0)l=n.transport;else {let c=$l(n,r?.platform);c.ok?(u=c.config.apiBaseUrl,l=Da({config:c.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(a=c.failure,l=Bo(c.failure));}this.configFailure=a,this.publishableKey=a===null?o:"",this.transport=l,a!==null&&Kl(a,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??fa,this.upload=n.upload??es,this.uploadTransport=n.uploadTransport??go,this.imageCache=n.imageCache??ql,this.kv=n.storage??Gl(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=a===null?Ho():Ho(()=>el("sdk_config",At("accessDenied"))),this.services={authFor:i(c=>this.buildAuth(c),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:u},this.registry={services:this.services,acquireChat:i(c=>this.acquireInternal("chat",jo(c),()=>this.buildChatController(c),Yl),"acquireChat"),releaseChat:i(c=>this.releaseInternal(c),"releaseChat"),peekChat:i(c=>this.entries.get(`${this.epoch}|chat|${jo(c)}`)?.controller??null,"peekChat"),acquire:i((c,p,f,m)=>this.acquireInternal(c,p,f,m),"acquire"),release:i(c=>this.releaseInternal(c),"release")},this.entitlements=this.store;let d=a===null&&(r?.startEntitlementPolling??!s);this.poller=a===null?this.buildPoller(r?.pollScheduler):null,d&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=Sa(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-Hg,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return Ul({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,a=false){let s=`${this.epoch}|${t}|${r}`,l=this.entries.get(s);if(l)return a||(l.warm?l.warm=false:l.refCount+=1),l.controller;let u=n();return this.entries.set(s,{controller:u,refCount:1,warm:a}),this.destroyers.set(u,o),u}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=Ss({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Ts(n,{controller:t});return o.then(a=>t.adoptPrompts(a.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=Yn(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await Vl(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return Bl({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>jl({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?E(Xl(t)):r(et(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let a={key:n,result:null,promise:this.runPrepare(r).then(s=>(a.result=s,s))};return this.prepared=a,a.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?Xl("prepare"):n===null?null:zo(n),a=this.identity,[s,l,u]=await Promise.all([o?E(o):a===null?M(void 0):a.currentToken().then(()=>M(void 0),()=>E(D("authRejected",{retryable:false}))),o?E(o):this.primeEntitlements(),t===null?void 0:o?E(o):this.primeChat(t)]),d=s.ok?l.ok&&(u?.ok??true)?"ready":"partial":"failed",c=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:c,status:d});}catch{}return Object.freeze({status:d,durationMs:c,session:s,entitlements:l,...u?{chat:u}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?E(t.error):M(void 0):E(D("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",jo(r),()=>this.buildChatController(r),Yl,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?E(o.cause):M(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i($o,"EverfurRuntimeImpl");var Vo=$o;function jo(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i(jo,"chatScopeKey");function Yl(e){e.dispose();}i(Yl,"disposeChat");function Xl(e){return D("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Xl,"disposedError");var Zl=Symbol.for("@everfur/sdk#EverfurContext@v1"),Jl=globalThis,Qr=Jl[Zl]??(Jl[Zl]=createContext(null));Qr.displayName??="EverfurContext";function X(){let e=useContext(Qr);if(e===null)throw new J("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(X,"useEverfurContext");function eu(){return X().handle}i(eu,"useEverfur");var tu=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),ru=globalThis,lr=ru[tu]??(ru[tu]=createContext(Et));lr.displayName??="EverfurThemeContext";function N(){return useContext(lr)}i(N,"useEverfurTheme");function Zr(e){let{runtime:t}=X(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot),o=e.seams.useColorScheme(),a=e.seams.useReducedMotion(),s=e.seams.useTextScale(),l=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,d=e.seams.platformMonoFamily?.(),c=e.seams.isFontRegistered,p=e.clientTheme?Kg(e.clientTheme):"",f=useMemo(()=>e.clientTheme?Ke(e.clientTheme):null,[p]),m=n.branding??null,y=useMemo(()=>No({branding:m,clientOverride:f,colorScheme:o,reducedMotion:a,textScale:s,scaleTypeSizes:u,highContrast:l,...d===void 0?{}:{platformMonoFamily:d},...c===void 0?{}:{isFontRegistered:c}}),[m,f,o,a,s,u,l,d,c]);return e.seams.useResolvedTheme?.(y),createElement(lr.Provider,{value:y},e.children)}i(Zr,"EverfurThemeProviderCore");function Kg(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(Kg,"stableKey");function su(e){let{config:t,user:r,activePet:n,theme:o,warmUp:a,children:s,seams:l}=e,u=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,d=useRef(null),c=useRef(null),[p,f]=useReducer(C=>C+1,0),m=useRef(null),y=useRef(void 0),S=r?.userRef??null;y.current!==S&&(y.current!==void 0&&(m.current=null),y.current=S);let g=m.current!==null?m.current.user:r??null,T=useRef(null),R=useRef(void 0),_=n??null;R.current!==_&&(R.current!==void 0&&(T.current=null),R.current=_);let w=T.current!==null?T.current.pet:n??null;(d.current===null||d.current.key!==u||d.current.runtime.isDisposed)&&(d.current!==null&&!d.current.runtime.isDisposed&&(c.current=d.current.runtime),d.current={key:u,runtime:Ql({config:l.withDefaults?l.withDefaults(t):t,user:g,activePet:w,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let b=d.current.runtime,x=useRef(null);useEffect(()=>{let C=d.current?.runtime;C===void 0||!C.isDisposed||x.current!==C&&(x.current=C,f());}),useEffect(()=>{let C=c.current;C!==null&&(c.current=null,C.dispose());});let A=g?.userRef??null;useLayoutEffect(()=>{b.setUser(g);},[b,A]),useLayoutEffect(()=>{b.setActivePet(w);},[b,w]),useEffect(()=>()=>b.dispose(),[b]),useEffect(()=>{a==="onMount"&&b.prepare(w===null?{}:{petRef:w});},[b,a,A,w]);let F=useMemo(()=>({setUser:i(C=>{m.current={user:C},b.setUser(C),f();},"setUser"),setActivePet:i(C=>{T.current={pet:C},b.setActivePet(C),f();},"setActivePet"),open:i(C=>b.open(C),"open"),prepare:i(C=>b.prepare(C),"prepare"),registerPet:i((C,I)=>b.registerPet(C,I),"registerPet"),updatePet:i((C,I)=>b.updatePet(C,I),"updatePet"),deletePet:i(C=>b.deletePet(C),"deletePet"),eraseUserData:i(()=>b.eraseUserData(),"eraseUserData"),logout:i(()=>{m.current={user:null};let C=b.logout();return f(),C},"logout")}),[b,f]),P=useMemo(()=>({runtime:b,handle:F,userRef:A,activePet:w,scopeEpoch:b.scopeEpoch}),[b,F,A,w,p]),v=createElement(Zr,{clientTheme:o??null,seams:l.theme,children:s});return createElement(Qr.Provider,{value:P},l.wrap?l.wrap(v):v)}i(su,"EverfurProviderCore");var ur="everfur:";function en(){try{if(typeof window>"u")return null;let e=window.localStorage;return e&&typeof e.getItem=="function"?e:null}catch{return null}}i(en,"storage");function Wo(){return {async getItem(e){try{return en()?.getItem(ur+e)??null}catch{return null}},async setItem(e,t){try{en()?.setItem(ur+e,t);}catch{}},async removeItem(e){try{en()?.removeItem(ur+e);}catch{}},async keys(e){try{let t=en();if(t===null)return [];let r=[],n=ur+e;for(let o=0;o<t.length;o+=1){let a=t.key(o);a!==null&&a.startsWith(n)&&r.push(a.slice(ur.length));}return Object.freeze(r)}catch{return []}}}}i(Wo,"createLocalStorageKv");var dr=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function qg(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[dr[t]]}}i(qg,"face");function lu(e,t){let{scale:r,scaleCaps:n}=e.type,o=n[t];return o>0?Math.min(r,o):r}i(lu,"tierScale");var Xg=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function Qg(e){return Xg.test(e)&&!e.includes("..")}i(Qg,"isBrandFontUrl");var uu=new Map;function Zg(e,t,r="400"){let n=e.trim(),o=`${n}
11
+ `));}l(),r.end();},"onError");e.addEventListener("message",o),e.addEventListener("done",a),e.addEventListener("error",s);function l(){if(!n){n=true,e.removeEventListener("message",o),e.removeEventListener("done",a),e.removeEventListener("error",s);try{e.close();}catch{}}}return i(l,"cleanup"),$f(r.source,l)}i(Vf,"eventSourceByteSource");async function*$f(e,t){try{yield*e;}finally{t();}}i($f,"sourceWithCleanup");function Wf(){let e=[],t=false,r=null,n=i(()=>{if(r){let a=r;r=null,a();}},"signal");async function*o(){for(;;){let a=e.shift();if(a!==void 0){yield a;continue}if(t)return;await new Promise(s=>{r=s;});}}return i(o,"gen"),{source:o(),push:i(a=>{e.push(a),n();},"push"),end:i(()=>{t=true,n();},"end")}}i(Wf,"createByteQueue");async function Kf(e,t){let r=t.fetchImpl??Ba(),n=ja(t.config.apiBaseUrl,e.path,e.query),o=Va(t.config,e.headers,"application/json",e.body!==void 0&&e.multipart===void 0),a=Zf(jf),s=Jf(a.signal,e.signal),l;try{l=await r(n,$a({...e,signal:s},o));}catch(c){return E(Jn(c))}finally{a.cancel();}let u=await Wa(l);return l.ok?M(u):E(Yf(l.status,u,Ua(l)))}i(Kf,"requestJson");function Ha(e){return {request:i(t=>Kf(t,e),"request"),stream:i((t,r)=>Gf(Qf(t,r),e),"stream")}}i(Ha,"createHttpTransport");async function*Gf(e,t){let r=ja(t.config.apiBaseUrl,e.path,e.query),n=Va(t.config,e.headers,"text/event-stream",e.body!==void 0&&e.multipart===void 0);if(t.eventSourceFactory){let l=t.eventSourceFactory(r,qf(e,n));yield*Dr(Vf(l),()=>Xf(l));return}let o=t.fetchImpl??Ba(),a;try{a=await o(r,$a(e,n));}catch(l){yield Da("",true,Ya(l));return}let s=Ua(a);if(!a.ok){let l=await Wa(a),u=Ka(l)??za(a.status),c=qa(l)||je(Ie(u));yield Da(u,c,Ga(l),s);return}if(a.body){yield*Dr(Ma(a.body),s);return}yield*Dr(Ma(null),s);}i(Gf,"streamFrames");function qf(e,t){return {method:e.method,headers:t,pollingInterval:0,...e.body!==void 0?{body:JSON.stringify(e.body)}:{}}}i(qf,"buildEventSourceInit");function Yf(e,t,r){let n=Ka(t),o=n?Ie(n):fa(e),a=Ga(t);return D(o,{httpStatus:e,...qa(t)?{retryable:true}:{},...r?{requestId:r}:{},...n?{wireCode:n}:{},...La(t)?{reasonCode:La(t)}:{},...a?{wireMessage:a}:{},...t!=null?{raw:t}:{}})}i(Yf,"errorFromResponse");function Jn(e){return D("internalError",{retryable:true,wireMessage:Ya(e)})}i(Jn,"networkError");function Ua(e){let t=e.headers.get(Na);return typeof t=="string"&&t.length>0?t:null}i(Ua,"requestIdOf");function Xf(e){if(typeof e.getResponseHeader!="function")return null;let t;try{t=e.getResponseHeader(Na);}catch{return null}return typeof t=="string"&&t.length>0?t:null}i(Xf,"eventSourceRequestId");function za(e){return e===401?"AUTH_EXPIRED":e===403?"ACCESS_DENIED":e===404?"NOT_FOUND":e===409?"IDEMPOTENCY_CONFLICT":e===421?"MISDIRECTED_REQUEST":e===429?"RATE_LIMITED":e===400||e===422?"INVALID_REQUEST":e===503||e>=500?"INTERNAL_ERROR":""}i(za,"statusToWireCode");function Da(e,t,r,n=null){return pe({code:e,retryable:t,wireMessage:r,synthesized:true,lastEventId:null,serverRequestId:n})}i(Da,"syntheticErrorFrame");function Ba(){let e=globalThis.fetch;if(typeof e!="function")throw new J("missing-peer-dependency","global fetch is unavailable; provide config.transport or an injected fetch implementation");return e}i(Ba,"getGlobalFetch");function ja(e,t,r){let n=t.startsWith("/")?t:`/${t}`,o=`${e}${n}`;if(r){let a=Object.entries(r).filter(s=>s[1]!==void 0).map(([s,l])=>`${encodeURIComponent(s)}=${encodeURIComponent(String(l))}`).join("&");a&&(o+=`?${a}`);}return o}i(ja,"buildUrl");function Va(e,t,r,n){let o={...Fa(e),accept:r};return n&&(o["content-type"]="application/json"),t&&Object.assign(o,t),o}i(Va,"mergeHeaders");function $a(e,t){let r={method:e.method,headers:t};return e.multipart!==void 0?r.body=e.multipart:e.body!==void 0&&(r.body=JSON.stringify(e.body)),e.signal&&(r.signal=e.signal),r}i($a,"buildInit");function Qf(e,t){return e.signal?e:{...e,signal:t}}i(Qf,"withSignal");function Zf(e){let t=new AbortController,r=setTimeout(()=>t.abort(),e);return {signal:t.signal,cancel:i(()=>clearTimeout(r),"cancel")}}i(Zf,"timeoutSignal");function Jf(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Jf,"mergeAbortSignals");async function Wa(e){try{return await e.json()}catch{return null}}i(Wa,"safeJson");function La(e){let t=e,r=t?.error?.reason_code??t?.reason_code;return typeof r=="string"&&r.length>0?r:null}i(La,"extractReasonCode");function Ka(e){let t=e,r=t?.error?.code??t?.code;return typeof r=="string"&&r.length>0?r:null}i(Ka,"extractWireCode");function Ga(e){let t=e,r=t?.error?.message??t?.message;return typeof r=="string"&&r.length>0?r:null}i(Ga,"extractWireMessage");function qa(e){let t=e;return t?.error?.retryable===true||t?.retryable===true}i(qa,"extractRetryable");function Ya(e){return e instanceof Error?e.message:typeof e=="string"?e:"network request failed"}i(Ya,"describeCause");var em=3e4,tm=qn*2,rm="idempotency-key",nm=new Set(["POST","PUT","PATCH","DELETE"]),om=Object.freeze({onEvent(){}}),im=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function am(e){let t=e.trim().replace(/[^A-Za-z0-9_.:-]/g,"-");return t.length===0?null:`efs_${t}`.slice(0,128)}i(am,"seededIdempotencyKey");function Te(e){let t=e.observer??om,r=e.timers??im,n=e.rng??Math.random,o=e.sleep??((f,m)=>Em(f,r,m)),a=e.maxAttempts??$t,s=e.unaryTimeoutMs??em,l=e.newIdempotencyKey??lm(),u=i(f=>{try{t.onEvent(f);}catch{}},"emit");async function c(f,m,y){let R=y?.maxAttempts,b=Math.max(1,R??a),T=y?.idempotent??nm.has(m.method),x=y?.idempotencyKey===void 0?null:am(y.idempotencyKey),_=T?x??l():null,w=sm(m,_),g=0;for(;;){let S=i(F=>Object.freeze({call:f,method:m.method,path:m.path,attempt:g,..._?{idempotencyKey:_}:{},...F}),"stamp");u(S({phase:"attempt"}));let I=bm(s,r),O=vm(I.signal,m.signal),k;try{k=await ka({...w,signal:O.signal},e.auth);}catch(F){k=E(Jn(F));}finally{O.dispose(),I.cancel();}if(k.ok)return u(S({phase:"settled",ok:true,reason:"ok"})),k;let v=k.error,C=dm(v,g,{maxAttempts:b,rng:n,now:r.now(),aborted:m.signal?.aborted===true,...R!==void 0?{perCallMaxAttempts:R}:{},...e.errorPolicy!==void 0?{policy:e.errorPolicy}:{}}),A={ok:false,code:v.code,reason:C.reason,...v.httpStatus!==void 0?{httpStatus:v.httpStatus}:{},...v.requestId!==void 0?{requestId:v.requestId}:{}};if(!C.retry)return u(S({phase:"settled",...A})),E(v);if(u(S({phase:"retry",...A,delayMs:C.delayMs})),await o(C.delayMs,m.signal),m.signal?.aborted===true)return u(S({phase:"settled",...A,reason:"aborted"})),E(v);g+=1;}}i(c,"send");async function d(f){return Wt(f,await hm(e.auth))}i(d,"authorize");async function*p(f,m,y){u(Object.freeze({call:f,phase:"stream.open",method:m.method,path:m.path,attempt:0}));try{yield*e.auth.transport.stream(m,y);}catch{yield pe({code:"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:null});}}return i(p,"stream"),Object.freeze({send:c,authorize:d,stream:p})}i(Te,"createRequestFunnel");function sm(e,t){let r={};for(let[n,o]of Object.entries(e.headers??{}))n.toLowerCase()!==rm&&(r[n]=o);return t!==null&&(r["Idempotency-Key"]=t),{...e,headers:r}}i(sm,"assembleHeaders");function lm(){let e=0;return ()=>`efk_${Date.now().toString(36)}_${(e++).toString(36)}_${Math.random().toString(36).slice(2,12)}`}i(lm,"defaultIdempotencyKeyFactory");var um=10;function dm(e,t,r){if(r.aborted)return {retry:false,reason:"aborted"};let n=cm(e);if(n==="quota")return {retry:false,reason:"daily-quota-exhausted"};if(n!=="burst"&&!je(e.code))return {retry:false,reason:"terminal-code"};let o=n==="burst"?"burst-throttle":"retryable-code";if(i(()=>{if(r.policy===void 0)return false;try{return !r.policy.shouldRetry(e.code,t)}catch{return false}},"policyVetoedRetry")())return {retry:false,reason:"terminal-code"};let s=i(()=>{if(r.policy===void 0)return null;let c;try{c=r.policy.maxAttempts(e.code);}catch{return null}return typeof c!="number"||!Number.isFinite(c)?null:Math.max(1,Math.min(um,Math.floor(c)))},"policyCeiling"),l=r.perCallMaxAttempts??s()??r.maxAttempts;if(t+1>=l)return {retry:false,reason:"attempts-exhausted"};let u=pm(e,r.now);return u!==null?u>tm?{retry:false,reason:"server-reset-beyond-budget"}:{retry:true,reason:o,delayMs:u}:{retry:true,reason:o,delayMs:Mr(t,r.rng)}}i(dm,"decideRetry");function cm(e){let t=e.code==="unknown"?Ie(gm(e.raw)):e.code;return t==="quotaExceeded"?"quota":t==="rateLimited"||e.httpStatus===429?"burst":null}i(cm,"throttleKind");function pm(e,t){let r=mm(e.raw);if(r!==null){let o=r-t;return o>0?o:0}let n=fm(e.raw);return n===null?null:Math.round(n*1e3)}i(pm,"retryOverrideMs");function fm(e){for(let t of eo(e)){let r=t.retry_after_seconds;if(typeof r=="number"&&Number.isFinite(r)&&r>=0)return r}return null}i(fm,"findRetryAfterSeconds");function mm(e){for(let t of eo(e)){let r=t.resets_at,n=ym(r);if(n!==null)return n}return null}i(mm,"findResetsAt");function eo(e){if(!Xa(e))return [];let t=[e];for(let r of ["error","detail"]){let n=e[r];Xa(n)&&t.push(n);}return t}i(eo,"candidateScopes");function ym(e){if(typeof e=="number"&&Number.isFinite(e))return e<1e11?Math.round(e*1e3):Math.round(e);if(typeof e=="string"&&e.trim().length>0){let t=Date.parse(e);return Number.isFinite(t)?t:null}return null}i(ym,"parseInstantMs");function gm(e){for(let t of eo(e)){let r=t.code;if(typeof r=="string"&&r.length>0)return r}return null}i(gm,"rawWireCode");function Xa(e){return typeof e=="object"&&e!==null}i(Xa,"isRecord");async function hm(e){return e.mode==="anonymous"?{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}:{mode:"personalized",token:await e.identity.currentToken(),userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{}}}i(hm,"resolveDeviceAuth");function bm(e,t){let r=new AbortController,n=t.setTimeout(()=>r.abort(),e);return {signal:r.signal,cancel:i(()=>t.clearTimeout(n),"cancel")}}i(bm,"boundedSignal");function vm(e,t){let r=i(()=>{},"noop");if(!t)return {signal:e,dispose:r};let n=new AbortController;if(e.aborted||t.aborted)return n.abort(),{signal:n.signal,dispose:r};let o=i(()=>n.abort(),"onAbort");return e.addEventListener("abort",o,{once:true}),t.addEventListener("abort",o,{once:true}),{signal:n.signal,dispose:i(()=>{e.removeEventListener("abort",o),t.removeEventListener("abort",o);},"dispose")}}i(vm,"mergeSignals");function Em(e,t,r){return e<=0||r?.aborted===true?Promise.resolve():new Promise(n=>{let o=t.setTimeout(()=>{r?.removeEventListener("abort",a),n();},e),a=i(()=>{t.clearTimeout(o),n();},"onAbort");r?.addEventListener("abort",a,{once:true});})}i(Em,"delayAbortable");function Ee(e){for(let t=0;t<e.length;t+=1){let r=e.charCodeAt(t);if(r>=55296&&r<=56319){let n=e.charCodeAt(t+1);if(!(n>=56320&&n<=57343))return true;t+=1;}else if(r>=56320&&r<=57343)return true}return false}i(Ee,"hasLoneSurrogate");function ct(e){return [...e].length}i(ct,"serverLength");var Lr=Object.freeze(["better","same","worse"]),ro=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Qa(e){return E(D("validationFailed",{retryable:false,wireMessage:e}))}i(Qa,"invalid");function to(){return E(D("internalError",{retryable:false}))}i(to,"malformed");function Za(e){return typeof e!="string"||e.trim().length===0?D("validationFailed",{retryable:false,wireMessage:"pet_ref must not be blank"}):Ee(e)?D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}):`/widget/v1/pets/${encodeURIComponent(e)}/cases`}i(Za,"petPath");var Ve=i(e=>typeof e=="string"?e:null,"str"),Ja=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"count");function es(e){if(typeof e!="object"||e===null)return null;let t=e,r=Ve(t.case_id),n=Ve(t.status);if(r===null||n===null)return null;let o=Ve(t.last_response);return Object.freeze({caseId:r,status:n,bodyLocation:Ve(t.body_location),lastResponse:o!==null&&Lr.includes(o)?o:null,checkInDueAt:Ve(t.check_in_due_at),openedAt:Ve(t.opened_at),resolvedAt:Ve(t.resolved_at),resolutionText:Ve(t.resolution_text),checkinAskCount:Ja(t.checkin_ask_count),checkinAnswerCount:Ja(t.checkin_answer_count)})}i(es,"caseFromWire");function ts(e){return {async list(t,r){let n=Za(t);if(typeof n!="string")return E(n);let o=await e.send("cases.list",{method:"GET",path:n,...r?.signal?{signal:r.signal}:{}});if(!o.ok)return E(o.error);let a=typeof o.value=="object"&&o.value!==null?o.value.cases:null;if(!Array.isArray(a))return to();let s=a.map(es);return s.every(l=>l!==null)?M(Object.freeze(s)):to()},async checkin(t,r,n,o){let a=Za(t);if(typeof a!="string")return E(a);if(typeof r!="string"||!ro.test(r))return Qa("case_id must be a UUID");if(!Lr.includes(n))return Qa("response must be one of better, same, worse");let s=await e.send("cases.checkin",{method:"POST",path:`${a}/${r}/checkin`,body:{response:n},...o?.signal?{signal:o.signal}:{}});if(!s.ok)return E(s.error);let l=typeof s.value=="object"&&s.value!==null?s.value:{},u=es(l.case);return u===null?to():M(Object.freeze({case:u,ctaDeepLink:Ve(l.cta_deep_link)}))}}}i(ts,"createCasesRepositoryOver");var rs=Object.freeze({async presignedPut(){return Promise.reject(new Error("UploadPort is unavailable; no presigned-upload adapter was injected"))}});var ns=Object.freeze({setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")});function Hr(e,t,r){return new Promise(n=>{if(t.aborted){n();return}let o={handle:void 0},a=i(()=>{r.clearTimeout(o.handle),t.removeEventListener("abort",a),n();},"done");o.handle=r.setTimeout(a,e),t.addEventListener("abort",a,{once:true});})}i(Hr,"delayAbortable");function Ur(e,t){if(!t)return e;let r=new AbortController;if(e.aborted||t.aborted)return r.abort(),r.signal;let n=i(()=>r.abort(),"onAbort");return e.addEventListener("abort",n,{once:true}),t.addEventListener("abort",n,{once:true}),r.signal}i(Ur,"mergeSignals");var no=class no{constructor(t){this.listeners=new Set;this.epoch=0;this.inFlight=null;this.snapshot=Object.freeze({...t});}subscribe(t){return this.listeners.add(t),()=>{this.listeners.delete(t);}}getSnapshot(){return this.snapshot}patch(t){this.snapshot=Object.freeze({...this.snapshot,...t});for(let r of this.listeners)r();}beginOperation(t){this.inFlight?.abort();let r=new AbortController;this.inFlight=r;let n=this.epoch;return {signal:t?Ur(r.signal,t):r.signal,epoch:n,settle:i(()=>{this.inFlight===r&&(this.inFlight=null);},"settle")}}alive(t){return t===this.epoch}rescope(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null;}dispose(){this.epoch+=1,this.inFlight?.abort(),this.inFlight=null,this.listeners.clear();}};i(no,"MediaStore");var Nr=no;function io(e,t,r){return Object.freeze({id:e,role:"user",text:t,createdAt:r,pending:true})}i(io,"makeUser");function ao(e,t,r){return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}i(ao,"makeAssistant");function qt(e){return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}i(qt,"stripPending");function os(e,t){let r={id:e.id,role:e.role,text:e.text+t,createdAt:e.createdAt};return e.citations&&(r.citations=e.citations),e.responseId&&(r.responseId=e.responseId),Object.freeze(r)}i(os,"appendText");function so(e,t){let r={id:t.messageId?t.messageId:e.id,role:"assistant",text:e.text,createdAt:e.createdAt};return t.citations.length>0&&(r.citations=t.citations),t.messageId&&(r.responseId=t.messageId),r.urgencyLevel=t.urgencyLevel,r.urgencyReason=t.urgencyReason,r.urgencyProvided=t.urgencyProvided,Object.freeze(r)}i(so,"finalizeAssistant");function is(e){return Object.freeze({status:e.status,messages:Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}i(is,"freezeSnapshot");function L(e,t,r){return D(e,{retryable:t,...r?{wireMessage:r}:{}})}i(L,"makeError");function lo(e){let t=Ie(e.code);return D(t,{retryable:e.retryable||Fr(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}i(lo,"errorFromFrame");function Ae(e){return pe({code:Cm(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}i(Ae,"synthErrorFrame");function Cm(e){switch(e){case "authExpired":return "AUTH_EXPIRED";case "authRejected":return "AuthorizationException";case "sessionRequired":return "session_required";case "accessDenied":return "ACCESS_DENIED";case "paymentRequired":return "TIER_UPGRADE_REQUIRED";case "quotaExceeded":return "QUOTA_EXCEEDED";case "rateLimited":return "RATE_LIMITED";case "validationFailed":return "ValidationException";case "sdkUpdateRequired":return "invalidRequest";case "conflict":return "ConflictException";case "idempotencyConflict":return "IDEMPOTENCY_CONFLICT";case "idempotencyInFlight":return "IDEMPOTENCY_KEY_IN_FLIGHT";case "conversationNotFound":return "CONVERSATION_NOT_FOUND";case "petNotFound":return "PET_NOT_FOUND";case "resourceNotFound":return "ResourceNotFoundException";case "streamTimeout":return "STREAM_TIMEOUT";case "mediaUploadFailed":return "MEDIA_UPLOAD_FAILED";case "moderationBlocked":return "MODERATION_BLOCKED";case "upstreamLlmTimeout":return "UPSTREAM_LLM_TIMEOUT";case "internalError":return "INTERNAL_ERROR";case "notImplemented":return "NotImplementedException";case "serviceUnavailable":return "ServiceUnavailableException";case "streamIncomplete":return "STREAM_INCOMPLETE";case "unknown":return "UNKNOWN";default:return Je(e)}}i(Cm,"canonicalWireCode");function as(e){let t=Array.isArray(e)?e:oo(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let n of t){if(!oo(n))continue;let o=Gt(n.category)??Gt(n.title)??"",a=Rm(n.prompts??n.questions);o.length===0&&a.length===0||r.push(Object.freeze({category:o,prompts:Object.freeze(a)}));}return Object.freeze(r)}i(as,"parsePromptCategories");function uo(e){let t=new Set,r=[];for(let n of e)for(let o of n.prompts){let a=o.trim();a.length===0||t.has(a)||(t.add(a),r.push(a));}return r}i(uo,"flattenPrompts");function oo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}i(oo,"isPlainObject");function Gt(e){return typeof e=="string"?e:null}i(Gt,"asStr");function Rm(e){if(!Array.isArray(e))return [];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(oo(r)){let n=Gt(r.text)??Gt(r.prompt)??Gt(r.title);n!==null&&t.push(n);}return t}i(Rm,"asPromptTextList");function ss(){let e=0;return ()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}i(ss,"defaultIdFactory");function ls(){let e=0;return ()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}i(ls,"defaultIdempotencyFactory");var ds={setTimeout:i((e,t)=>setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>clearTimeout(e),"clearTimeout"),now:i(()=>Date.now(),"now")};async function*cs(e,t,r,n){let o=e[Symbol.asyncIterator](),a=us(t.overallMs,n),s=us(t.idleMs,n),l=Tm(r);try{for(;;){if(r.aborted)return;let u=o.next().then(p=>({tag:"next",value:p}),()=>({tag:"streamError"})),c=await Promise.race([u,s.promise.then(()=>({tag:"idle"})),a.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(c.tag==="abort")return;if(c.tag==="streamError"){if(r.aborted)return;yield xm();return}if(c.tag==="idle"||c.tag==="overall"){yield Sm();return}let d=c.value;if(d.done||(s.reset(t.idleMs),yield d.value,d.value.terminal))return}}finally{s.cancel(),a.cancel(),Promise.resolve(o.return?.(void 0)).catch(()=>{});}}i(cs,"withWatchdog");function Sm(){return pe({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(Sm,"synthTimeoutFrame");function xm(){return pe({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}i(xm,"synthStreamErrorFrame");function us(e,t){let r=i(()=>{},"resolveFn"),n=new Promise(a=>{r=a;}),o=t.setTimeout(()=>r(),e);return {promise:n,reset(a){t.clearTimeout(o),o=t.setTimeout(()=>r(),a);},cancel(){t.clearTimeout(o);}}}i(us,"deadline");function Tm(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true});})}i(Tm,"abortPromise");var ps=128,fs=128,ms=/[\u0000-\u001F\u007F]/,km=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Pm(e){let t=e,r=ct(t);if(r===0||r>fs)throw new J("invalid-argument",`petRef must be 1..${fs} characters`);if(ms.test(t))throw new J("invalid-argument","petRef must be printable (no control characters)");return t}i(Pm,"petRef");function _m(e){let t=e,r=ct(t);if(r===0||r>ps)throw new J("invalid-argument",`userRef must be 1..${ps} characters`);if(t.includes("@"))throw new J("invalid-argument","userRef must not contain '@'");if(ms.test(t))throw new J("invalid-argument","userRef must be printable (no control characters)");return t}i(_m,"userRef");function wm(e){if(!km.test(e))throw new J("invalid-argument","conversationId must be a UUID");return e}i(wm,"conversationId");var Im="checkin",Am=/^\d{4}-\d{2}-\d{2}$/,zr="watching";function ys(e){return e.status!=null&&e.status!==zr}i(ys,"isCheckinSettled");function gs(e){let{askCount:t,answerCount:r}=e;return typeof t!="number"||!Number.isFinite(t)||typeof r!="number"||!Number.isFinite(r)||t<=0?true:r>=t}i(gs,"isLiveAskAnswered");function co(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,o]=t;return r!==Im||n===void 0||o===void 0||!ro.test(n)||!Am.test(o)?null:{caseId:n,dueDay:o}}i(co,"parseCheckinOrigin");function hs(e){return co(e)?.caseId??null}i(hs,"parseCheckinOriginRef");function po(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return E(D("validationFailed"));let r=[];for(let[n,o]of [["cursor",e?.cursor],["pet_ref",e?.petRef]])if(o!==void 0){if(typeof o!="string"||o.length===0||Ee(o))return E(D("validationFailed"));r.push(`${n}=${encodeURIComponent(o)}`);}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),M(r.length?`?${r.join("&")}`:"")}i(po,"historyQuery");function Qt(e){return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(e)}i(Qt,"validConversationId");function Xt(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}i(Xt,"object");function bs(e){return e==null||typeof e=="string"&&e.length>0&&!Ee(e)}i(bs,"cursor");function Yt(){return E(D("internalError",{retryable:false}))}i(Yt,"malformed");function vs(e){let t=Xt(e);if(!t||!Array.isArray(t.conversations)||!bs(t.next_cursor))return Yt();let r=[];for(let n of t.conversations){let o=Xt(n);if(!o||typeof o.conversation_id!="string"||!Qt(o.conversation_id)||!(o.title==null||typeof o.title=="string")||typeof o.created_at!="string"||typeof o.updated_at!="string")return Yt();let a=o.unread_message_count;if(!(a==null||Number.isInteger(a)&&a>=0))return Yt();r.push(Object.freeze({id:o.conversation_id,title:o.title??null,createdAt:o.created_at,updatedAt:o.updated_at,unreadCount:a??null}));}return M(Object.freeze({conversations:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(vs,"mapConversationPage");function Es(e){let t=Xt(e);if(!t||!Array.isArray(t.messages)||!bs(t.next_cursor))return Yt();let r=[],n=new Set;for(let o of t.messages){let a=Xt(o);if(!a||typeof a.message_id!="string"||!Qt(a.message_id)||typeof a.role!="string"||typeof a.content!="string"||typeof a.created_at!="string")return Yt();if(a.role!=="user"&&a.role!=="assistant"||n.has(a.message_id))continue;n.add(a.message_id);let s=typeof a.proactive_origin_ref=="string"?a.proactive_origin_ref:null,l=a.role==="assistant"?hs(s):null;r.push(Object.freeze({id:a.message_id,role:a.role,text:a.content,createdAt:a.created_at,...a.role==="assistant"?{responseId:a.message_id}:{},...a.urgency_level!==void 0?{urgencyLevel:Om(a.urgency_level)}:{},...Array.isArray(a.citations)?{citations:Fm(a.citations)}:{},...s!==null?{proactiveOriginRef:s}:{},...l!==null?{checkin:Object.freeze({caseId:l,answer:null,resolutionText:null,status:null})}:{}}));}return M(Object.freeze({messages:Object.freeze(r),nextCursor:t.next_cursor??null}))}i(Es,"mapMessagePage");function Om(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Om,"normalizeUrgency");function Fm(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];return Object.freeze(e.flatMap(r=>{let n=Xt(r);if(!n||typeof n.source_name!="string"||typeof n.authority_tier!="string")return [];let o={};for(let a of t){let s=n[a];(typeof s=="string"||s===null)&&(o[a]=s);}return [Object.freeze(o)]}))}i(Fm,"historyCitations");var fo=Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Zt=4e3;var pt=4e3;function Cs(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:L("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(t=>typeof t!="string"||t.trim().length===0)?{reason:"bad_image_key",error:L("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}i(Cs,"validateImageKeys");function yo(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return {reason:"empty",error:L("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>pt?{reason:"too_long",error:L("validationFailed",false,`message is ${r} characters; the server accepts at most ${pt}`)}:null}i(yo,"validateMessageText");function Rs(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}i(Rs,"urgencyTier");async function*Jt(e){yield e;}i(Jt,"singleFrameStream");async function*Ss(){}i(Ss,"emptyStream");var Mm=6e4,Dm=18e4,Lm=24,Nm=512,Hm=false;function xs(e){return new go(e)}i(xs,"createChatController");var ho=class ho extends Nr{constructor(r){super(is({status:"idle",messages:[],conversationId:r.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=new Set;this.lastTurn=null;this.unadoptedCreate=null;this.lastResponseIdValue=null;this.historyGeneration=0;this.disposed=false;this.bootstrapPrompts=[];this.scopePrompts=[];this.replyPrompts=null;this.unreadByConversation=new Map;this.classifiedMessageIds=new Set;this.pendingDelta="";this.flushHandle=null;this.auth=r.auth,this.funnel=r.funnel??Te({auth:r.auth,...r.errorPolicy?{errorPolicy:r.errorPolicy}:{}}),this.petRef=r.petRef??null,this.cases=ts(this.funnel),this.telemetry=r.telemetry??Ar,this.errorPolicy=r.errorPolicy??ya,this.timers=r.timers??ds,this.rng=r.rng??Math.random,this.newId=r.newId??ss(),this.makeIdempotencyKey=r.makeIdempotencyKey??ls(),this.budget={idleMs:r.budget?.idleMs??Mm,overallMs:r.budget?.overallMs??Dm};}patch(r){if(r.messages!==void 0){let n=Object.freeze([...r.messages]);super.patch({...r,messages:n});return}super.patch(r);}send(r,n,o){let a=n??{};if(this.disposed||this.snapshot.isBootstrapping){let u=L(this.disposed?"accessDenied":"internalError",!this.disposed);return o?(o.onError(u),()=>{}):Jt(Ae(u))}let s=yo(r)??Cs(a.imageS3Keys);if(s!==null)return this.telemetry.track("chat.send.rejected",{reason:s.reason}),this.patch({status:"error",isStreaming:false,error:s.error}),o?(o.onError(s.error),()=>{}):Jt(Ae(s.error));if(o)return this.driveWithHandlers(r,a,o);let l=this.beginTurn(r,a);return this.runTurn(l,a.signal)}askEverfur(r,n){if(this.disposed)return Jt(Ae(L("accessDenied",false)));let o=yo(r);return o!==null?(this.telemetry.track("chat.send.rejected",{reason:o.reason}),Jt(Ae(o.error))):(this.resetThread(),this.send(r,n??{}))}retryLast(){let r=this.lastTurn;if(r===null){let a=this.snapshot.conversationId;return a!==null&&this.snapshot.status==="error"?this.retryHistory(a):Ss()}r.assistantMessageId=null,r.sawDelta=false,r.conversationIdOverride=null,this.discardPendingDelta();let o=this.snapshot.messages.some(a=>a.id===r.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,io(r.userMessageId,r.text,this.stamp())];return this.patch({error:null,stopped:false,messages:o}),this.runTurn(r,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let r=this.snapshot.messages.some(o=>o.role==="user"&&o.pending===true),n=r?this.snapshot.messages.map(o=>o.pending===true?qt(o):o):this.snapshot.messages;(this.snapshot.status==="streaming"||r)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...r?{messages:n,stopped:true}:{}});}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.reflectUnreadDot();}resetThread(r=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=r,this.replyPrompts=null,this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:r,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false});}newConversation(){this.disposed||this.resetThread(this.scopePrompts);}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let r of this.handlerTeardowns)r();this.handlerTeardowns.clear(),super.dispose();}adoptConversation(r){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==r&&this.patch({conversationId:r}));}adoptPrompts(r){if(this.disposed)return;let n=Object.freeze(uo(r));this.bootstrapPrompts=n,this.scopePrompts=n,this.replyPrompts===null&&(n.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:n}));}async listConversations(r){return this.listConversationsWith(r)}async listConversationsWith(r,n){let o=po(r,100);if(!o.ok)return o;let a=this.epoch;if(this.disposed)return E(L("accessDenied",false));let s=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${o.value}`},r?.signal,n);if(!this.alive(a)||this.disposed)return E(L("accessDenied",false));if(!s.ok)return s;let l=vs(s.value);if(l.ok){for(let d of l.value.conversations)d.unreadCount!==null&&this.unreadByConversation.set(d.id,d.unreadCount);let u=this.snapshot.conversationId,c=u===null?void 0:this.unreadByConversation.get(u);c!==void 0&&c!==this.snapshot.unreadCount&&this.patch({unreadCount:c}),this.reflectUnreadDot();}return l}reflectUnreadDot(){let r=false;for(let n of this.unreadByConversation.values())if(n>0){r=true;break}r!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:r});}async openCheckin(r){if(this.disposed)return E(L("accessDenied",false));let n=r?.conversationId??null;if(n!==null){let u=await this.resumeConversation(n);return u.ok?M(n):E(u.error)}let o=r?.petRef??this.petRef,a=await this.listConversations({...o===null?{}:{petRef:o},limit:1});if(!a.ok)return E(a.error);let s=a.value.conversations[0];if(s===void 0)return M(null);let l=await this.resumeConversation(s.id);return l.ok?M(s.id):E(l.error)}async markRead(r){if(this.disposed)return E(L("accessDenied",false));let n=this.snapshot.conversationId;if(n===null)return M(void 0);let o=this.epoch,a=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${n}/read`},r?.signal);return !this.alive(o)||this.disposed?E(L("accessDenied",false)):a.ok?(this.unreadByConversation.set(n,0),this.snapshot.conversationId===n&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),M(void 0)):E(a.error)}async submitFeedback(r,n,o,a){if(this.disposed)return E(L("accessDenied",false));if(typeof r!="string"||r.trim().length===0||Ee(r))return E(L("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!fo.includes(n))return E(L("validationFailed",false,`feedback_type must be one of ${fo.join(", ")}`));let s=typeof o=="string"?o.trim():"";if([...s].length>Zt)return E(L("validationFailed",false,`notes is over ${Zt} characters`));let l={feedback_type:n};s.length>0&&(l.notes=s);let u=this.epoch,c=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(r)}/feedback`,body:l},a?.signal);if(!this.alive(u)||this.disposed)return E(L("accessDenied",false));if(!c.ok)return E(c.error);let d=c.value?.feedback_id;return M(Object.freeze({feedbackId:typeof d=="string"?d:""}))}async answerCheckin(r,n,o){if(this.disposed)return E(L("accessDenied",false));let a=o?.petRef??this.petRef;if(a===null)return E(L("validationFailed",false,"a check-in needs the pet the case belongs to"));let s=this.epoch,l=await this.cases.checkin(a,r,n,o?.signal?{signal:o.signal}:{});if(!this.alive(s)||this.disposed)return E(L("accessDenied",false));if(!l.ok)return l;let u=l.value.case.openedAt,c=Object.freeze({caseId:r,answer:n,resolutionText:l.value.case.resolutionText,status:l.value.case.status??null,...u!==null?{openedAt:u}:{}}),d=i(p=>p.checkin?.caseId===r,"carries");return this.snapshot.messages.some(d)&&this.patch({messages:this.snapshot.messages.map(p=>d(p)?Object.freeze({...p,checkin:c}):p)}),l}async getMessages(r,n){if(!Qt(r))return E(L("validationFailed",false));let o=po(n,200);if(!o.ok)return o;let a=this.epoch;if(this.disposed)return E(L("accessDenied",false));let s=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${r}/messages${o.value}`},n?.signal);return !this.alive(a)||this.disposed?E(L("accessDenied",false)):s.ok?Es(s.value):s}async resumeConversation(r){if(this.disposed)return E(L("accessDenied",false));if(!Qt(r))return E(L("validationFailed",false));this.resetThread();let n=this.historyGeneration;this.patch({conversationId:r,isBootstrapping:true,isLoadingHistory:true});let o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return E(L("accessDenied",false));if(!o.ok)return this.patch({status:"error",error:o.error,isBootstrapping:false,isLoadingHistory:false}),o;let a=this.unreadByConversation.get(r)??null;return this.patch({messages:o.value.messages,historyCursor:o.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:a}),this.stampCheckinStatuses(n),a!==null&&a>0&&this.markRead(),M(void 0)}async stampCheckinStatuses(r){let n=this.petRef;if(n===null||!this.snapshot.messages.some(c=>c.checkin!==void 0&&c.checkin.status===null))return;let o=await this.cases.list(n);if(!o.ok||r!==this.historyGeneration||this.disposed)return;let a=new Set(o.value.filter(c=>c.status===zr).map(c=>c.caseId)),s=new Map(o.value.map(c=>[c.caseId,c])),l=false,u=this.snapshot.messages.map(c=>{let d=c.checkin;if(d===void 0||d.status!==null)return c;l=true;let p=s.get(d.caseId),f=d.openedAt??p?.openedAt??null,m=a.has(d.caseId),y=p!==void 0&&(!m||gs({askCount:p.checkinAskCount,answerCount:p.checkinAnswerCount}))?p.lastResponse:null;return Object.freeze({...c,checkin:Object.freeze({...d,status:m?zr:p?.status??"resolved",answer:d.answer??y,resolutionText:d.resolutionText??p?.resolutionText??null,...f!==null?{openedAt:f}:{}})})});l&&this.patch({messages:u});}async refreshActiveThread(){if(this.disposed)return E(L("accessDenied",false));let r=this.snapshot.conversationId;if(r===null||this.snapshot.isStreaming)return M(void 0);let n=this.historyGeneration,o=await this.getMessages(r);if(n!==this.historyGeneration||this.disposed)return E(L("accessDenied",false));if(!o.ok)return E(o.error);let a=new Set(this.snapshot.messages.map(l=>l.id)),s=o.value.messages.filter(l=>!a.has(l.id));return s.length>0&&this.patch({messages:[...this.snapshot.messages,...s]}),await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),M(void 0)}async loadOlderMessages(){if(this.disposed)return E(L("accessDenied",false));let r=this.snapshot.conversationId,n=this.snapshot.historyCursor;if(!r||!n||this.snapshot.isLoadingHistory)return M(void 0);let o=this.historyGeneration;this.patch({isLoadingHistory:true});let a=await this.getMessages(r,{cursor:n});if(o!==this.historyGeneration||this.disposed)return E(L("accessDenied",false));if(this.patch({isLoadingHistory:false}),!a.ok)return a;let s=new Set(this.snapshot.messages.map(u=>u.id)),l=a.value.messages.filter(u=>!s.has(u.id));return this.patch({messages:[...l,...this.snapshot.messages],historyCursor:a.value.nextCursor===n?null:a.value.nextCursor}),M(void 0)}async*retryHistory(r){let n=await this.resumeConversation(r);n.ok||(yield Ae(n.error));}async primeConversation(r){if(this.disposed)return E(L("accessDenied",false));let n=r?.petRef??null,o={petRef:n,settled:this.primeBounded(n)};this.unadoptedCreate=o;let a=await o.settled;return this.disposed?E(L("accessDenied",false)):(!a.ok&&this.unadoptedCreate===o&&(this.unadoptedCreate=null),a)}async primeBounded(r){let n=await this.headThreadWithUnread(r);if(n!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(n)).ok)return M(n);let o=this.snapshot.conversationId;return o!==null?M(o):this.createConversationBounded(r)}async headThreadWithUnread(r){let n=await this.listConversationsWith({...r===null?{}:{petRef:r},limit:1},{maxAttempts:1});if(!n.ok)return null;let o=n.value.conversations[0];return o===void 0||o.unreadCount===null||o.unreadCount<=0?null:o.id}async createConversation(r){let n=this.epoch;if(this.disposed)return E(L("accessDenied",false));let o=r?.petRef??null,a={petRef:o,settled:this.createConversationBounded(o)};this.unadoptedCreate=a;let s=await a.settled;return !this.alive(n)||this.disposed?E(L("accessDenied",false)):(!s.ok&&this.unadoptedCreate===a&&(this.unadoptedCreate=null),s)}async createConversationBounded(r,n){let o={method:"POST",path:"/widget/v1/conversations",body:r?{pet_ref:r}:{}},a=await this.authedUnary("chat.createConversation",o,n,{maxAttempts:1});if(!a.ok)return E(a.error);let s=a.value?.conversation_id??a.value?.id;return typeof s!="string"||s.length===0?E(L("internalError",true)):M(s)}async getPrompts(r){let n=this.epoch;if(this.disposed)return E(L("accessDenied",false));let o=r?.petRef??null;if(o!==null&&Ee(o))return E(D("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let a=o!==null?`?pet_ref=${encodeURIComponent(o)}`:"",s=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${a}`});return !this.alive(n)||this.disposed?E(L("accessDenied",false)):s.ok?M(as(s.value)):E(s.error)}async authedUnary(r,n,o,a){return this.funnel.send(r,o?{...n,signal:o}:n,a)}driveWithHandlers(r,n,o){let a=new AbortController,s=Ur(a.signal,n.signal),l=this.beginTurn(r,n),u=this.runTurn(l,s),c=false,d=i(()=>{c||(c=true,a.abort(),this.handlerTeardowns.delete(d));},"teardown");return this.handlerTeardowns.add(d),(async()=>{for await(let p of u){if(c)break;o.onFrame(p),p.kind==="done"&&o.onDone(this.lastResponseIdValue);}!c&&this.snapshot.status==="error"&&this.snapshot.error!==null&&o.onError(this.snapshot.error),this.handlerTeardowns.delete(d);})(),d}beginTurn(r,n){let o={epoch:this.epoch,text:r,petRef:n.petRef??null,imageS3Keys:Object.freeze([...n.imageS3Keys??[]]),idempotencyKey:n.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:n.conversationId??null};return this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,io(o.userMessageId,r,this.stamp())]}),o}async*runTurn(r,n){let o=this.beginOperation(n);r.epoch=o.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=r;let a=0,s=false,l=false;try{for(;;){if(o.signal.aborted||!this.alive(o.epoch))return;let u=r.conversationIdOverride===null&&this.snapshot.conversationId===null,c=u?this.unadoptedCreate:null;if(c!==null&&(r.petRef===null||r.petRef===c.petRef)){let b=await c.settled;if(o.signal.aborted||!this.alive(o.epoch))return;b.ok&&this.snapshot.conversationId===null&&this.adoptConversation(b.value);}if(u&&this.snapshot.conversationId===null){let b=await this.createConversationBounded(r.petRef,o.signal);if(o.signal.aborted||!this.alive(o.epoch))return;if(!b.ok){yield*this.emitTerminal(r,b.error,Ae(b.error));return}this.adoptConversation(b.value);}let d=r.conversationIdOverride??this.snapshot.conversationId;if(d===null){let b=L("internalError",!0);yield*this.emitTerminal(r,b,Ae(b));return}this.clearAssistantInProgress(r);let p=new AbortController,f=Ur(o.signal,p.signal),m=null;try{let b;try{b=await this.funnel.authorize(this.buildSendRequest(r,d));}catch{let x=this.authRejected();yield*this.emitTerminal(r,x,Ae(x));return}if(o.signal.aborted||!this.alive(o.epoch))return;let T=this.funnel.stream("chat.send",b,f);for await(let x of cs(T,this.budget,f,this.timers)){if(!this.alive(o.epoch))return;if(x.kind==="error"&&x.terminal){m=x;break}if(this.applyFrame(x,r),yield x,x.terminal){o.settle();return}}}finally{p.abort();}if(o.signal.aborted||!this.alive(o.epoch))return;if(m===null){if(this.snapshot.status==="complete")return;let b=L("streamIncomplete",!0);yield*this.emitTerminal(r,b,Ae(b));return}let y=Ie(m.code);if(y==="authExpired"&&this.auth.mode==="personalized"&&!l){l=!0,this.telemetry.track("chat.auth.refresh",{});let b=await this.tryForceRefresh();if(o.signal.aborted||!this.alive(o.epoch))return;if(!b){let T=this.authRejected();yield*this.emitTerminal(r,T,m);return}this.patch({reconnecting:!0});continue}if(y==="authExpired"){this.telemetry.track("chat.auth.rejected",{});let b=this.authRejected();yield*this.emitTerminal(r,b,m);return}if(y==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(r,lo(m),m);return}if(ma(y)&&!s){s=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),r.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let R=m.retryable&&Fr(y,!0);if(Hm&&R&&a+1<this.errorPolicy.maxAttempts(y));yield*this.emitTerminal(r,lo(m),m);return}}finally{o.settle();}}*emitTerminal(r,n,o){this.applyError(r,n),yield o;}applyFrame(r,n){switch(r.kind){case "accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case "heartbeat":return;case "delta":this.applyDelta(r.delta,n);return;case "done":this.applyDone(r,n);return;case "analysisStarted":case "analysisComplete":return;case "unknown":this.telemetry.track("chat.frame.unknown",{});return;case "error":return;default:return Je(r)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(r,n){if(n.assistantMessageId===null){let o=this.newId();n.assistantMessageId=o,n.sawDelta=true;let a=this.snapshot.messages.map(s=>s.id===n.userMessageId&&s.pending===true?qt(s):s);this.patch({status:"streaming",isStreaming:true,messages:[...a,ao(o,r,this.stamp())]});return}if(this.pendingDelta+=r,this.pendingDelta.length>=Nm){this.flushPendingDelta(n);return}this.scheduleDeltaFlush(n);}scheduleDeltaFlush(r){if(this.flushHandle!==null)return;let n=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(n)){this.pendingDelta="";return}this.flushPendingDelta(r);},Lm);}flushPendingDelta(r){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let n=this.pendingDelta;this.pendingDelta="";let o=r.assistantMessageId;if(o===null)return;let a=this.snapshot.messages.map(s=>s.id===o?os(s,n):s);this.patch({messages:a});}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta="";}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null);}applyDone(r,n){this.flushPendingDelta(n),this.lastResponseIdValue=r.messageId?r.messageId:null;let o=r.conversationId?r.conversationId:this.snapshot.conversationId,a;if(n.assistantMessageId!==null)a=this.snapshot.messages.map(l=>l.id===n.assistantMessageId?so(l,r):l);else {let l=this.newId();n.assistantMessageId=l,n.sawDelta=true,a=[...this.snapshot.messages.map(c=>c.id===n.userMessageId&&c.pending===true?qt(c):c),so(ao(l,"",this.stamp()),r)];}let s=uo([{category:"",prompts:r.followUpQuestions}]);this.replyPrompts=s.length>0?Object.freeze(s):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:o,messages:a,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!r.urgencyProvided&&o!==null&&this.classifyTurn(o,this.lastResponseIdValue);}async classifyTurn(r,n){if(n===null||this.disposed)return;let o=String(n);if(this.classifiedMessageIds.has(o))return;this.classifiedMessageIds.add(o);let a=this.epoch,s=this.historyGeneration,l=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${r}/classify`});if(!l.ok||!this.alive(a)||this.disposed||s!==this.historyGeneration||this.snapshot.conversationId!==r)return;let u=Rs(l.value?.urgency),c=typeof l.value?.reason=="string"?l.value.reason:null,d=i(p=>p.responseId===n,"carries");this.snapshot.messages.some(d)&&this.patch({messages:this.snapshot.messages.map(p=>d(p)?Object.freeze({...p,urgencyLevel:u,urgencyReason:c,urgencyProvided:true}):p)});}applyError(r,n){this.flushPendingDelta(r);let o=this.snapshot.messages.map(a=>a.id===r.userMessageId&&a.pending===true?qt(a):a);this.patch({status:"error",isStreaming:false,error:n,messages:o,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(n);}catch{}}clearAssistantInProgress(r){if(this.discardPendingDelta(),r.assistantMessageId===null)return;let n=r.assistantMessageId;r.assistantMessageId=null,r.sawDelta=false;let o=this.snapshot.messages.filter(a=>a.id!==n);o.length!==this.snapshot.messages.length&&this.patch({messages:o});}buildSendRequest(r,n){let o={message:r.text};return r.imageS3Keys.length>0&&(o.image_s3_keys=r.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${n}/messages`,body:o,headers:{"Idempotency-Key":r.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}authRejected(){return L("authRejected",false)}};i(ho,"ChatControllerImpl");var go=ho;async function Ps(e,t){let{controller:r}=t,n=e.petRef??null,o=e.resumeConversationId??null,a=[],s=false,l=false,u=false,c=null,d=null,p=o?r.resumeConversation(o).then(w=>w.ok?M(o):w):r.primeConversation(n?{petRef:n}:void 0),f=r.getPrompts(n!==null?{petRef:n}:void 0),[m,y]=await Promise.all([p,f]),R=null;if(m.ok)R=m.value,a.push(m.value),r.getSnapshot().conversationId===null&&r.adoptConversation(m.value);else {let w=m.error;d=w,Ts(w)?(l=true,c=w):(ks(w)&&(s=true),u=true);}let b=[];y.ok?b=y.value:T(y.error);function T(w){Ts(w)?(l=true,c===null&&(c=w)):ks(w)&&(s=true);}i(T,"recordAuthSignals");let x=c!==null?c.displayMessage:null;return Object.freeze({conversationId:R,petRef:n,suggestedPrompts:b,error:x,warning:x===null&&R===null&&u?Um:null,cause:c??d,diagnostics:Object.freeze({candidateConversationIds:Object.freeze([...a]),sawForbidden:s,sawUnauthorized:l,sawConversationInitFailure:u})})}i(Ps,"bootstrapChat");var Um="Chat is ready. Your first message will start the conversation.";function Ts(e){return e.httpStatus===401||e.code==="authExpired"||e.code==="authRejected"}i(Ts,"isUnauthorized");function ks(e){return e.httpStatus===403||e.code==="accessDenied"}i(ks,"isForbidden");var bo=Object.freeze({postMultipart(){return Promise.reject(new Error("UploadTransport is unavailable; no records upload adapter was injected"))}});function _s(e){return e!==bo}i(_s,"isUploadTransportAvailable");var zm=Object.freeze(["image/jpeg","image/jpg","image/png","image/heic","image/heif","image/webp"]),Is="image/jpeg,image/png,image/webp,image/heic,image/heif,.jpg,.jpeg,.png,.webp,.heic,.heif",Br=10*1024*1024,jr=5,er=120,Bm="/widget/v1/uploads/initiate";function jm(e){return typeof e=="string"&&zm.includes(e.trim().toLowerCase())}i(jm,"isAttachmentMime");function Vm(e){if(!e)return "attachment";let t=e.replace(/[\\/]+/g," ").replace(/[\x00-\x1f\x7f"]/g,"").replace(/\s+/g," ").trim();if(!t)return "attachment";if(t.length<=er)return t;let r=t.lastIndexOf(".");if(r===-1||r===t.length-1)return t.slice(0,er);let n=t.slice(r);return n.length>=er?t.slice(0,er):`${t.slice(0,r).slice(0,er-n.length)}${n}`}i(Vm,"sanitizeFilename");function vo(e){return e<1024?`${e} B`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}i(vo,"formatBytes");var tr=i(e=>Object.freeze({ok:true,value:e}),"ok"),ke=i(e=>Object.freeze({ok:false,error:e}),"err");function ie(e,t,r,n){return Object.freeze({code:e,retryable:t,filename:r,...n??{}})}i(ie,"failure");function $m(e){if(typeof e.sizeBytes=="number"&&Number.isFinite(e.sizeBytes)&&e.sizeBytes>=0)return e.sizeBytes;let t=e.blob;return t!==void 0&&typeof t.size=="number"&&Number.isFinite(t.size)?t.size:null}i($m,"attachmentSize");function Wm(e){let t=Vm(e.name),r=typeof e.mimeType=="string"?e.mimeType.trim().toLowerCase():"";if(!jm(r))return ke(ie("unsupported_type",false,t));let n=$m(e);return n===null?ke(ie("unknown",false,t)):n>Br?ke(ie("too_large",false,t,{sizeBytes:n})):tr(Object.freeze({file:e,filename:t,contentType:r,sizeBytes:n}))}i(Wm,"validateAttachment");function Km(e){if(typeof e!="object"||e===null)return null;let t=e,r=i(c=>typeof c=="string"&&c.length>0?c:null,"str"),n=i(c=>typeof c=="number"&&Number.isFinite(c)?c:null,"num"),o=r(t.upload_id),a=r(t.upload_url),s=r(t.s3_key);if(o===null||a===null||s===null)return null;let l={},u=t.upload_fields;if(typeof u=="object"&&u!==null)for(let[c,d]of Object.entries(u))typeof d=="string"&&(l[c]=d);return Object.freeze({upload_id:o,upload_url:a,upload_fields:Object.freeze(l),expires_in_seconds:n(t.expires_in_seconds)??0,max_content_length:n(t.max_content_length)??Br,s3_key:s,purpose:r(t.purpose)})}i(Km,"parsePolicy");function Gm(e,t){let r=e.httpStatus;switch(e.code){case "quotaExceeded":return ie("quota_exceeded",false,t,{cause:e});case "rateLimited":return ie("rate_limited",true,t,{cause:e});case "idempotencyConflict":case "idempotencyInFlight":return ie("idempotency_conflict",true,t,{cause:e});case "validationFailed":return ie("unsupported_type",false,t,{cause:e});case "serviceUnavailable":case "streamTimeout":return ie("network",true,t,{cause:e});default:return r===429?ie("rate_limited",true,t,{cause:e}):r===503?ie("network",true,t,{cause:e}):r===void 0?ie("network",true,t,{cause:e}):ie("server",e.retryable,t,{httpStatus:r,cause:e})}}i(Gm,"initiateFailure");async function qm(e,t,r){let n=await e.send("chat.attachments.initiate",{method:"POST",path:Bm,body:{filename:t.filename,content_type:t.contentType,file_size:t.sizeBytes},...r?.signal?{signal:r.signal}:{}});if(!n.ok)return ke(Gm(n.error,t.filename));let o=Km(n.value);return o===null?ke(ie("server",false,t.filename)):tr(o)}i(qm,"initiateAttachmentUpload");async function Ym(e,t,r,n){let o=i(()=>n?.signal?.aborted===true,"cancelled");if(o())return ke(ie("cancelled",true,r.filename));try{return await e.postMultipart(t,r.file,{...n?.signal?{signal:n.signal}:{},...n?.onProgress?{onProgress:n.onProgress}:{}}),tr(void 0)}catch{return o()?ke(ie("cancelled",true,r.filename)):ke(ie("server",true,r.filename))}}i(Ym,"uploadAttachmentBytes");var Xm=2,Qm=3,Zm=Object.freeze([1e3,2e3,4e3]),ws=0;function Jm(){return ws+=1,`attachment-${ws}`}i(Jm,"defaultNewId");function As(e){let t=Math.max(1,e.concurrency??Xm),r=Math.max(1,e.maxAttempts??Qm),n=e.backoffMs??Zm,o=Math.max(1,e.maxPerMessage??jr),a=e.timers??ns,s=e.newId??Jm,l=_s(e.transport),u=new Map,c=[],d=[],p=new Set,f=new Set,m=Object.freeze({attachments:Object.freeze([])}),y=false,R=i(()=>{m=Object.freeze({attachments:Object.freeze(c.flatMap(g=>{let S=u.get(g);return S===void 0?[]:[S.state]}))});for(let g of f)g();},"publish"),b=i((g,S)=>{g.state=Object.freeze({...g.state,...S}),R();},"patch"),T=i(()=>{for(;!y&&p.size<t&&d.length>0;){let g=d.shift(),S=u.get(g);S!==void 0&&(p.add(g),x(S).finally(()=>{p.delete(g),T();}));}},"pump"),x=i(async g=>{let{attachment:S}=g;for(;g.attempts<r;){if(y||g.controller.signal.aborted)return;g.attempts+=1;let I=g.controller.signal;b(g,{status:"uploading",error:null,progress:0});let O=await qm(e.funnel,S,{signal:I});if(y||I.aborted)return;let k;if(!O.ok)k=ke(O.error);else {let F=await Ym(e.transport,O.value,S,{signal:I,onProgress:i(B=>{!I.aborted&&g.state.status==="uploading"&&b(g,{progress:ey(B)});},"onProgress")});if(y||I.aborted)return;k=F.ok?tr(O.value.s3_key):ke(F.error);}if(k.ok){b(g,{status:"uploaded",s3Key:k.value,error:null,progress:1});return}let v=k.error,C=v.retryable&&g.attempts<r;if(b(g,{status:C?"uploading":"failed",error:v,progress:0}),!C)return;let A=n[Math.min(g.attempts-1,n.length-1)]??0;await Hr(A,I,a);}},"run"),_=i(g=>{d.push(g.state.id),T();},"enqueue"),w={available:l,subscribe(g){return f.add(g),()=>{f.delete(g);}},getSnapshot:i(()=>m,"getSnapshot"),get uploading(){return m.attachments.some(g=>g.status==="uploading")},get s3Keys(){return m.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[])},add(g){let S=Wm(g);if(!S.ok)return S;if(y||c.length>=o)return ke(ie("too_many",false,S.value.filename));let I=s(),O={attachment:S.value,controller:new AbortController,attempts:0,state:Object.freeze({id:I,filename:S.value.filename,previewUri:g.uri,contentType:S.value.contentType,sizeBytes:S.value.sizeBytes,status:"uploading",s3Key:null,error:null,progress:0})};return u.set(I,O),c.push(I),R(),_(O),tr(O.state)},retry(g){let S=u.get(g);S===void 0||y||S.state.status!=="failed"||(S.controller=new AbortController,S.attempts=0,b(S,{status:"uploading",error:null,progress:0,s3Key:null}),_(S));},remove(g){let S=u.get(g);if(S===void 0)return;S.controller.abort(),u.delete(g);let I=c.indexOf(g);I>=0&&c.splice(I,1);let O=d.indexOf(g);O>=0&&d.splice(O,1),R();},clear(){for(let g of [...c])w.remove(g);},dispose(){y=true;for(let g of u.values())g.controller.abort();u.clear(),c.length=0,d.length=0,f.clear(),m=Object.freeze({attachments:Object.freeze([])});}};return w}i(As,"createAttachmentQueue");function ey(e){return Number.isNaN(e)||e<0?0:e>1?1:e}i(ey,"clamp");var Os=Object.freeze({dog:"dog",canine:"dog",k9:"dog",puppy:"dog",cat:"cat",feline:"cat",kitten:"cat"});function rr(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return Object.prototype.hasOwnProperty.call(Os,t)?Os[t]:null}i(rr,"canonicalPetSpecies");var Fs=50,ty=128,Eo=120,Ms=120,ry=2e3,Ds=120,ny=80,Hs=new Set(["male","female","unknown"]),Us=new Set(["day","month","year"]),zs=new Set(["low","medium","high","athletic"]),Bs=new Set(["indoor","outdoor","both"]),js=new Set(["mild","moderate","severe"]),oy=/^(\d{4})-(\d{2})-(\d{2})$/,Vs=[["sex","sex"],["spayedNeutered","spayed_neutered"],["birthDate","birth_date"],["birthDatePrecision","birth_date_precision"],["activityLevel","activity_level"],["indoorOutdoor","indoor_outdoor"],["foodBrand","food_brand"],["foodType","food_type"],["microchipId","microchip_id"]],$s=[["allergies","allergies"],["medications","medications"],["supplements","supplements"],["conditions","conditions"]];Object.freeze([...Vs,...$s].map(([e])=>e));function iy(e){let t=oy.exec(e);if(t===null)return false;let[r,n,o]=[Number(t[1]),Number(t[2]),Number(t[3])],a=new Date(Date.UTC(r,n-1,o));return a.getUTCFullYear()===r&&a.getUTCMonth()===n-1&&a.getUTCDate()===o}i(iy,"isRealDate");var or=i(e=>(t,r)=>typeof r=="string"&&e.has(r)?null:`${t} must be one of ${[...e].join(", ")}`,"oneOf"),ay=i((e,t)=>typeof t=="boolean"?null:`${e} must be true or false`,"boolean"),$r=i((e,t)=>typeof t=="string"&&iy(t)?null:`${e} must be a real date written YYYY-MM-DD`,"date"),Oe=i((e,t={})=>(r,n)=>{if(typeof n!="string")return `${r} must be a string`;if(Ee(n))return `${r} contains an unpaired surrogate and cannot be encoded`;let o=t.trimmed?n.trim():n;if(t.required&&o.length===0)return `${r} is required and must not be blank`;let a=ct(o);return a<=e?null:`${r} is ${a} characters; the server accepts at most ${e}`},"text"),sy={sex:or(Hs),spayedNeutered:ay,birthDate:$r,birthDatePrecision:or(Us),activityLevel:or(zs),indoorOutdoor:or(Bs),foodBrand:Oe(Ds),foodType:Oe(Ds),microchipId:Oe(ny)},Co=["ref","ref",false,Oe(ty,{required:true,trimmed:true})],Ro=["notes","notes",false,Oe(ry,{trimmed:true})],Ls=[Co,["name","name",true,Oe(Eo,{required:true,trimmed:true})],["dose","dose",false,Oe(Ms,{trimmed:true})],["frequency","frequency",false,Oe(Ms,{trimmed:true})],["startDate","start_date",false,$r],["endDate","end_date",false,$r],Ro],ly={allergies:[Co,["allergen","allergen",true,Oe(Eo,{required:true,trimmed:true})],["severity","severity",false,or(js)],Ro],medications:Ls,supplements:Ls,conditions:[Co,["conditionName","condition_name",true,Oe(Eo,{required:true,trimmed:true})],["diagnosedDate","diagnosed_date",false,$r],Ro]};function uy(e,t,r){let n=`${e}[${t}]`;if(typeof r!="object"||r===null||Array.isArray(r))return {error:`${n} must be an object`};let o=r,a={};for(let[u,c,d,p]of ly[e]){let f=o[u];if(f==null){if(d)return {error:`${n}.${u} is required`};f===null&&(a[c]=null);continue}let m=p(`${n}.${u}`,f);if(m!==null)return {error:m};a[c]=f;}let s=a.start_date,l=a.end_date;return typeof s=="string"&&typeof l=="string"&&l<s?{error:`${n}.endDate must not be before startDate`}:{item:a}}i(uy,"itemToWire");function dy(e,t){if(!Array.isArray(t))return {error:`${e} must be an array (send [] to clear it)`};if(t.length>Fs)return {error:`${e} has ${t.length} items; the server accepts at most ${Fs}`};let r=[],n=new Set;for(let o=0;o<t.length;o+=1){let a=uy(e,o,t[o]);if("error"in a)return a;let s=a.item.ref;if(typeof s=="string"){let l=s.trim();if(n.has(l))return {error:`${e}: ref ${JSON.stringify(l)} is used twice; a ref names one item`};n.add(l);}r.push(a.item);}return {items:r}}i(dy,"listToWire");function Ws(e,t){let r=e,n={};for(let[s,l]of Vs){let u=r[s];if(u!==void 0){if(u!==null){let c=sy[s](s,u);if(c!==null)return {error:c}}n[l]=u;}}let o=r.birthDate!==void 0,a=r.birthDatePrecision!==void 0;if(o!==a||o&&r.birthDate===null!=(r.birthDatePrecision===null))return {error:"birthDate and birthDatePrecision must be sent together, both set or both null"};for(let[s,l]of $s){let u=r[s];if(u===void 0)continue;let c=dy(s,u);if("error"in c)return c;n[l]=c.items;}return Object.keys(n).length>0&&t!==void 0&&rr(t)===null?{error:"health fields need a pet Everfur reads as a dog or a cat (dog, canine, k9, puppy, cat, feline, kitten)"}:{body:n}}i(Ws,"petHealthToWire");var te=i(e=>typeof e=="string"?e:null,"str"),nr=i((e,t)=>typeof t=="string"&&e.has(t)?t:null,"pick"),cy=i(e=>typeof e=="boolean"?e:null,"bool");function Vr(e,t){return Array.isArray(e)?Object.freeze(e.flatMap(r=>{if(typeof r!="object"||r===null||Array.isArray(r))return [];let n=t(r);return n===null?[]:[n]})):Object.freeze([])}i(Vr,"itemsFromWire");function Ns(e){let t=te(e.name);return t===null||t.length===0?null:Object.freeze({ref:te(e.ref),name:t,dose:te(e.dose),frequency:te(e.frequency),startDate:te(e.start_date),endDate:te(e.end_date),notes:te(e.notes)})}i(Ns,"medicationFromWire");function Ks(e){let t=e.profile_version;return Object.freeze({profileVersion:typeof t=="number"&&Number.isInteger(t)&&t>=0?t:0,sex:nr(Hs,e.sex),spayedNeutered:cy(e.spayed_neutered),birthDate:te(e.birth_date),birthDatePrecision:nr(Us,e.birth_date_precision),activityLevel:nr(zs,e.activity_level),indoorOutdoor:nr(Bs,e.indoor_outdoor),foodBrand:te(e.food_brand),foodType:te(e.food_type),microchipId:te(e.microchip_id),allergies:Vr(e.allergies,r=>{let n=te(r.allergen);return n===null||n.length===0?null:Object.freeze({ref:te(r.ref),allergen:n,severity:nr(js,r.severity),notes:te(r.notes)})}),medications:Vr(e.medications,Ns),supplements:Vr(e.supplements,Ns),conditions:Vr(e.conditions,r=>{let n=te(r.condition_name);return n===null||n.length===0?null:Object.freeze({ref:te(r.ref),conditionName:n,diagnosedDate:te(r.diagnosed_date),notes:te(r.notes)})})})}i(Ks,"petHealthFromWire");var Ys=100,Xs=50,Qs=100,Zs=50,Js=500,py=128,fy=6e4;function Me(e){return D("validationFailed",{retryable:false,wireMessage:e})}i(Me,"invalid");function ft(e,t,r){if(typeof t!="string")return Me(`${e} must be a string`);let n=ct(t);return n<=r?null:Me(`${e} is ${n} characters; the server accepts at most ${r}`)}i(ft,"checkString");function Wr(e,t,r){return typeof t=="number"&&Number.isFinite(t)&&t>=0&&t<=r?null:Me(`${e} must be a finite number between 0 and ${r}`)}i(Wr,"outOfRange");function Gs(e,t){if(typeof e!="string")return Me("pet_ref must be a string");if(e.trim().length===0)return Me("pet_ref must not be blank");if(Ee(e))return Me("pet_ref contains an unpaired surrogate and cannot be encoded");if(t!=null&&typeof t!="object")return Me("profile must be an object");let r=[ft("pet_ref",e,py)];return t?.name!==void 0&&r.push(ft("name",t.name,Ys)),t?.species!==void 0&&r.push(ft("species",t.species,Xs)),t?.breed!==void 0&&r.push(ft("breed",t.breed,Qs)),t?.ageYears!==void 0&&r.push(Wr("age_years",t.ageYears,Zs)),t?.weightKg!==void 0&&r.push(Wr("weight_kg",t.weightKg,Js)),r.find(n=>n!==null)??null}i(Gs,"validate");function el(e,t){let r=Ws(e,t);return "error"in r?{error:Me(r.error)}:r}i(el,"healthToWire");function my(e){if(typeof e!="object"||e===null)return {error:Me("patch must be an object")};let t=e,r=[["name","name",a=>ft("name",a,Ys)],["species","species",a=>ft("species",a,Xs)],["breed","breed",a=>ft("breed",a,Qs)],["ageYears","age_years",a=>Wr("age_years",a,Zs)],["weightKg","weight_kg",a=>Wr("weight_kg",a,Js)]],n={};for(let[a,s,l]of r){let u=t[a];if(u!==void 0){if(u!==null){let c=l(u);if(c!==null)return {error:c}}n[s]=u;}}let o=el(t,t.species);return "error"in o?o:(Object.assign(n,o.body),Object.keys(n).length===0?{error:Me("patch must change at least one field")}:{body:n})}i(my,"patchToWire");function yy(e){if(e==null)return {body:{}};let t=el(e,e.species);return "error"in t?t:{body:{...e.name!==void 0?{name:e.name}:{},...e.species!==void 0?{species:e.species}:{},...e.breed!==void 0?{breed:e.breed}:{},...e.ageYears!==void 0?{age_years:e.ageYears}:{},...e.weightKg!==void 0?{weight_kg:e.weightKg}:{},...t.body}}}i(yy,"toWire");var Fe=i(e=>typeof e=="string"?e:null,"str"),Kr=i(e=>typeof e=="number"&&Number.isFinite(e)?e:null,"num");function qs(e,t){let r=typeof e=="object"&&e!==null?e:{};return Object.freeze({petRef:Fe(r.pet_ref)??t,name:Fe(r.name),species:Fe(r.species),breed:Fe(r.breed),ageYears:Kr(r.age_years),weightKg:Kr(r.weight_kg)})}i(qs,"fromWire");function tl(e){if(typeof e!="object"||e===null)return null;let t=e,r=Fe(t.pet_ref);return r===null||r.length===0?null:Object.freeze({petId:Fe(t.pet_id),petRef:r,name:Fe(t.name),species:Fe(t.species),breed:Fe(t.breed),ageYears:Kr(t.age_years),weightKg:Kr(t.weight_kg),updatedAt:Fe(t.updated_at)})}i(tl,"widgetPetFromWire");function gy(e){let t=tl(e);return t===null?null:Object.freeze({...t,...Ks(e)})}i(gy,"widgetPetProfileFromWire");function hy(e){let t=Array.isArray(e)?e:typeof e=="object"&&e!==null&&Array.isArray(e.pets)?e.pets:[];return Object.freeze(t.flatMap(r=>{let n=tl(r);return n===null?[]:[n]}))}i(hy,"petListFromWire");function et(e){return by(Te({auth:e}),Te({auth:e,unaryTimeoutMs:fy}))}i(et,"createPetsRepository");function by(e,t=e){let r=i((o,a)=>a?{...o,signal:a}:o,"withSignal"),n=i(o=>Gs(o,void 0)??`/widget/v1/pets/${encodeURIComponent(o)}`,"petPath");return {async list(o){let a=await e.send("pets.list",r({method:"GET",path:"/widget/v1/pets"},o?.signal));return a.ok?M(hy(a.value)):E(a.error)},async registerPet(o,a,s){let l=Gs(o,a);if(l!==null)return E(l);let u=yy(a);if("error"in u)return E(u.error);let d={method:"POST",path:`/widget/v1/pets/${encodeURIComponent(o)}`,body:u.body},p=await e.send("pets.registerPet",s?.signal?{...d,signal:s.signal}:d);return p.ok?M(qs(p.value,o)):E(p.error)},async updatePet(o,a,s){let l=n(o);if(typeof l!="string")return E(l);let u=my(a);if("error"in u)return E(u.error);let c=await e.send("pets.updatePet",r({method:"PATCH",path:l,body:u.body},s?.signal));return c.ok?M(qs(c.value,o)):E(c.error)},async getPetProfile(o,a){let s=n(o);if(typeof s!="string")return E(s);let l=await e.send("pets.getPetProfile",r({method:"GET",path:`${s}/profile`},a?.signal));if(!l.ok)return E(l.error);let u=gy(l.value);return u===null?E(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the pet profile response carried no pet_ref"})):M(u)},async deletePet(o,a){let s=n(o);if(typeof s!="string")return E(s);let l=await e.send("pets.deletePet",r({method:"DELETE",path:s},a?.signal));return l.ok?M(void 0):E(l.error)},async eraseUserData(o){let a=await t.send("pets.eraseUserData",r({method:"DELETE",path:"/widget/v1/me"},o?.signal),{maxAttempts:1});return a.ok?M(void 0):E(a.error)}}}i(by,"createPetsRepositoryOver");var xo=Object.freeze({chat:Object.freeze(["chat.message.create"]),records:Object.freeze(["records.upload.create","records.record.read"]),recordsClinic:Object.freeze(["records.clinic.create"]),video:Object.freeze(["video.gait.execute"]),photo:Object.freeze(["photo.checkup.execute"]),animations:Object.freeze(["animations.state.read"]),televet:Object.freeze(["televet.visit.create"])});function vy(e){return xo[e]}i(vy,"requires");function rl(e,t){let r=Object.freeze({reason:t,level:e,recoverable:false}),n=[],o=new Set;for(let a of Object.keys(xo))for(let s of xo[a])o.has(s)||(o.add(s),n.push(Object.freeze({resource:s,granted:false,disabled:r})));return Object.freeze(n)}i(rl,"deniedDecisionsFor");function nl(e,t,r){let n=vy(e),o=new Map;for(let l of t)o.set(l.resource,l);if(r?.isPending===true&&n.some(l=>!o.has(l)))return So({name:e,enabled:false,isPending:true,limits:{}});let a=Ey(n,o);return n.filter(l=>o.get(l)?.granted!==true).length===0?So({name:e,enabled:true,isPending:false,limits:a}):So({name:e,enabled:false,isPending:false,limits:a,disabled:Cy(n,o)})}i(nl,"decideCapability");function Ey(e,t){let r={};for(let n of e){let o=t.get(n)?.limits;if(o)for(let[a,s]of Object.entries(o)){let l=r[a];r[a]=l===void 0?s:Math.min(l,s);}}return r}i(Ey,"mergeLimits");function Cy(e,t){for(let r of e){let n=t.get(r)?.disabled;if(n)return Object.freeze({reason:n.reason,level:n.level,recoverable:n.recoverable})}return Object.freeze({reason:At("accessDenied"),level:"user_entitlement",recoverable:false})}i(Cy,"disabledFor");function So(e){let t={name:e.name,enabled:e.enabled,isPending:e.isPending,limits:Object.freeze({...e.limits})};return e.disabled!==void 0&&(t.disabled=e.disabled),Object.freeze(t)}i(So,"freezeDecision");function ye(e){let t=ae(e);return t===null?null:Sy(t)}i(ye,"parseColor");function ae(e){if(typeof e=="number")return ol(e);if(typeof e!="string")return null;let t=e.trim();if(t.length===0)return null;if(t.startsWith("#"))return To(t.slice(1));if(t.toLowerCase().startsWith("0x"))return To(t.slice(2));if(t.toLowerCase().startsWith("rgb"))return Ry(t);if(/^[0-9a-fA-F]+$/.test(t)){let r=To(t);if(r!==null)return r}return /^\d+$/.test(t)?ol(Number.parseInt(t,10)):null}i(ae,"toRgba");function To(e){let t=e.trim();if(!/^[0-9a-fA-F]+$/.test(t))return null;if(t.length===3)return {r:ko(t[0]),g:ko(t[1]),b:ko(t[2]),a:1};if(t.length===6)return {r:mt(t,0),g:mt(t,2),b:mt(t,4),a:1};if(t.length===8){let r=mt(t,0);return {r:mt(t,2),g:mt(t,4),b:mt(t,6),a:r/255}}return null}i(To,"fromHex");function Ry(e){let t=e.indexOf("("),r=e.indexOf(")");if(t<0||r<0||r<t)return null;let n=e.slice(t+1,r).split(",").map(u=>u.trim());if(n.length<3)return null;let o=Po(Number(n[0])),a=Po(Number(n[1])),s=Po(Number(n[2]));if(o===null||a===null||s===null)return null;let l=1;if(n.length>=4){let u=Number(n[3]);if(!Number.isFinite(u))return null;l=Math.min(1,Math.max(0,u));}return {r:o,g:a,b:s,a:l}}i(Ry,"fromRgbFunc");function ol(e){if(!Number.isFinite(e))return null;let t=Math.trunc(e)>>>0,r=t>>>24&255;return {r:t>>>16&255,g:t>>>8&255,b:t&255,a:r===0?1:r/255}}i(ol,"argbIntToRgba");function mt(e,t){return Number.parseInt(e.slice(t,t+2),16)}i(mt,"byte");function ko(e){return Number.parseInt(`${e??"0"}${e??"0"}`,16)}i(ko,"dup");function Po(e){return Number.isFinite(e)?Math.min(255,Math.max(0,Math.round(e))):null}i(Po,"clampByte");function Sy(e){if(e.a>=1)return gt(e.r,e.g,e.b);let t=Math.round(e.a*1e3)/1e3;return `rgba(${e.r},${e.g},${e.b},${t})`}i(Sy,"normalizeRgba");function gt(e,t,r){return `#${_o(e)}${_o(t)}${_o(r)}`.toUpperCase()}i(gt,"rgbToHex");function _o(e){return e.toString(16).padStart(2,"0")}i(_o,"hex2");var xy="#111111",Ot="#FFFFFF",Gr="#000000";function al(e){let t=ae(e);if(t===null)return Ot;let r=yt(t),n=yt({r:17,g:17,b:17}),o=yt({r:255,g:255,b:255});return Ao(r,o)>=Ao(r,n)?Ot:xy}i(al,"readableOn");function ir(e,t){let r=al(e);return ue(r,e)>=t?r:ue(Ot,e)>=ue(Gr,e)?Ot:Gr}i(ir,"legibleOn");function ar(e){let t=i(r=>e.reduce((n,o)=>Math.min(n,ue(r,o)),Number.POSITIVE_INFINITY),"worst");return t(Ot)>=t(Gr)?Ot:Gr}i(ar,"poleForGrounds");function yt(e){let t=wo(e.r/255),r=wo(e.g/255),n=wo(e.b/255);return .2126*t+.7152*r+.0722*n}i(yt,"relativeLuminance");function wo(e){return e<=.03928?e/12.92:Math.pow((e+.055)/1.055,2.4)}i(wo,"linearize");function Ao(e,t){let r=Math.max(e,t),n=Math.min(e,t);return (r+.05)/(n+.05)}i(Ao,"luminanceContrast");function ue(e,t){let r=ae(e),n=ae(t);if(r===null||n===null)return 1;let o=n.a>=1?n:{...n},a=r.a>=1?r:sl(r,o);return Ao(yt(a),yt(o))}i(ue,"contrastRatio");function sl(e,t){let r=e.a,n=i((o,a)=>Math.round(o*r+a*(1-r)),"mix");return {r:n(e.r,t.r),g:n(e.g,t.g),b:n(e.b,t.b),a:1}}i(sl,"composite");function ht(e,t){let r=ae(e),n=ae(t);if(r===null||n===null)return null;let o=r.a>=1?r:sl(r,{...n});return gt(o.r,o.g,o.b)}i(ht,"flattenOnto");function $e(e,t){let r=ae(e);if(r===null)return null;let n=Math.min(1,Math.max(0,t));return `rgba(${r.r}, ${r.g}, ${r.b}, ${n})`}i($e,"withAlpha");var il=.05;function tt(e,t,r,n){let o=t[0];if(o===void 0)return r;let a=i(c=>t.every(d=>ue(c,d)>=n),"reads");if(ae(e)===null)return r;if(a(e))return e;let s=ht(e,o),l=s===null?null:ae(s),u=ae(r);if(l===null||u===null)return r;for(let c=1;c<1/il;c+=1){let d=c*il,p=i((m,y)=>Math.round(m+(y-m)*d),"mix"),f=gt(p(l.r,u.r),p(l.g,u.g),p(l.b,u.b));if(a(f))return f}return r}i(tt,"pushToContrast");function ll(e,t,r){let n=e/255,o=t/255,a=r/255,s=Math.max(n,o,a),l=Math.min(n,o,a),u=(s+l)/2;if(s===l)return {h:0,s:0,l:u};let c=s-l,d=c/(1-Math.abs(2*u-1)),p;return s===n?(p=(o-a)/c*60,p<0&&(p=p+360)):s===o?p=((a-n)/c+2)*60:p=((n-o)/c+4)*60,{h:p,s:d,l:u}}i(ll,"rgbToHsl");function Oo(e){let{h:t,s:r,l:n}=e,o=(1-Math.abs(2*n-1))*r,a=t/60,s=o*(1-Math.abs(a%2-1)),l=n-o/2,u=Math.floor(a)%6,c=[[o,s,0],[s,o,0],[0,o,s],[0,s,o],[s,0,o],[o,0,s]],[d,p,f]=c[u];return {r:Io(d+l),g:Io(p+l),b:Io(f+l)}}i(Oo,"hslToRgb");function Io(e){return Math.min(255,Math.max(0,Math.floor(e*255+.5)))}i(Io,"channel");function We(e){if(e!==null&&typeof e=="object"&&!Object.isFrozen(e)){Object.freeze(e);for(let t of Object.keys(e))We(e[t]);}return e}i(We,"deepFreeze");var qr=Object.freeze({content:0,heading:2,control:1.8,compact:1.5,badge:1.3}),dl={xs:4,sm:8,md:12,lg:16,xl:24,xxl:32},cl={tile:5,xs:6,sm:10,md:14,lg:20,xl:28,pill:500},ul={nano:8,small:9,micro:10,tiny:11,caption:12,bodyTight:13,body:14,subtitle:16,heading:18,verdict:24},Ty={tight:1.15,snug:1.3,normal:1.4,relaxed:1.55},ky={regular:"400",medium:"500",bold:"700"},Py={eyebrow:1,monoWide:.9,headerBrand:-0.42,tight:-0.35},Fo=0,bt="System",rt="monospace",_y=["content","heading","control","compact","badge"];function wy(e){let t={};for(let r of _y)t[r]=e;return t}i(wy,"authoredTierSizes");function pl(){return {family:bt,mono:rt,fontUrl:null,families:{regular:bt,medium:bt,bold:bt,mono:rt,monoMedium:rt,monoBold:rt},namedFaces:{regular:false,medium:false,bold:false,mono:false,monoMedium:false,monoBold:false},fontUrls:{},size:ul,tierSizes:wy(ul),lineHeight:Ty,weight:ky,letterSpacing:Py,scale:1,maxScale:Fo,scaleCaps:qr}}i(pl,"baseType");var fl={},vt=Object.freeze({standard:Object.freeze([.2,0,0,1]),emphasized:Object.freeze([.2,.8,.2,1]),exit:Object.freeze([.4,0,1,1])});function sr(e){return `cubic-bezier(${e.join(", ")})`}i(sr,"cssCubicBezier");var ml={duration:{instant:80,fast:140,normal:220,slow:320},spring:{gentle:{damping:18,stiffness:200}},easing:{standard:sr(vt.standard),emphasized:sr(vt.emphasized),exit:sr(vt.exit)},reducedMotion:false},Iy={brand:"#10462E",brandSoft:"rgba(16,70,46,0.10)",brandSofter:"rgba(16,70,46,0.15)",brandBorder:"rgba(16,70,46,0.18)",borderHairlineGreen:"rgba(16,70,46,0.25)",brandBorderStrong:"rgba(16,70,46,0.55)",brandInk:"#10462E",linkInk:"#10462E",surface:"#FFFFFF",surfaceCream:"#FDFBF8",surfaceSubtle:"#EFE9E3",background:"#FFFFFF",borderRingCream:"#D8D2C8",chatGround:"#FFFFFF",composerFill:"#FDFBF8",composerBorder:"rgba(16,70,46,0.75)",shadow:"#0B3421",text:{primary:"#111111",secondary:"#0E462E",muted:"#6E6660",placeholder:"rgba(61,61,61,0.75)",onBrand:"#FFFFFF",metaCool:"#3D3D3D",timestamp:"rgba(61,61,61,0.75)"},primary:"#10462E",onPrimary:"#FFFFFF",accent:"#10462E",onAccent:"#FFFFFF",accentEdge:"#07C168",success:"#07C168",danger:"#B91C1C",errorRed:"#FF1B00",warningStrong:"#A45610",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.12)",badgeBgCaution:"rgba(217,130,29,0.14)",badgeBgCritical:"rgba(185,28,28,0.12)",badgeBgNeutral:"rgba(110,102,96,0.12)",bubbleUser:"#10462E",bubbleAssistant:"#FFFFFF",skeleton:"#EFE9E3",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.10)",checkupCardConcernBg:"rgba(239,167,0,0.10)"},Et=We({brightness:"light",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Iy,space:dl,radius:cl,type:pl(),motion:ml,slots:fl}),Ay={brand:"#6BD39A",brandSoft:"rgba(107,211,154,0.12)",brandSofter:"rgba(107,211,154,0.18)",brandBorder:"rgba(107,211,154,0.22)",borderHairlineGreen:"rgba(107,211,154,0.28)",brandBorderStrong:"rgba(107,211,154,0.55)",brandInk:"#6BD39A",linkInk:"#6BD39A",surface:"#1C1F23",surfaceCream:"#23272C",surfaceSubtle:"#23272C",background:"#15171A",borderRingCream:"#3A3F45",chatGround:"#1C1F23",composerFill:"#23272C",composerBorder:"rgba(107,211,154,0.75)",shadow:"#000000",text:{primary:"#F5F3F0",secondary:"#A9E4C4",muted:"#9A938C",placeholder:"rgba(255,255,255,0.55)",onBrand:"#0E1F17",metaCool:"#C9C9C9",timestamp:"rgba(245,243,240,0.7)"},primary:"#6BD39A",onPrimary:"#0E1F17",accent:"#6BD39A",onAccent:"#0E1F17",accentEdge:"#34D888",success:"#07C168",danger:"#F87171",errorRed:"#FF6B5B",warningStrong:"#F0A35E",cautionAccent:"#D9821D",riskConcern:"#EFA700",sentiment:{up:"#07C168",neutral:"#FBC558",down:"#FF1B00"},badgeBgPositive:"rgba(7,193,104,0.18)",badgeBgCaution:"rgba(217,130,29,0.20)",badgeBgCritical:"rgba(185,28,28,0.22)",badgeBgNeutral:"rgba(255,255,255,0.10)",bubbleUser:"#6BD39A",bubbleAssistant:"#1C1F23",skeleton:"#23272C",scanButtonPink:"#FFC3BC",checkupCardLowRiskBg:"rgba(7,193,104,0.16)",checkupCardConcernBg:"rgba(239,167,0,0.16)"},Yr=We({brightness:"dark",highContrast:false,meta:{displayName:"Everfur",logoUrl:null,placeholder:null,hidePoweredBy:false},color:Ay,space:dl,radius:cl,type:pl(),motion:ml,slots:fl});var Oy="#23272C",yl=4.5,Fy=.6,Mo=.9,My=.02,Dy="#FFFFFF",Ly="#111111";function Ny(e){return ue(e,Oy)>=yl&&Math.max(ue(e,Dy),ue(e,Ly))>=yl}i(Ny,"readsOnDark");function bl(e){let t=ae(e);if(t===null)return null;let{h:r,s:n,l:o}=ll(t.r,t.g,t.b),a=Math.min(Math.max(o,Fy),Mo);for(let l=0;;l+=1){let u=a+l*My;if(u>Mo)break;let c=Oo({h:r,s:n,l:u}),d=gt(c.r,c.g,c.b);if(Ny(d))return d}let s=Oo({h:r,s:n,l:Mo});return gt(s.r,s.g,s.b)}i(bl,"deriveDarkVariant");var Hy=7,gl=.05,Uy="#000000",zy="#FFFFFF";function By(e,t,r,n){let o=ht(e,t);if(o===null)return r;if(ue(o,t)>=n)return o;let a=ae(o),s=ae(r);if(a===null||s===null)return r;for(let l=1;l<1/gl;l+=1){let u=l*gl,c=i((p,f)=>Math.round(p+(f-p)*u),"mix"),d=gt(c(a.r,s.r),c(a.g,s.g),c(a.b,s.b));if(ue(d,t)>=n)return d}return r}i(By,"pushContrast");function jy(e,t){let r=[e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill],n=r[0],o=hl(n);for(let a of r){let s=hl(a);(t?s>o:s<o)&&(n=a,o=s);}return n}i(jy,"hardestGround");function hl(e){let t=ae(e);return t===null?0:yt(t)}i(hl,"luminanceOf");function nt(e,t){return ht(e,t)??ye(e)??t}i(nt,"solid");function vl(e){let t=e.color,r=e.brightness==="dark",n=r?zy:Uy,o=jy(t,r),a=i(l=>By(l,o,n,Hy),"text"),s={...t,brandSoft:nt(t.brandSoft,t.surface),brandSofter:nt(t.brandSofter,t.surface),brandBorder:a(t.brandBorder),borderHairlineGreen:a(t.borderHairlineGreen),brandBorderStrong:a(t.brandBorderStrong),brandInk:a(t.brandInk),linkInk:a(t.linkInk),borderRingCream:a(t.borderRingCream),composerBorder:a(t.composerBorder),text:{primary:a(t.text.primary),secondary:a(t.text.secondary),muted:a(t.text.muted),placeholder:a(t.text.placeholder),onBrand:t.text.onBrand,metaCool:a(t.text.metaCool),timestamp:a(t.text.timestamp)},badgeBgPositive:nt(t.badgeBgPositive,t.surface),badgeBgCaution:nt(t.badgeBgCaution,t.surface),badgeBgCritical:nt(t.badgeBgCritical,t.surface),badgeBgNeutral:nt(t.badgeBgNeutral,t.surface),checkupCardLowRiskBg:nt(t.checkupCardLowRiskBg,t.surface),checkupCardConcernBg:nt(t.checkupCardConcernBg,t.surface)};return We({...e,highContrast:true,color:s})}i(vl,"deriveHighContrast");var Ct=Object.freeze(["composerInput","sendButton","userBubble","assistantBubble","recordCard","vetVisitButton","primaryButton","link"]),Vy=Object.freeze(["backgroundColor","borderColor","borderRadius","textColor"]),Pe=4.5,$y=Object.freeze({});function Wy(e){return Ct.includes(e)}i(Wy,"isSlotName");function Ky(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)?Math.max(0,t):null}i(Ky,"parseRadius");function El(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t={},r=false;for(let[n,o]of Object.entries(e)){if(!Wy(n)||o===null||typeof o!="object")continue;let a=Gy(o);a!==null&&(t[n]=a,r=true);}return r?Object.freeze(t):null}i(El,"parseThemeSlots");function Xr(e,t,r){return e[t]!==void 0?e[t]:e[r]}i(Xr,"pick");function Gy(e){let t={},r=ye(Xr(e,"background_color","backgroundColor"));r!==null&&(t.backgroundColor=r);let n=ye(Xr(e,"border_color","borderColor"));n!==null&&(t.borderColor=n);let o=Ky(Xr(e,"border_radius","borderRadius"));o!==null&&(t.borderRadius=o);let a=ye(Xr(e,"text_color","textColor"));return a!==null&&(t.textColor=a),Object.keys(t).length===0?null:Object.freeze(t)}i(Gy,"parseSlot");function Cl(e,t){return t===null||Object.keys(t).length===0?e??$y:e===null||Object.keys(e).length===0?t:Object.freeze({...e,...t})}i(Cl,"mergeThemeSlots");var Do=3;function qy(e,t){return e===void 0?t:t.length===0?[e]:t.map(r=>ht(e,r)??r)}i(qy,"seatsOf");function Yy(e,t){let r=ar(e);return e.every(n=>ue(r,n)>=t)}i(Yy,"someInkReads");function Xy(e,t){let r=t[0];return r===void 0?null:ht(e,r)}i(Xy,"collapseUnsatisfiableFill");function Qy(e){let t=ir(e[0],Pe);return e.every(r=>ue(t,r)>=Pe)?t:ar(e)}i(Qy,"inkFor");function Rl(e,t){let r=false,n={};for(let o of Ct){let a=e[o];if(a===void 0)continue;let s=a.backgroundColor,l=t?.[o]??[],u=qy(s,l),c={...a},d=false;if(s!==void 0&&u.length>1&&!Yy(u,Pe)){let p=Xy(s,l);p!==null&&(c.backgroundColor=p,u=[p],d=true);}if(u.length>0){let p=a.textColor;if(s!==void 0)(p===void 0||u.some(f=>ue(p,f)<Pe))&&(c.textColor=Qy(u),d=true);else if(p!==void 0){let f=tt(p,u,ar(u),Pe);f!==p&&(c.textColor=f,d=true);}if(a.borderColor!==void 0){let f=tt(a.borderColor,u,ar(u),Do);f!==a.borderColor&&(c.borderColor=f,d=true);}}n[o]=d?Object.freeze(c):a,r=r||d;}return r?Object.freeze(n):e}i(Rl,"guardSlotContrast");var Tl=Object.freeze(["display_name","logo_url","logo_url_dark","primary_color","accent_color","primary_color_dark","accent_color_dark","brightness","color_scheme","font_family","font_url","fonts","font_urls","chat_placeholder","surface_style","radius_scale","accessibility_max_font_scale","slots"]),lr="slots.",kl=Object.freeze([1,2]);function Qr(e){return Object.keys(e).every(t=>t==="schemaVersion"||(e[t]??null)===null)}i(Qr,"isEmptyBranding");function Pl(e){let t=e?.schemaVersion??null;return t===null||kl.includes(t)}i(Pl,"isKnownBrandingSchema");function _l(e){return new Set(["hide_powered_by",...e?.lockedFields??[]])}i(_l,"lockedFieldsOf");function Zy(e){return e==="hide_powered_by"||Tl.includes(e)?true:e.startsWith(lr)&&Ct.includes(e.slice(lr.length))}i(Zy,"isThemeLockName");function Ke(e){if(e===null||typeof e!="object")return null;let t=e,r={displayName:Rt(Y(t,"display_name","displayName")),logoUrl:Rt(Y(t,"logo_url","logoUrl")),primaryColor:ye(Y(t,"primary_color","primaryColor")),accentColor:ye(Y(t,"accent_color","accentColor")),brightness:rg(Y(t,"brightness","color_scheme","colorScheme")),fontFamily:Rt(Y(t,"font_family","fontFamily")),fontUrl:Rt(Y(t,"font_url","fontUrl")),fonts:Sl(Y(t,"fonts")),fontUrls:Sl(Y(t,"font_urls","fontUrls")),placeholder:Rt(Y(t,"chat_placeholder","placeholder","chatPlaceholder")),hidePoweredBy:Jy(Y(t,"hide_powered_by","hidePoweredBy")),primaryColorDark:ye(Y(t,"primary_color_dark","primaryColorDark")),accentColorDark:ye(Y(t,"accent_color_dark","accentColorDark")),surfaceStyle:xl(Y(t,"surface_style","surfaceStyle"),eg),radiusScale:xl(Y(t,"radius_scale","radiusScale"),tg),logoUrlDark:Rt(Y(t,"logo_url_dark","logoUrlDark")),slots:El(Y(t,"slots")),accessibilityMaxFontScale:og(Y(t,"accessibility_max_font_scale","accessibilityMaxFontScale")),lockedFields:ag(Y(t,"locked_fields","lockedFields")),schemaVersion:ig(Y(t,"schema_version","schemaVersion"))};return Qr(r)?null:Object.freeze(r)}i(Ke,"parseClientBranding");function Jy(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();if(t==="true")return true;if(t==="false")return false}return null}i(Jy,"parseBool");function Y(e,...t){for(let r of t)if(Object.prototype.hasOwnProperty.call(e,r)){let n=e[r];if(n!==void 0)return n}}i(Y,"pick");function Rt(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(Rt,"parseNonEmptyString");var ur=["regular","medium","bold","mono","monoMedium","monoBold"];function Sl(e){if(e===null||typeof e!="object"||Array.isArray(e))return null;let t=e,r={};for(let n of ur){let o=Rt(Y(t,n));o!==null&&(r[n]=o);}return Object.keys(r).length===0?null:Object.freeze(r)}i(Sl,"parseFaceMap");var eg=["white","cream","subtle"],tg=["sharp","default","round"];function xl(e,t){if(typeof e!="string")return null;let r=e.trim().toLowerCase();return t.includes(r)?r:null}i(xl,"parseEnum");function rg(e){if(typeof e!="string")return null;let t=e.trim().toLowerCase();return t==="light"||t==="dark"||t==="auto"?t:null}i(rg,"parseBrightness");function wl(e){let t=typeof e=="number"?e:typeof e=="string"?Number(e.trim()):Number.NaN;return Number.isFinite(t)&&(typeof e!="string"||e.trim().length>0)?t:null}i(wl,"parseNumber");var ng=1,Il=3.1;function og(e){let t=wl(e);return t===null?null:t<=0?0:Math.min(Il,Math.max(ng,t))}i(og,"parseMaxFontScale");function ig(e){if(e==null)return null;let t=wl(e);return t!==null&&Number.isInteger(t)&&t>=1?t:0}i(ig,"parseSchemaVersion");function Lo(e){let t=e.trim();return t.startsWith(lr)?t:t.replace(/([a-z0-9])([A-Z])/g,"$1_$2").toLowerCase()}i(Lo,"toWireName");function ag(e){if(!Array.isArray(e))return null;let t=[];for(let r of e){if(typeof r!="string")continue;let n=Lo(r);Zy(n)&&!t.includes(n)&&t.push(n);}return t.length===0?null:Object.freeze(t)}i(ag,"parseLockedFields");function No(e){if(e===null)return null;let t=e.trim();return t.length===0?null:/^https:\/\/\S+$/i.test(t)?t:null}i(No,"hardenHttpsUrl");function Al(e,t){if(t===null||Qr(t))return e;let r=(t.brightness==="light"||t.brightness==="dark")&&t.brightness!==e.brightness?t.brightness==="dark"?Yr:Et:e,n=r.brightness==="dark"?Yr:Et,o=r.brightness==="dark",a=o?t.primaryColorDark??Ol(t.primaryColor):t.primaryColor,s=o?t.accentColorDark??Ol(t.accentColor):t.accentColor,l=a??r.color.primary,u=s??r.color.accent,c=a!==null&&cg(t,l,n,o),d=c?n.color.primary:l,p=a!==null&&!c?ae(d):null,f=i(R=>Math.round(R+(255-R)*.4),"lift"),m=p!==null?{brand:d,bubbleUser:d,brandInk:d,text:{...r.color.text,secondary:d},brandSoft:`rgba(${p.r}, ${p.g}, ${p.b}, 0.10)`,brandSofter:`rgba(${p.r}, ${p.g}, ${p.b}, 0.15)`,brandBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.20)`,borderHairlineGreen:`rgba(${p.r}, ${p.g}, ${p.b}, 0.28)`,brandBorderStrong:`rgba(${p.r}, ${p.g}, ${p.b}, 0.55)`,composerBorder:`rgba(${p.r}, ${p.g}, ${p.b}, 0.75)`,accentEdge:`rgb(${f(p.r)}, ${f(p.g)}, ${f(p.b)})`}:c?pg(n,r.color.text):{},y={brightness:r.brightness,highContrast:r.highContrast,meta:{displayName:t.displayName??r.meta.displayName,logoUrl:(o?t.logoUrlDark??t.logoUrl:t.logoUrl)??r.meta.logoUrl,placeholder:t.placeholder??r.meta.placeholder,hidePoweredBy:t.hidePoweredBy??r.meta.hidePoweredBy},color:{...r.color,...m,...dg(t.surfaceStyle??null,n),primary:d,accent:u,onPrimary:r.color.onPrimary,onAccent:r.color.onAccent},space:r.space,radius:mg(t.radiusScale??null,r.radius,n),type:{...r.type,...ug(r.type,t),maxScale:t.accessibilityMaxFontScale??r.type.maxScale},motion:r.motion,slots:Cl(r.slots,t.slots??null)};return We(y)}i(Al,"withServerBranding");var sg={regular:["regular"],medium:["medium","regular"],bold:["bold","medium","regular"],mono:["mono"],monoMedium:["monoMedium","mono"],monoBold:["monoBold","monoMedium","mono"]},lg=[["regular","medium","bold"],["mono","monoMedium","monoBold"]];function Ho(e){return e==="mono"||e==="monoMedium"||e==="monoBold"}i(Ho,"isMonoFace");function ug(e,t){let r=t.fonts??{},n=t.fontUrls??{},o={...e.families},a={...e.namedFaces},s={...e.fontUrls};for(let l of ur){let u=sg[l].map(p=>r[p]).find(p=>p!==void 0),c=Ho(l)?null:t.fontFamily;u!==void 0?(o[l]=u,a[l]=true):c!==null&&(o[l]=c,a[l]=false);let d=n[l]??(l==="regular"?t.fontUrl:null)??null;d!==null?s[l]=d:u!==void 0&&delete s[l];}for(let l of lg)for(let u of l)a[u]&&l.some(c=>c!==u&&o[c]===o[u])&&(a[u]=false);return {family:o.regular,mono:o.mono,fontUrl:s.regular??null,families:o,namedFaces:a,fontUrls:s}}i(ug,"mergeFaces");function Ol(e){return e===null?null:bl(e)}i(Ol,"darkVariantOf");function dg(e,t){if(e===null)return {};let r=t.color;return {chatGround:e==="white"?r.surface:e==="subtle"?r.surfaceSubtle:r.surfaceCream}}i(dg,"surfaceOf");function Fl(e,t){return e==null?false:ye(e)===ye(t)}i(Fl,"sameColor");function cg(e,t,r,n){return Fl(t,r.color.primary)?true:n&&(e.primaryColorDark??null)===null&&Fl(e.primaryColor,Et.color.primary)}i(cg,"isCompiledPrimary");function pg(e,t){let r=e.color;return {text:{...t,secondary:r.text.secondary},brand:r.brand,bubbleUser:r.bubbleUser,brandInk:r.brandInk,brandSoft:r.brandSoft,brandSofter:r.brandSofter,brandBorder:r.brandBorder,borderHairlineGreen:r.borderHairlineGreen,brandBorderStrong:r.brandBorderStrong,composerBorder:r.composerBorder,accentEdge:r.accentEdge}}i(pg,"compiledBrandFamily");var fg={sharp:.5,default:1,round:1.5};function mg(e,t,r){if(e===null)return t;let n=fg[e],o=r.radius,a=i(s=>Math.round(s*n),"s");return {tile:a(o.tile),xs:a(o.xs),sm:a(o.sm),md:a(o.md),lg:a(o.lg),xl:a(o.xl),pill:o.pill}}i(mg,"radiusOf");var yg="Everfur",gg=.5;function Uo(e){let t=e?.branding??null,r=Pl(t)?t:null,n=Cg(e?.clientOverride??null,_l(r)),o=e?.colorScheme==="dark"?"dark":"light",a=n?.brightness??r?.brightness??"light",u=Al((a==="auto"?o:a)==="dark"?Yr:Et,Ml(r)),c=Al(u,Ml(n));return Fg(c,e)}i(Uo,"resolveTheme");function hg(e,t,r){return Uo({...r,branding:Ke(t),clientOverride:Ke(e)})}i(hg,"previewTheme");function bg(e){return e==="placeholder"?"chat_placeholder":Lo(e)}i(bg,"wireNameOf");var vg={brightness:["color_scheme"],fontUrl:["font_family"],fonts:["font_family"],fontUrls:["font_url","font_family"],primaryColorDark:["primary_color"],accentColorDark:["accent_color"],logoUrlDark:["logo_url"]};function Eg(e,t){return t.has(bg(e))?true:(vg[e]??[]).some(r=>t.has(r))}i(Eg,"isLocked");function Cg(e,t){if(e===null)return null;let r=false,n={...e};for(let s of Object.keys(e))(e[s]??null)!==null&&(Eg(s,t)||s==="lockedFields")&&(n[s]=null,r=true);let o=n.slots??null;if(o!==null){let s={},l=false;for(let u of Ct){let c=o[u];c!==void 0&&(t.has(`${lr}${u}`)?l=true:s[u]=c);}l&&(n.slots=Object.keys(s).length===0?null:Object.freeze(s),r=true);}if(!r)return e;let a=Object.freeze(n);return Qr(a)?null:a}i(Cg,"withoutFields");function Ml(e){return e===null||e.brightness===null?e:Object.freeze({...e,brightness:null})}i(Ml,"withoutBrightness");function Rg(e,t){if(t===1)return e;let r={};for(let[n,o]of Object.entries(e))r[n]=Math.round(o*t*10)/10;return r}i(Rg,"scaledSizes");function Sg(e){return e===void 0||!Number.isFinite(e)?1:Math.max(gg,e)}i(Sg,"effectiveScale");var Dl=["content","heading","control","compact","badge"];function xg(e){if(!(e>0))return qr;let t={};for(let r of Dl){let n=qr[r];t[r]=n===0?0:Math.min(n,e);}return t}i(xg,"tierCaps");function Tg(e,t){return t>0?Math.min(e,t):e}i(Tg,"capped");function kg(e,t,r,n){let o={};for(let a of Dl)o[a]=n?Rg(e,Tg(t,r[a])):e;return o}i(kg,"sizesByTier");function Pg(e){return e==="dark"?"#FFFFFF":"#000000"}i(Pg,"inkPole");function _g(e){return [e.surface,e.surfaceCream,e.surfaceSubtle,e.background,e.chatGround,e.composerFill]}i(_g,"textGrounds");function wg(e){return [e.surface,e.surfaceCream,e.background,e.chatGround,e.composerFill]}i(wg,"controlGrounds");function Ll(e){return [e.chatGround,e.surface,e.surfaceCream]}i(Ll,"linkGrounds");function Ig(e){return {composerInput:[e.composerFill],sendButton:[e.composerFill],userBubble:[e.bubbleUser],assistantBubble:[e.chatGround,e.surfaceCream],recordCard:[e.surface],vetVisitButton:[e.primary],primaryButton:[e.brand],link:Ll(e)}}i(Ig,"slotGrounds");function Ag(e,t){try{let r=e(t);return r===!0||r===!1?r:null}catch{return null}}i(Ag,"registration");function Og(e,t){let r=t?.isFontRegistered,n=t?.platformMonoFamily?.trim()||null;if(r===void 0&&n===null)return {family:e.family,mono:e.mono,families:e.families,namedFaces:e.namedFaces};let o={...e.families},a={...e.namedFaces};for(let s of ur)!(o[s]===bt||o[s]===rt)&&r!==void 0&&Ag(r,o[s])===false&&(o[s]=Ho(s)?rt:bt,a[s]=false),n!==null&&Ho(s)&&o[s]===rt&&(o[s]=n);return {family:o.regular,mono:o.mono,families:o,namedFaces:a}}i(Og,"platformFaces");function Fg(e,t){let r=e.color.primary,n=e.color.accent,o=e.meta.displayName.trim().length===0?yg:e.meta.displayName,a=No(e.meta.logoUrl),s={};for(let _ of ur){let w=e.type.fontUrls[_];w!==void 0&&(s[_]=No(w));}let l=s.regular??null,c=t?.reducedMotion===true?{duration:{instant:0,fast:0,normal:0,slow:0},spring:{gentle:{damping:100,stiffness:1e3}},easing:e.motion.easing,reducedMotion:true}:e.motion,d=Number.isFinite(e.type.maxScale)?e.type.maxScale:Fo,p=Sg(t?.textScale),f=xg(d),m=kg(e.type.size,p,f,t?.scaleTypeSizes===true),y=e.color,R=Pg(e.brightness),b=_g(y),T={...y,primary:r,accent:n,onPrimary:ir(r,Pe),onAccent:ir(n,Pe),brandInk:tt(y.brandInk,b,R,Pe),linkInk:tt(e.slots.link?.textColor??n,Ll(y),R,Pe),text:{...y.text,secondary:tt(y.text.secondary,b,R,Pe)},brandBorderStrong:tt(y.brandBorderStrong,wg(y),R,Do)},x={brightness:e.brightness,highContrast:false,meta:{displayName:o,logoUrl:a,placeholder:e.meta.placeholder,hidePoweredBy:e.meta.hidePoweredBy},color:T,space:e.space,radius:e.radius,type:{...e.type,...Og(e.type,t),fontUrl:l,fontUrls:s,size:m.content,tierSizes:m,scale:p,maxScale:d,scaleCaps:f},motion:c,slots:Rl(e.slots,Ig(T))};return t?.highContrast===true?vl(We(x)):We(x)}i(Fg,"finalize");var Nl="/widget/v1/entitlements",Mg=304,Dg=Object.freeze({kind:"notModified"});async function Ul(e,t={},r=Te({auth:e})){let n=await r.send("entitlements.fetch",Ng(t));return n.ok?Hg(n.value):n.error.httpStatus===Mg?Dg:{kind:"failed",error:n.error}}i(Ul,"fetchEntitlements");var Lg=64;function Ng(e){let t={};return zo(e.cachedRevision)&&(t["if-none-match"]=`"${e.cachedRevision}"`),e.region&&e.region.length<=Lg?{method:"GET",path:Nl,headers:t,query:{region:e.region}}:{method:"GET",path:Nl,headers:t}}i(Ng,"buildRequest");function Hg(e){if(e===null||typeof e!="object"||!zo(e.revision))return Hl();let t=typeof e.region=="string"?e.region:"",r=zo(e.ttl_seconds)?e.ttl_seconds:0;return Object.freeze({kind:"updated",revision:e.revision,region:t,ttlSeconds:r,decisions:zg(e.capabilities),branding:Ug(e)})}i(Hg,"parseUpdated");function Ug(e){let t=Ke(e.branding);if(t!==null)return t;let r=e.render_hints;if(r!==null&&typeof r=="object"){let n=Ke(r.branding);return n!==null?n:Ke(r)}return null}i(Ug,"parseBranding");function zg(e){if(e===null||typeof e!="object")return Object.freeze([]);let t=[];for(let[r,n]of Object.entries(e))Bg(n)&&t.push(Object.freeze({resource:r,granted:true}));return Object.freeze(t)}i(zg,"mapCapabilities");function Bg(e){return typeof e=="object"&&e!==null&&e.enabled===true}i(Bg,"isEnabled");function Hl(){return {kind:"failed",error:D("internalError",{retryable:true,wireMessage:"malformed entitlements response"})}}i(Hl,"malformed");function zo(e){return typeof e=="number"&&Number.isFinite(e)}i(zo,"isFiniteNumber");var jg=30;function zl(e){let t=e.scheduler??Vg,r=e.resolve??Ul,n=Math.max(1,e.floorSeconds??jg),o=e.rng??Math.random,a=i(()=>n+o()*n,"jitteredFloorSeconds"),s=false,l=false,u=null,c=null,d=n,p=0,f=i(()=>{u!==null&&(t.clear(u),u=null);},"clearTimer"),m=i(T=>{l||!s||(d=Math.max(n,T),u=t.set(()=>{u=null,b();},d*1e3));},"schedule"),y=null,R=i(async()=>{if(l)return null;let T=p;e.onFetch?.();let x=e.region?{cachedRevision:c,region:e.region}:{cachedRevision:c},_;try{_=await r(e.authFor(),x);}catch(w){return e.telemetry?.track("sdk.entitlements.poll_error",{reason:$g(w)}),!l&&T===p&&(e.onSettled?.(),m(a())),null}if(l||T!==p)return null;switch(_.kind){case "updated":c=_.revision,e.update(_.decisions,_.branding??null),m(_.ttlSeconds);break;case "notModified":m(d);break;case "failed":e.telemetry?.track("sdk.entitlements.poll_failed",{code:_.error.code}),m(a());break;default:m(a());}return e.onSettled?.(),_},"tick"),b=i(()=>{let T=R().finally(()=>{y===T&&(y=null);});return y=T,T},"run");return {start(){s||l||(s=true,b());},prime(){return l?Promise.resolve(null):y??b()},stop(){l||(l=true,p++,f());},refresh(){l||!s||(p++,c=null,f(),b());}}}i(zl,"createEntitlementPoller");var Vg={set(e,t){let r=setTimeout(e,t);return r.unref?.(),r},clear(e){clearTimeout(e);}};function $g(e){return e instanceof Error?e.message:"poll failed"}i($g,"describe");var Bl="everfur.notifications.device";var Wg=3e3,jl=Object.freeze([Bl]);function Vl(e){let{leaving:t,identity:r,hooks:n,telemetry:o}=e;if(t===null||r===null||n.size===0)return null;let a=Object.freeze({userRef:t.userRef,auth:e.graceAuth()}),s=[...n].map(c=>{try{return Promise.resolve(c(a))}catch(d){return Promise.reject(d)}}),l=i((c,d)=>{try{o.track("sdk.logout.hookFailed",{reason:c,count:d,totalCount:s.length});}catch{}},"report"),u=Promise.allSettled(s).then(c=>{let d=c.filter(p=>p.status==="rejected").length;d>0&&l("failed",d);});return new Promise(c=>{let d=false,p=i(()=>{d||(d=true,clearTimeout(f),c());},"finish"),f=setTimeout(()=>{d||l("timeout",s.length),p();},Wg);u.then(p,p);})}i(Vl,"startBeforeLogoutHooks");function $l(e){let{leaving:t,identity:r,transport:n,sessionId:o}=e,a=r.currentToken();a.catch(()=>{});let s={userRef:t.userRef,currentToken:i(()=>a,"currentToken"),hasToken:i(()=>true,"hasToken"),clear:i(()=>{},"clear")};return {mode:"personalized",transport:n,identity:s,userRef:t.userRef,sessionId:o}}i($l,"graceAuth");async function Wl(e,t){if(jl.length===0)return;let r=await Promise.allSettled(jl.map(o=>e.removeItem(o))),n=r.filter(o=>o.status==="rejected").length;n>0&&t.track("sdk.logout.sweepPartialFailure",{failedCount:n,totalCount:r.length});}i(Wl,"sweepPerUserKv");function Kg(){return Object.freeze([Object.freeze({resource:"chat.message.create",granted:true})])}i(Kg,"compiledDefaultDecisions");function Bo(e=Kg){let t=new Set,r=Object.freeze({decisions:e(),isPending:false,branding:null}),n=i(()=>{for(let o of t)o();},"emit");return {subscribe(o){return t.add(o),()=>{t.delete(o);}},getSnapshot(){return r},set(o){r=Object.freeze({decisions:Object.freeze([...o.decisions]),isPending:o.isPending,branding:o.branding??null}),n();},reset(){r=Object.freeze({decisions:e(),isPending:false,branding:null}),n();},setPending(o){r.isPending!==o&&(r=Object.freeze({...r,isPending:o}),n());}}}i(Bo,"createEntitlementStore");function jo(e){return D("validationFailed",{retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`})}i(jo,"notConfiguredError");function Kl(e,t){let r={publishableKey:e.publishableKey,...e.apiBaseUrl!==void 0?{apiBaseUrl:e.apiBaseUrl}:{},...e.contractVersion!==void 0?{contractVersion:e.contractVersion}:{},...e.debug!==void 0?{debug:e.debug}:{}};return Oa(r,t===void 0?void 0:{platform:t})}i(Kl,"tryResolveClient");function Gl(e){return Object.freeze({track(t,r){try{e.track(t,r);}catch{}},trackExpectedFailure(t,r){try{e.trackExpectedFailure(t,r);}catch{}}})}i(Gl,"guardTelemetry");function ql(e,t){try{t.trackExpectedFailure("sdk.config.invalid",{reason:e.reason});}catch{}globalThis.console?.error?.(`[everfur] SDK disabled: ${e.message}
12
+ [everfur] Every Everfur capability will render its off-state until this is fixed. If the value is set in your environment, note that babel-preset-expo inlines only EXPO_PUBLIC_* variables into a release bundle.`);}i(ql,"reportConfigFailure");function Vo(e){return Object.freeze({request(){return Promise.resolve(E(jo(e)))},stream(t,r){let n=pe({code:"sdk_not_configured",retryable:false,wireMessage:`Everfur SDK is not configured: ${e.message}`,synthesized:true,lastEventId:null});return {async*[Symbol.asyncIterator](){r.aborted||(yield n);}}}})}i(Vo,"refusingTransport");function Yl(){let e=new Map;return {async getItem(t){return e.get(t)??null},async setItem(t,r){e.set(t,r);},async removeItem(t){e.delete(t);},async keys(t){return [...e.keys()].filter(r=>r.startsWith(t))}}}i(Yl,"createInMemoryKv");var Xl=Object.freeze({clearMemoryCache(){},clearDiskCache(){}});function Jl(e,t){return new Wo(e,t)}i(Jl,"createEverfurRuntime");var Gg=6e4,Ko=class Ko{constructor(t,r){this.sessionId=Xn();this.entries=new Map;this.destroyers=new Map;this.epoch=0;this.disposed=false;this.verdictSettled=false;this.refreshTimer=null;this.bootstraps=new WeakMap;this.prepared=null;this.beforeLogoutHooks=new Set;this.pendingBeforeLogout=null;this.leavingSessionId=null;let n=t.config;if(n.secureStore!==void 0&&n.secureStore.isAvailable===true)throw new J("invalid-argument","config.secureStore is not yet consumable: SDK token persistence is unimplemented. Omit secureStore to keep memory-only tokens (SPEC-10 \xA75.3).");this.telemetry=n.telemetry?Gl(n.telemetry):Ar;let o=typeof n?.publishableKey=="string"?n.publishableKey.trim():"",a=Zn(n?.publishableKey),s=n.transport!==void 0,l,u=typeof n.apiBaseUrl=="string"&&n.apiBaseUrl.trim().length>0?n.apiBaseUrl.trim():null;if(a!==null)l=Vo(a);else if(n.transport!==void 0)l=n.transport;else {let d=Kl(n,r?.platform);d.ok?(u=d.config.apiBaseUrl,l=Ha({config:d.config,...r?.eventSourceFactory?{eventSourceFactory:r.eventSourceFactory}:{}})):(a=d.failure,l=Vo(d.failure));}this.configFailure=a,this.publishableKey=a===null?o:"",this.transport=l,a!==null&&ql(a,this.telemetry),this.errorPolicy=n.errorPolicy,this.camera=n.camera??ga,this.upload=n.upload??rs,this.uploadTransport=n.uploadTransport??bo,this.imageCache=n.imageCache??Xl,this.kv=n.storage??Yl(),this.currentUser=t.user??null,this.identity=this.buildIdentity(t.user??null),this.activePet=t.activePet,this.store=a===null?Bo():Bo(()=>rl("sdk_config",At("accessDenied"))),this.services={authFor:i(d=>this.buildAuth(d),"authFor"),telemetry:this.telemetry,errorPolicy:this.errorPolicy,camera:this.camera,upload:this.upload,uploadTransport:this.uploadTransport,imageCache:this.imageCache,kv:this.kv,apiBaseUrl:u},this.registry={services:this.services,acquireChat:i(d=>this.acquireInternal("chat",$o(d),()=>this.buildChatController(d),Ql),"acquireChat"),releaseChat:i(d=>this.releaseInternal(d),"releaseChat"),peekChat:i(d=>this.entries.get(`${this.epoch}|chat|${$o(d)}`)?.controller??null,"peekChat"),acquire:i((d,p,f,m)=>this.acquireInternal(d,p,f,m),"acquire"),release:i(d=>this.releaseInternal(d),"release")},this.entitlements=this.store;let c=a===null&&(r?.startEntitlementPolling??!s);this.poller=a===null?this.buildPoller(r?.pollScheduler):null,c&&this.poller?.start();}get isDisposed(){return this.disposed}get scopeEpoch(){return this.epoch}buildIdentity(t){if(t===null)return null;let r=Ta(t.userRef,t.getToken,n=>this.armTokenRefresh(r,n));return r}armTokenRefresh(t,r){if(this.clearTokenRefresh(),r===null||this.disposed||t!==this.identity)return;let n=r-Date.now();if(n<=0)return;let o=Math.max(n-Gg,n/2);this.refreshTimer=setTimeout(()=>{this.refreshTimer=null,!(this.disposed||t!==this.identity)&&t.currentToken({forceRefresh:true}).catch(()=>{});},o),this.refreshTimer.unref?.();}clearTokenRefresh(){this.refreshTimer!==null&&clearTimeout(this.refreshTimer),this.refreshTimer=null;}buildPoller(t){return zl({authFor:i(()=>this.buildAuth(this.currentUser?.userRef??null),"authFor"),update:i((r,n)=>this.updateEntitlements({decisions:r,isPending:false,branding:n}),"update"),onFetch:i(()=>{this.verdictSettled||this.store.setPending(true);},"onFetch"),onSettled:i(()=>{this.verdictSettled=true,this.store.setPending(false);},"onSettled"),telemetry:this.telemetry,...t?{scheduler:t}:{}})}acquireInternal(t,r,n,o,a=false){let s=`${this.epoch}|${t}|${r}`,l=this.entries.get(s);if(l)return a||(l.warm?l.warm=false:l.refCount+=1),l.controller;let u=n();return this.entries.set(s,{controller:u,refCount:1,warm:a}),this.destroyers.set(u,o),u}releaseInternal(t){for(let[r,n]of this.entries)if(n.controller===t){n.refCount-=1,n.refCount<=0&&(this.runDestroyer(t),this.entries.delete(r));return}}runDestroyer(t){let r=this.destroyers.get(t);this.destroyers.delete(t),r&&r(t);}buildChatController(t){let r=xs({auth:this.buildAuth(t.userRef),telemetry:this.telemetry,...this.errorPolicy?{errorPolicy:this.errorPolicy}:{},initialConversationId:t.conversationId,petRef:t.petRef});return this.runBootstrap(r,t),r}runBootstrap(t,r){let n={};r.petRef!==null&&(n.petRef=r.petRef),r.conversationId!==null&&(n.resumeConversationId=r.conversationId);let o=Ps(n,{controller:t});return o.then(a=>t.adoptPrompts(a.suggestedPrompts)).catch(()=>{}),this.bootstraps.set(t,o),o}buildAuth(t){return this.identity!==null&&this.currentUser!==null?{mode:"personalized",transport:this.transport,identity:this.identity,userRef:this.currentUser.userRef,sessionId:this.sessionId}:{mode:"anonymous",transport:this.transport,publishableKey:this.publishableKey,userRef:this.currentUser===null?null:t,sessionId:this.sessionId}}setUser(t){if(this.disposed)return;let r=t?.userRef??null,n=this.currentUser?.userRef??null;if(r===n){this.currentUser=t,t&&this.identity===null&&(this.identity=this.buildIdentity(t));return}this.pendingBeforeLogout=this.beforeLogoutSettlement(),this.identity?.clear(),this.clearTokenRefresh(),this.currentUser=t,this.identity=this.buildIdentity(t),this.rescopeAll();}async logout(){if(this.disposed)return;let t=this.currentUser===null;this.leavingSessionId=this.sessionId,this.sessionId=Xn(),this.setUser(null),this.leavingSessionId=null,t&&this.rescopeAll();let r=this.pendingBeforeLogout;this.pendingBeforeLogout=null,r!==null&&await r,await Wl(this.kv,this.telemetry);}onBeforeLogout(t){return this.disposed?()=>{}:(this.beforeLogoutHooks.add(t),()=>{this.beforeLogoutHooks.delete(t);})}beforeLogoutSettlement(){let t=this.currentUser,r=this.identity;return Vl({leaving:t,identity:r,hooks:this.beforeLogoutHooks,telemetry:this.telemetry,graceAuth:i(()=>$l({leaving:t,identity:r,transport:this.transport,sessionId:this.leavingSessionId??this.sessionId}),"graceAuth")})}async registerPet(t,r){return this.withPets("registerPet",n=>r===void 0?n.registerPet(t):n.registerPet(t,r))}updatePet(t,r){return this.withPets("updatePet",n=>n.updatePet(t,r))}deletePet(t){return this.withPets("deletePet",r=>r.deletePet(t))}eraseUserData(){return this.withPets("eraseUserData",t=>t.eraseUserData())}async withPets(t,r){return this.disposed?E(Zl(t)):r(et(this.buildAuth(this.currentUser?.userRef??null)))}prepare(t){let r=t?.petRef??null,n=`${this.epoch}|${this.currentUser?.userRef??""}|${r??""}`,o=this.prepared;if(o!==null&&o.key===n&&(o.result===null||o.result.status==="ready"))return o.promise;let a={key:n,result:null,promise:this.runPrepare(r).then(s=>(a.result=s,s))};return this.prepared=a,a.promise}async runPrepare(t){let r=Date.now(),n=this.configFailure,o=this.disposed?Zl("prepare"):n===null?null:jo(n),a=this.identity,[s,l,u]=await Promise.all([o?E(o):a===null?M(void 0):a.currentToken().then(()=>M(void 0),()=>E(D("authRejected",{retryable:false}))),o?E(o):this.primeEntitlements(),t===null?void 0:o?E(o):this.primeChat(t)]),c=s.ok?l.ok&&(u?.ok??true)?"ready":"partial":"failed",d=Date.now()-r;try{this.telemetry.track("sdk.prepare.timing",{durationMs:d,status:c});}catch{}return Object.freeze({status:c,durationMs:d,session:s,entitlements:l,...u?{chat:u}:{}})}async primeEntitlements(){let t=await this.poller?.prime();return t?t.kind==="failed"?E(t.error):M(void 0):E(D("internalError",{retryable:true}))}async primeChat(t){let r={userRef:this.currentUser?.userRef??null,petRef:t,conversationId:null},n=this.acquireInternal("chat",$o(r),()=>this.buildChatController(r),Ql,true),o=await this.bootstraps.get(n);return o?.cause&&n.getSnapshot().conversationId===null&&(o=await this.runBootstrap(n,r)),o?.cause?E(o.cause):M(void 0)}setActivePet(t){if(this.disposed)return;let r=t??null;r!==this.activePet&&(this.activePet=r,this.rescopeAll());}updateEntitlements(t){this.disposed||this.configFailure===null&&this.store.set(t);}open(t){this.telemetry.track("sdk.open",{capability:t});}dispose(){this.disposed||(this.disposed=true,this.epoch+=1,this.poller?.stop(),this.identity?.clear(),this.clearTokenRefresh(),this.disposeAllControllers());}rescopeAll(){this.epoch+=1,this.disposeAllControllers(),this.store.reset(),this.verdictSettled=false,this.poller?.refresh();}disposeAllControllers(){for(let t of this.entries.values())this.runDestroyer(t.controller);this.entries.clear(),this.destroyers.clear();}};i(Ko,"EverfurRuntimeImpl");var Wo=Ko;function $o(e){return `${e.userRef??""}|${e.petRef??""}|${e.conversationId??""}`}i($o,"chatScopeKey");function Ql(e){e.dispose();}i(Ql,"disposeChat");function Zl(e){return D("validationFailed",{retryable:false,wireMessage:`the Everfur runtime is disposed; ${e} was called after unmount`})}i(Zl,"disposedError");var eu=Symbol.for("@everfur/sdk#EverfurContext@v1"),tu=globalThis,Zr=tu[eu]??(tu[eu]=createContext(null));Zr.displayName??="EverfurContext";function X(){let e=useContext(Zr);if(e===null)throw new J("not-initialized","Everfur hooks must be called inside <EverfurProvider>. Wrap your tree once, high.");return e}i(X,"useEverfurContext");function ru(){return X().handle}i(ru,"useEverfur");var nu=Symbol.for("@everfur/sdk#EverfurThemeContext@v1"),ou=globalThis,dr=ou[nu]??(ou[nu]=createContext(Et));dr.displayName??="EverfurThemeContext";function N(){return useContext(dr)}i(N,"useEverfurTheme");function Jr(e){let{runtime:t}=X(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot),o=e.seams.useColorScheme(),a=e.seams.useReducedMotion(),s=e.seams.useTextScale(),l=e.seams.useHighContrast(),u=e.seams.scaleTypeSizes,c=e.seams.platformMonoFamily?.(),d=e.seams.isFontRegistered,p=e.clientTheme?eh(e.clientTheme):"",f=useMemo(()=>e.clientTheme?Ke(e.clientTheme):null,[p]),m=n.branding??null,y=useMemo(()=>Uo({branding:m,clientOverride:f,colorScheme:o,reducedMotion:a,textScale:s,scaleTypeSizes:u,highContrast:l,...c===void 0?{}:{platformMonoFamily:c},...d===void 0?{}:{isFontRegistered:d}}),[m,f,o,a,s,u,l,c,d]);return e.seams.useResolvedTheme?.(y),createElement(dr.Provider,{value:y},e.children)}i(Jr,"EverfurThemeProviderCore");function eh(e){try{return JSON.stringify(e)}catch{return Object.keys(e).join("&")}}i(eh,"stableKey");function uu(e){let{config:t,user:r,activePet:n,theme:o,warmUp:a,children:s,seams:l}=e,u=`${t?.publishableKey??""}|${t?.apiBaseUrl??""}|${t?.contractVersion??""}`,c=useRef(null),d=useRef(null),[p,f]=useReducer(C=>C+1,0),m=useRef(null),y=useRef(void 0),R=r?.userRef??null;y.current!==R&&(y.current!==void 0&&(m.current=null),y.current=R);let b=m.current!==null?m.current.user:r??null,T=useRef(null),x=useRef(void 0),_=n??null;x.current!==_&&(x.current!==void 0&&(T.current=null),x.current=_);let w=T.current!==null?T.current.pet:n??null;(c.current===null||c.current.key!==u||c.current.runtime.isDisposed)&&(c.current!==null&&!c.current.runtime.isDisposed&&(d.current=c.current.runtime),c.current={key:u,runtime:Jl({config:l.withDefaults?l.withDefaults(t):t,user:b,activePet:w,theme:o??null},{platform:l.platform,...l.eventSourceFactory?{eventSourceFactory:l.eventSourceFactory}:{}})});let g=c.current.runtime,S=useRef(null);useEffect(()=>{let C=c.current?.runtime;C===void 0||!C.isDisposed||S.current!==C&&(S.current=C,f());}),useEffect(()=>{let C=d.current;C!==null&&(d.current=null,C.dispose());});let I=b?.userRef??null;useLayoutEffect(()=>{g.setUser(b);},[g,I]),useLayoutEffect(()=>{g.setActivePet(w);},[g,w]),useEffect(()=>()=>g.dispose(),[g]),useEffect(()=>{a==="onMount"&&g.prepare(w===null?{}:{petRef:w});},[g,a,I,w]);let O=useMemo(()=>({setUser:i(C=>{m.current={user:C},g.setUser(C),f();},"setUser"),setActivePet:i(C=>{T.current={pet:C},g.setActivePet(C),f();},"setActivePet"),open:i(C=>g.open(C),"open"),prepare:i(C=>g.prepare(C),"prepare"),registerPet:i((C,A)=>g.registerPet(C,A),"registerPet"),updatePet:i((C,A)=>g.updatePet(C,A),"updatePet"),deletePet:i(C=>g.deletePet(C),"deletePet"),eraseUserData:i(()=>g.eraseUserData(),"eraseUserData"),logout:i(()=>{m.current={user:null};let C=g.logout();return f(),C},"logout")}),[g,f]),k=useMemo(()=>({runtime:g,handle:O,userRef:I,activePet:w,scopeEpoch:g.scopeEpoch}),[g,O,I,w,p]),v=createElement(Jr,{clientTheme:o??null,seams:l.theme,children:s});return createElement(Zr.Provider,{value:k},l.wrap?l.wrap(v):v)}i(uu,"EverfurProviderCore");var cr="everfur:";function tn(){try{if(typeof window>"u")return null;let e=window.localStorage;return e&&typeof e.getItem=="function"?e:null}catch{return null}}i(tn,"storage");function Go(){return {async getItem(e){try{return tn()?.getItem(cr+e)??null}catch{return null}},async setItem(e,t){try{tn()?.setItem(cr+e,t);}catch{}},async removeItem(e){try{tn()?.removeItem(cr+e);}catch{}},async keys(e){try{let t=tn();if(t===null)return [];let r=[],n=cr+e;for(let o=0;o<t.length;o+=1){let a=t.key(o);a!==null&&a.startsWith(n)&&r.push(a.slice(cr.length));}return Object.freeze(r)}catch{return []}}}}i(Go,"createLocalStorageKv");var pr=Object.freeze({regular:"regular",medium:"medium",bold:"bold",mono:"regular",monoMedium:"medium",monoBold:"bold"});function rh(e,t){let r=e.type,n=r.families[t];return t==="mono"||r.namedFaces[t]?{fontFamily:n}:{fontFamily:n,fontWeight:r.weight[pr[t]]}}i(rh,"face");function du(e,t){let{scale:r,scaleCaps:n}=e.type,o=n[t];return o>0?Math.min(r,o):r}i(du,"tierScale");var oh=/^https:\/\/sdk(-staging)?\.everfur\.com\/fonts\/[\w./-]+\.woff2$/;function ih(e){return oh.test(e)&&!e.includes("..")}i(ih,"isBrandFontUrl");var cu=new Map;function ah(e,t,r="400"){let n=e.trim(),o=`${n}
13
13
  ${t}
14
- ${r}`,a=uu.get(o);if(a===void 0){if(a=Promise.resolve(false),t!==null&&n!==""&&n!=="System"&&Qg(t))try{let s=document.fonts;a=new FontFace(n,`url("${t}") format("woff2")`,{display:"swap",weight:r}).load().then(l=>(s.add(l),!0)).catch(()=>!1);}catch{}uu.set(o,a);}return a}i(Zg,"loadBrandFont");var Jg=["regular","medium","bold","mono","monoMedium","monoBold"];function du(e){let{families:t,fontUrls:r,weight:n,namedFaces:o}=e.type;useEffect(()=>{for(let a of Jg){let s=r[a];s!=null&&Zg(t[a],s,o[a]?n.regular:n[dr[a]]);}},[t,r,n,o]);}i(du,"useBrandFont");function cr(e){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(e)??null}catch{return null}}i(cr,"queryFor");function Ko(e){return t=>{let r=cr(e);return r===null||typeof r.addEventListener!="function"?()=>{}:(r.addEventListener("change",t),()=>r.removeEventListener?.("change",t))}}i(Ko,"subscribeTo");var cu="(prefers-color-scheme: dark)",eh="(prefers-color-scheme: light)",pu="(prefers-reduced-motion: reduce)",fu="(prefers-contrast: more)",th=Ko(cu),rh=Ko(pu),nh=Ko(fu);function oh(){let e=cr(cu);return e===null?null:e.matches?"dark":cr(eh)?.matches?"light":null}i(oh,"readColorScheme");function ih(){return cr(pu)?.matches===true}i(ih,"readReducedMotion");function ah(){return cr(fu)?.matches===true}i(ah,"readMoreContrast");var sh=16,lh=false;var tn=null;function mu(e){return Number.parseFloat(window.getComputedStyle(e).fontSize)}i(mu,"fontPx");function uh(){let e=document.body??document.documentElement,t=document.createElement("span");t.setAttribute("aria-hidden","true"),t.style.setProperty("position","absolute","important"),t.style.setProperty("visibility","hidden","important"),t.style.setProperty("font-size","medium","important"),e.appendChild(t);try{return mu(t)}finally{t.remove();}}i(uh,"probeDefaultPx");function dh(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let e=lh?mu(document.documentElement):uh();return Number.isFinite(e)&&e>0?e/sh:1}catch{return 1}}i(dh,"measureTextScale");function ch(){return tn===null&&(tn=dh()),tn}i(ch,"readTextScale");function ph(e){if(typeof window>"u"||typeof window.addEventListener!="function")return ()=>{};let t=i(()=>{tn=null,e();},"onResize");return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)}i(ph,"subscribeTextScale");function fh(){return useSyncExternalStore(th,oh,()=>null)}i(fh,"useWebColorScheme");function mh(){return useSyncExternalStore(rh,ih,()=>false)}i(mh,"useWebReducedMotion");function yh(){return useSyncExternalStore(nh,ah,()=>false)}i(yh,"useWebHighContrast");function gh(){return useSyncExternalStore(ph,ch,()=>1)}i(gh,"useWebTextScale");var nn=Object.freeze({useColorScheme:fh,useReducedMotion:mh,useTextScale:gh,useHighContrast:yh,scaleTypeSizes:true,useResolvedTheme:du});function bh(e){return e.storage===void 0?{...e,storage:Wo()}:e}i(bh,"withWebDefaults");var vh=Object.freeze({platform:"web",withDefaults:bh,theme:nn});function Eh(e){return createElement(su,{...e,seams:vh})}i(Eh,"EverfurProvider");function Ft(e){let{runtime:t}=X(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>tl(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Ft,"useCapability");var qo=class qo extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,n){return Object.is(r.resetKey,n.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(qo,"HostRenderBoundary");var Go=qo;function xh({render:e}){return e()}i(xh,"RenderHost");function xt({render:e,fallback:t,resetKey:r}){return createElement(Go,{fallback:t,resetKey:r,children:createElement(xh,{render:e})})}i(xt,"HostRender");function Yo(e,t,r){return Math.round(r*lu(e,t)*10)/10}i(Yo,"tierPx");var gu='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',Th="System";function Xo(e){let t=e.trim();return t.length===0||t===Th?gu:`${hu(t)}, ${gu}`}i(Xo,"cssFontFamily");function kh(e){let t=e.trim();return t.length===0||t==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${hu(t)}, ui-monospace, Menlo, Consolas, monospace`}i(kh,"cssMonoFamily");function hu(e){return `"${e.replace(/[\\"]/g,"\\$&")}"`}i(hu,"quote");function k(e,t){let r=e.type,n=r.families[t];return {fontFamily:t==="mono"||t==="monoMedium"||t==="monoBold"?kh(n):Xo(n),fontWeight:r.namedFaces[t]?r.weight.regular:r.weight[dr[t]]}}i(k,"faceCss");var Ph=48;function _h(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(_h,"selectView");function Zo(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:a,className:s}=e,l=Ft(t),u=useMemo(()=>_h(l),[l]);switch(u){case "enabled":return r;case "pending":return o?jsx(xt,{render:o,fallback:jsx(bu,{capability:t,style:a,className:s})}):jsx(bu,{capability:t,style:a,className:s});case "disabled":return n?jsx(xt,{render:()=>n(l),fallback:jsx(vu,{decision:l,style:a,className:s}),resetKey:l}):jsx(vu,{decision:l,style:a,className:s});default:return Je(u)}}i(Zo,"CapabilityGate");function bu({capability:e,style:t,className:r}){let n=N(),o=useMemo(()=>Eu(n),[n]);return jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${e}`,className:r,style:{...o.offstate,...t},children:jsx("div",{style:o.skeletonBar})})}i(bu,"PendingSkeleton");function vu({decision:e,style:t,className:r}){let n=N(),o=useMemo(()=>Eu(n),[n]),a=e.disabled?.reason??"";return jsx("div",{className:r,style:{...o.offstate,...t},children:a.length>0?jsx("p",{style:o.offstateText,children:a}):null})}i(vu,"OffState");function Eu(e){let{color:t,space:r,radius:n,type:o}=e;return {offstate:{boxSizing:"border-box",minHeight:Ph,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${r.md}px ${r.lg}px`,backgroundColor:t.surfaceCream,borderRadius:n.md,border:`1px solid ${t.brandBorder}`},offstateText:{margin:0,...k(e,"regular"),fontSize:o.size.body,lineHeight:`${Math.round(o.size.body*o.lineHeight.normal)}px`,color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}}}i(Eu,"makeStyles");var h=Object.freeze({placeholder:"Ask me anything!",send:"Send",stop:"Stop",retry:"Try again",followUps:"Helpful follow-ups",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",typing:"Assistant is typing",loading:"Loading",empty:"No messages yet",transcript:"Conversation",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting\u2026",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openMenu:"Open menu",openMenuUnread:"Open menu, unread chats",yourPets:"Your Pets",yourPet:"Your pet",switchActivePet:"Switch active pet, {name}",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active \xB7 ",close:"Close",addAnotherPet:"Add another pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function K(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(K,"fillCopy");var Jo=Object.freeze([Object.freeze({key:"inaccurate",label:h.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:h.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:h.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:h.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:h.feedbackReasonOther,feedbackType:"not_helpful"})]),Cu=Object.freeze([Object.freeze({sentiment:"up",label:h.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:h.feedbackNeutral}),Object.freeze({sentiment:"down",label:h.feedbackNotHelpful})]);function wh(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(wh,"sentimentToFeedbackType");function Su(e,t){if(e==="down"&&t!==null){let r=Jo.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return wh(e)}i(Su,"feedbackTypeFor");var Fh=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function pr(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=X(),a=e?.petRef??n??null,s=e?.conversationId??null,l=useMemo(()=>({runtime:t,userRef:r,petRef:a,conversationId:s,scopeEpoch:o}),[t,r,a,s,o]),[u,d]=useState(null),c=u?.scope===l?u.controller:t.registry.peekChat({userRef:r,petRef:a,conversationId:s}),p=useRef(null);useEffect(()=>{let P=t.registry.acquireChat({userRef:r,petRef:a,conversationId:s});return p.current=P,d({scope:l,controller:P}),()=>{p.current=null,d(v=>v?.controller===P?null:v),t.registry.releaseChat(P);}},[t,r,a,s,o,l]);let f=useCallback(P=>c?c.subscribe(P):Mh,[c]),m=useCallback(()=>c?c.getSnapshot():Fh,[c]),y=useSyncExternalStore(f,m,m),S=useCallback((P,v)=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?ti(c,c.send(P,v?.imageS3Keys===void 0?{}:{imageS3Keys:v.imageS3Keys}),()=>p.current===c):Promise.resolve(ri()),[c]),g=useCallback(P=>c&&p.current===c&&!c.getSnapshot().isBootstrapping?ti(c,c.askEverfur(P),()=>p.current===c):Promise.resolve(ri()),[c]),T=useCallback(()=>c&&p.current===c?ti(c,c.retryLast(),()=>p.current===c):Promise.resolve(ri()),[c]),R=useCallback(()=>{c&&p.current===c&&c.stop();},[c]),_=useCallback(()=>{c&&p.current===c&&c.adoptConversation(null);},[c]),[w,b]=useState({controller:null,byMessage:{}}),x=w.controller===c?w.byMessage:Dh,A=useCallback(async(P,v,C,I)=>{if(!c||p.current!==c)return E(D("accessDenied"));let O=String(P),B=w.controller===c?w.byMessage[O]:void 0;if(B===v&&C==null)return b(Z=>{let q={...Z.controller===c?Z.byMessage:{}};return delete q[O],{controller:c,byMessage:q}}),M(Object.freeze({feedbackId:""}));b(Z=>({controller:c,byMessage:{...Z.controller===c?Z.byMessage:{},[O]:v}}));let V=await c.submitFeedback(P,Su(v,C??null),I??null);return p.current!==c?E(D("accessDenied")):(V.ok||b(Z=>{let q={...Z.controller===c?Z.byMessage:{}};return B===void 0?delete q[O]:q[O]=B,{controller:c,byMessage:q}}),V)},[c,w]),F=useMemo(()=>{let P=i(async v=>{if(!c||p.current!==c)return E(D("accessDenied"));let C=await v(c);return p.current===c?C:E(D("accessDenied"))},"run");return {listConversations:i(v=>P(C=>C.listConversations({...a?{petRef:a}:{},...v})),"listConversations"),getMessages:i((v,C)=>P(I=>I.getMessages(v,C)),"getMessages"),resumeConversation:i(v=>P(C=>C.resumeConversation(v)),"resumeConversation"),loadOlderMessages:i(()=>P(v=>v.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>P(v=>v.markRead()),"markRead"),refreshActiveThread:i(()=>P(v=>v.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((v,C)=>P(I=>I.answerCheckin(v,C)),"answerCheckin"),openCheckin:i(v=>P(C=>C.openCheckin(v)),"openCheckin")}},[c,a]);return useMemo(()=>({status:y.status,messages:y.messages,conversationId:y.conversationId,petRef:a,error:y.error,isStreaming:y.isStreaming,isBootstrapping:y.isBootstrapping,historyCursor:y.historyCursor??null,isLoadingHistory:y.isLoadingHistory??false,stopped:y.stopped??false,reconnecting:y.reconnecting??false,...F,suggestedPrompts:y.suggestedPrompts,unreadCount:y.unreadCount,hasUnreadThreads:y.hasUnreadThreads??false,newConversation:_,sentimentByMessage:x,feedback:A,send:S,askEverfur:g,retryLast:T,stop:R}),[y,a,S,g,T,R,F,_,x,A])}i(pr,"useEverfurChat");var Mh=i(()=>{},"NOOP_UNSUBSCRIBE"),Dh=Object.freeze({});async function ti(e,t,r){for await(let o of t);if(!r())return E(D("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?E(n.error):M(Lh(n.messages))}i(ti,"driveToResult");function Lh(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}i(Lh,"lastAssistantResponseId");function ri(){return E(D("internalError",{retryable:true}))}i(ri,"notReadyError");function Tu(e){switch(e.code){case "too_large":return K(h.attachmentTooLarge,{max:ho(zr),filename:e.filename,size:ho(e.sizeBytes??0)});case "too_many":return K(h.attachmentTooMany,{max:Br});case "unsupported_type":return K(h.attachmentUnsupported,{filename:e.filename});case "network":return h.attachmentNetwork;case "server":return K(h.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return h.attachmentCancelled;case "rate_limited":return h.attachmentRateLimited;case "quota_exceeded":return h.attachmentQuota;case "idempotency_conflict":return h.attachmentConflict;case "unknown":return h.attachmentUnknown}}i(Tu,"attachmentErrorMessage");function ku(e,t){return K(e>=t?h.attachmentsFull:h.addAttachment,{used:e,total:t})}i(ku,"attachControlLabel");var zh=Object.freeze({attachments:Object.freeze([])});function on(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=X(),o=e.maxPerMessage??Br,a=useMemo(()=>{if(e.queue)return e.queue;let{services:g}=t.registry;return ws({funnel:Te({auth:g.authFor(r),...g.errorPolicy?{errorPolicy:g.errorPolicy}:{}}),transport:e.transport??g.uploadTransport,maxPerMessage:o})},[t,r,n,o,e.queue,e.transport]);useEffect(()=>()=>{a!==e.queue&&a.dispose();},[a,e.queue]);let s=useSyncExternalStore(a.subscribe,a.getSnapshot,()=>zh),[l,u]=useState(null),d=useCallback(g=>{let R=(Array.isArray(g)?g:[g]).map(w=>a.add(w)),_=R.find(w=>!w.ok);return _!==void 0&&!_.ok&&u(_.error),R},[a,u]),c=useCallback(g=>a.retry(g),[a]),p=useCallback(g=>a.remove(g),[a]),f=useCallback(()=>a.clear(),[a]),m=useCallback(()=>u(null),[u]),y=s.attachments.some(g=>g.status==="uploading"),S=s.attachments.some(g=>g.status==="failed");return useMemo(()=>({available:a.available,attachments:s.attachments,maxPerMessage:o,uploading:y,failed:S,blocked:y||S,s3Keys:s.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[]),rejected:l,add:d,retry:c,remove:p,clear:f,dismissRejected:m}),[a.available,s,o,y,S,l,d,c,p,f,m])}i(on,"useChatAttachments");var Vh="pet_not_registered";function wu(e){return e!=null&&e.reasonCode===Vh}i(wu,"isPetNotRegistered");var $h=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function Iu(e,t,r){let{runtime:n,userRef:o,scopeEpoch:a}=X(),s=useCallback(()=>et(n.registry.services.authFor(o)),[n,o,a]),l=useMemo(()=>t===void 0?null:oi(t),[t]),[u,d]=useState({key:null,status:"idle",error:null,registered:null}),c=useRef(0),p=useRef(r);p.current=r;let f=e===null||l===null?null:`${String(o)}|${a}|${e}|${l}`,m=useCallback(()=>{if(e===null||t===void 0||f===null)return;let S=++c.current;d({key:f,status:"registering",error:null,registered:null}),s().registerPet(e,t).then(g=>{S===c.current&&(g.ok?(d({key:f,status:"registered",error:null,registered:g.value}),p.current?.()):d({key:f,status:"failed",error:g.error,registered:null}));});},[s,e,f]);useEffect(()=>{if(f===null){c.current+=1;return}return m(),()=>{c.current+=1;}},[f,m]);let y=useCallback(()=>{u.status==="failed"&&m();},[u.status,m]);return useMemo(()=>f===null?$h:u.key!==f?{status:"registering",error:null,registered:null,retry:y}:{status:u.status,error:u.error,registered:u.registered,retry:y},[f,u,y])}i(Iu,"useChatPetRegistration");function oi(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(oi).join(",")}]`:`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>`${JSON.stringify(r)}:${oi(n)}`).join(",")}}`}i(oi,"stableKey");var Kh=500;function ii(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,Kh):null}i(ii,"sanitizeSeedPrompt");function Ou(e,t,r){let n=ii(r),o=useRef(e);o.current=e;let a=useRef(null);useEffect(()=>{if(n===null||t||a.current===n)return;let s=o.current;s!==void 0&&(a.current=n,Promise.resolve(s(n)).catch(()=>{}));},[n,t]);}i(Ou,"useInitialAsk");function Gh(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}i(Gh,"isCoalesced");function Fu(e,t){let r=t.activeConversationId;return r===null||r.length===0?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:Gh(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(Fu,"decideChatRefresh");function ai(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(ai,"reportHostFailure");function qh(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(qh,"isThenable");function se(e,...t){if(typeof e=="function")try{let r=e(...t);return qh(r)&&Promise.resolve(r).then(void 0,ai),r}catch(r){ai(r);return}}i(se,"callHost");function Mu(e,...t){let r;try{r=e(...t);}catch(n){return ai(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(Mu,"callHostAsync");function Lu(e,t){let r=useRef(t);r.current=t;let n=useRef(null),o=useRef(null),a=e?.isOffline===void 0?false:se(()=>e.isOffline?.()===!0)===true,s=useRef(()=>{});s.current=l=>{let{conversationId:u,isTurnInFlight:d,refresh:c}=r.current,p=Fu(l,{activeConversationId:u,isTurnInFlight:d,isOffline:a,lastRefresh:n.current,now:Date.now()});if(p.action!=="skip"){if(p.action==="defer"){o.current!=="announced"&&(o.current=l);return}o.current=null,n.current={conversationId:p.conversationId,at:Date.now()},c!==void 0&&Promise.resolve(c()).catch(()=>{});}},useEffect(()=>{if(t.isTurnInFlight||a)return;let l=o.current;l!==null&&s.current(l);},[t.isTurnInFlight,a]),useEffect(()=>{if(e===void 0)return;let l=[],u=i((d,c)=>{if(d===void 0)return;let p=se(()=>d(()=>{s.current(c);}));typeof p=="function"&&l.push(p);},"subscribe");return u(e.onForeground?.bind(e),"foreground"),u(e.onOnline?.bind(e),"foreground"),u(e.onAnnounced?.bind(e),"announced"),()=>{for(let d of l)se(d);}},[e]);}i(Lu,"useChatLifecycle");function Xh(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(Xh,"targetKey");function Uu(e,t){let r=Xh(t),n=useRef({openCheckin:e,target:t});n.current={openCheckin:e,target:t};let o=useRef(null);useEffect(()=>{if(r===null||o.current===r)return;o.current=r;let{openCheckin:a,target:s}=n.current;a===void 0||s===void 0||Promise.resolve(a(s)).catch(()=>{});},[r]);}i(Uu,"useCheckinTarget");var W=Object.freeze({heading:"Chat History",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No matching chats",noMatchBody:"Try a different title or start a new conversation.",loading:"Loading your chats\u2026",loadFailed:"Couldn\u2019t load your chats",loadingMore:"Loading more\u2026",untitled:"New conversation",newConversation:"New conversation",newChat:"New chat",search:"Search",retry:"Try again",retryA11y:"Retry loading chats",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages\u2026",openConversation:"Open conversation",unreadPrefix:"Unread. "});function sn(e){let t=e?.replace(/\s+/g," ").trim();return t||W.untitled}i(sn,"conversationTitle");function zu(e){return `${e.unreadCount!==null&&e.unreadCount>0?W.unreadPrefix:""}${W.openConversation} ${sn(e.title)}`}i(zu,"openConversationLabel");function Hu(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(Hu,"normalizeForSearch");function tb(e,t){let r=Hu(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let a=Hu(sn(o.title)),s=a.indexOf(r);if(s<0)continue;let l=s===0?0:a.charAt(s-1)===" "?1:2;n[l]?.push(o);}return n.flat()}i(tb,"filterConversations");function li(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(li,"fresh");function Bu(e){let[t,r]=useState(false),[n,o]=useState(""),a=e.listConversations,s=useRef(0),[l,u]=useState(()=>li(a)),d=l.scope===a?l:li(a);useEffect(()=>(s.current+=1,r(false),o(""),u(li(a)),()=>{s.current+=1;}),[a]);let c=useCallback(async _=>{let w=++s.current,b=_!==void 0;u(A=>({...A,scope:a,loading:!b,loadingMore:b,error:null}));let x=await e.listConversations(_?{cursor:_}:void 0);if(w===s.current){if(!x.ok){u(A=>({...A,loading:false,loadingMore:false,error:x.error.displayMessage}));return}u(A=>{let F=_&&A.scope===a?A.rows:[],P=new Set(F.map(v=>v.id));return {scope:a,loading:false,loadingMore:false,error:null,rows:[...F,...x.value.conversations.filter(v=>!P.has(v.id))],cursor:x.value.nextCursor===_?null:x.value.nextCursor}});}},[e.listConversations,a]),p=i(()=>{r(true),o(""),c();},"show"),f=i(()=>{s.current+=1,r(false);},"close"),m=i(async _=>{let w=++s.current;u(x=>({...x,loading:true,error:null}));let b=await e.resumeConversation(_);w===s.current&&(u(x=>({...x,loading:false,error:b.ok?null:b.error.displayMessage})),b.ok&&r(false));},"resume"),y=i(async()=>{let _=s.current,w=await e.loadOlderMessages();_===s.current&&!w.ok&&u(b=>({...b,error:w.error.displayMessage}));},"earlier"),S=i(()=>{e.newConversation(),s.current+=1,r(false);},"newConversation"),g=i(()=>{d.cursor===null||d.loading||d.loadingMore||n.trim().length>0||c(d.cursor);},"loadMore"),T=useMemo(()=>tb(d.rows,n),[d.rows,n]),R=n.trim().length>0;return {...d,open:t,show:p,close:f,load:c,resume:m,earlier:y,newConversation:S,loadMore:g,query:n,setQuery:o,searching:R,filtered:T,emptyKind:d.rows.length===0?"empty":"noMatch"}}i(Bu,"useHistoryPanel");var ln="#111111",un="#FFFFFF",ob=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:ln,pillColor:un,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:ln,pillColor:un,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ln,pillColor:un,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:ln,pillColor:un,showsVetAction:false})});function ib(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(ib,"urgencySignature");function ab(e){return K(h.urgencyGeneralReason,{petName:e?.trim()||h.emptyTitlePetFallback})}i(ab,"generalUrgencyReason");function $u(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let o=n.urgencyLevel;return o?{messageId:n.id,level:o,reason:n.urgencyReason??null}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:ab(t)}:null}return null}i($u,"latestUrgencySource");function Wu(e){let t=e===null?null:ib(e),[r,n]=useState(null),[o,a]=useState(false);useEffect(()=>a(false),[t]);let l=e!==null&&(o||!(r!==null&&r===t)),u=e===null?null:ob[e.level],d=e!==null&&!l&&e.level!=="general",c=useCallback(()=>{t!==null&&n(t),a(false);},[t]),p=useCallback(()=>a(true),[]);return useMemo(()=>({source:e,tier:u,signature:t,showBanner:l,showCompactIcon:d,showVetAction:l&&u!==null&&u.showsVetAction,dismissLabel:u===null?null:K(h.dismissBanner,{label:u.label}),dismiss:c,expand:p}),[e,u,t,l,d,c,p])}i(Wu,"useUrgencySurface");function Ku(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(Ku,"selectView");function sb(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(sb,"needsNewConversation");function Gu(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=sb(t);return {tone:"error",title:r?h.turnUnreachableTitle:h.turnFailedTitle,body:t.displayMessage,actionLabel:r?h.turnStartNewChat:h.turnRetry,action:r?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:h.turnStoppedTitle,body:h.turnStoppedBody,actionLabel:h.turnRetry,action:"retry"}:null}i(Gu,"turnNotice");function dn(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(dn,"awaitingAssistant");function qu(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(qu,"buildChatOpts");function cn(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=X(),o=useMemo(()=>et(e.registry.services.authFor(t)),[e,t,n]),[a,s]=useState({repository:o,pets:[],loading:true,error:null}),l=a.repository===o?a:{pets:[],loading:true,error:null},u=useRef(0),d=useCallback(async()=>{let p=++u.current;s(m=>({...m,repository:o,loading:true,error:null,pets:m.repository===o?m.pets:[]}));let f=await o.list();p===u.current&&s(f.ok?{repository:o,pets:f.value,loading:false,error:null}:m=>({repository:o,pets:m.repository===o?m.pets:[],loading:false,error:f.error}));},[o]);useEffect(()=>(d(),()=>{u.current+=1;}),[d]);let c=useMemo(()=>r===null?null:l.pets.find(p=>p.petRef===r)??null,[r,l.pets]);return useMemo(()=>({pets:l.pets,activePet:c,loading:l.loading,error:l.error,refresh:d}),[l.pets,l.loading,l.error,c,d])}i(cn,"useEverfurPets");function Yu(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(Yu,"headerPetOf");var it=Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var mr=2,fb="data-ef-focus-ring",Xu="data-ef-focus-ring-color";function di(e){return {outline:`${mr}px solid ${e}`,outlineOffset:mr}}i(di,"focusRingStyle");var fn=false,pn=0;function Qu(e){e.metaKey||e.ctrlKey||e.altKey||(fn=true);}i(Qu,"onKeyDown");function Mt(){fn=false;}i(Mt,"onPointerDown");function mb(){return typeof document>"u"?()=>{}:(pn===0&&(document.addEventListener("keydown",Qu,true),document.addEventListener("pointerdown",Mt,true),document.addEventListener("mousedown",Mt,true),document.addEventListener("touchstart",Mt,true)),pn+=1,()=>{pn-=1,!(pn>0)&&(document.removeEventListener("keydown",Qu,true),document.removeEventListener("pointerdown",Mt,true),document.removeEventListener("mousedown",Mt,true),document.removeEventListener("touchstart",Mt,true),fn=false);})}i(mb,"bindModality");var yb=new Set(["","text","search","email","tel","url","password","number"]);function gb(e){return e.tagName==="TEXTAREA"||e.isContentEditable?true:e.tagName!=="INPUT"?false:yb.has((e.getAttribute("type")??"").toLowerCase())}i(gb,"isTextField");function Zu(e,t){useEffect(()=>{let r=e.current;if(r===null)return;let n=mb(),o=new Map,a=i(l=>{let u=l.target;if(!(u instanceof HTMLElement)||o.has(u)||u.closest(`[${fb}="self"]`)!==null||!fn&&!gb(u))return;o.set(u,{outline:u.style.outline,outlineOffset:u.style.outlineOffset});let d=u.closest(`[${Xu}]`),c=di(d?.getAttribute(Xu)||t);u.style.outline=c.outline,u.style.outlineOffset=`${c.outlineOffset}px`;},"onFocusIn"),s=i(l=>{let u=l.target;if(!(u instanceof HTMLElement))return;let d=o.get(u);d!==void 0&&(o.delete(u),u.style.outline=d.outline,u.style.outlineOffset=d.outlineOffset);},"onFocusOut");return r.addEventListener("focusin",a),r.addEventListener("focusout",s),()=>{r.removeEventListener("focusin",a),r.removeEventListener("focusout",s);for(let[l,u]of o)l.style.outline=u.outline,l.style.outlineOffset=u.outlineOffset;o.clear(),n();}},[e,t]);}i(Zu,"useKeyboardFocusRing");var ci=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function ed(e){let t=N(),r=useMemo(()=>bb(t),[t]);return jsxs("div",{role:"note",className:e.className,style:{...r.container,...e.style},children:[jsx("p",{style:r.title,children:ci.title}),jsx("p",{style:r.body,children:ci.body})]})}i(ed,"ClinicalDisclaimer");function bb(e){let{color:t,space:r,type:n}=e,o=`${Math.round(n.size.caption*n.lineHeight.snug)}px`;return {container:{boxSizing:"border-box",display:"flex",flexDirection:"column",gap:r.xs,padding:`${r.md}px ${r.lg}px`,borderTop:`1px solid ${t.borderHairlineGreen}`,backgroundColor:t.surfaceCream},title:{margin:0,...k(e,"bold"),fontSize:n.size.caption,lineHeight:o,color:t.text.secondary,letterSpacing:n.letterSpacing.eyebrow},body:{margin:0,...k(e,"regular"),fontSize:n.size.caption,lineHeight:o,color:t.text.muted}}}i(bb,"makeStyles");function td(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}i(td,"chatVetVisitOptions");var rd=Symbol.for("@everfur/sdk/televet");function Ge(){let e=globalThis,t=e[rd];if(t!==void 0)return t;let r={presenter:null,snapshot:Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:new Set,dailyRegistered:false};return e[rd]=r,r}i(Ge,"televetGlobal");function mn(e){let t=Ge();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(mn,"publish");function nd(e){let t=Ge().presenter;if(t===null)return "absent";try{return t(e)===!1?"declined":"presented"}catch(r){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",r),"threw"}}i(nd,"callTelevetPresenter");function od(e){let t=Ge();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(od,"subscribeTelevetExperience");function pi(){return Ge().snapshot}i(pi,"televetExperienceSnapshot");function Eb(){return Ge().hosts.length>0}i(Eb,"hasTelevetHost");function id(e){if(!Eb())return false;let t=Object.freeze({...e});return mn({request:t,serial:Ge().snapshot.serial+1}),true}i(id,"presentTelevetExperience");function fi(){Ge().snapshot.request!==null&&mn({request:null});}i(fi,"dismissTelevetExperience");function ad(){let e=Ge(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],mn({activeHost:e.hosts[0]??null}),t}i(ad,"claimTelevetHost");function sd(e){let t=Ge();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;mn(r===null?{activeHost:r,request:null}:{activeHost:r});}i(sd,"releaseTelevetHost");function dd(e){let t=null;return ()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null);}),r}}i(dd,"memoizeTelevetLoader");function cd(e){let[t,r]=useState(null);useEffect(()=>{let d=ad();return r(d),()=>{sd(d);}},[]);let n=useSyncExternalStore(od,pi,pi),a=t!==null&&n.activeHost===t?n.request:null,[s,l]=useState(null),u=a!==null&&s===null;return useEffect(()=>{if(!u)return;let d=true;return e().then(c=>{d&&l(()=>c);},c=>{d&&(console.warn("[everfur] The in-app vet visit could not load its screens.",c),fi());}),()=>{d=false;}},[u,e]),a===null||s===null?null:{module:s,request:a,serial:n.serial,dismiss:fi}}i(cd,"useTelevetExperienceHost");var Sb=dd(()=>import('@everfur/sdk/web/televet/booking'));function pd(){let e=cd(Sb);if(e===null)return null;let{EverfurTelevetDialog:t}=e.module;return jsx(t,{request:e.request,onClose:e.dismiss},e.serial)}i(pd,"EverfurTelevetHost");var mi=Object.freeze(["visit","join","summary","messages"]);function yi(e){return typeof e=="string"&&mi.includes(e)}i(yi,"isVetVisitIntent");var xb="/widget/v1/televet/handoffs",Tb="/widget/v1/televet/availability",kb="/widget/v1/televet/chat-entry",Pb=/^[a-z0-9][a-z0-9_-]{0,39}$/,_b=/^[A-Za-z0-9_-]{22}$/;var fd=32,md=128,yd=64;function hi(e){let t=e.httpStatus;switch(e.code){case "sessionRequired":return "sessionRequired";case "authExpired":case "authRejected":return "authRejected";case "sdkUpdateRequired":return "sdkUpdateRequired";case "validationFailed":return "invalidRequest";case "rateLimited":case "quotaExceeded":return "rateLimited";}return t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}i(hi,"vetVisitErrorReasonOf");function gd(e){return E(D("validationFailed",{retryable:false,wireMessage:e}))}i(gd,"invalid");function gi(e){return E(D("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(gi,"unusable");function wb(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Pb.test(n))return {ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n;}let o=t?.entry;if(o!=null){if(o!=="chat"||e===void 0)return {ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=o;}let a=t?.visitRef,s=t?.intent,l=a!=null;if(l){let u=typeof a=="string"?a.trim():"";if(u.length<1||[...u].length>yd)return {ok:false,message:`visitRef must be 1..${yd} characters`};r.visit_ref=u;}if(s!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!yi(s))return {ok:false,message:`intent must be one of ${mi.join(", ")}`};r.intent=s;}return {ok:true,body:r}}i(wb,"handoffBody");function Ib(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!yi(r)?null:Object.freeze({visitRef:t,intent:r})}i(Ib,"parseVisitEcho");function bd(e){let t=e.funnel??Te({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(hd(r,"televet.visit.handoff_failed",{reason:hi(o)}),E(o)),"failed");return {async createHandoff(o,a){let s;if(o!=null){let g=typeof o=="string"?[...o].length:0;if(g<1||g>md)return n(D("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${md} characters`}));s=o;}let l=wb(s,a);if(!l.ok){let g=gd(l.message);return g.ok?g:n(g.error)}let u=l.body,d=await t.send("televet.visit.handoff",{method:"POST",path:xb,body:u},{idempotent:false,maxAttempts:1});if(!d.ok)return n(d.error);let c=Ab(d.value),p=u.return_to!==void 0,f=p?d.value?.flow_id:void 0;if(p&&(typeof f!="string"||!_b.test(f))){let g=gi("the handoff response carried no usable return flow id");return g.ok?g:n(g.error)}let m=u.visit_ref!==void 0,y=m?Ib(d.value?.visit):null;if(m&&y===null){let g=gi("the handoff response did not confirm the visit it opens");return g.ok?g:n(g.error)}let S=c===null?null:Object.freeze({...c,...p?{flowId:f}:{},...y!==null?{visit:y}:{}});return S===null?n(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(hd(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),M(S))},async checkAvailability(o){if(typeof o!="string"||o.length>fd)return gd(`state must be at most ${fd} characters`);let a=await t.send("televet.visit.availability",{method:"POST",path:Tb,body:{state:o}},{idempotent:false,maxAttempts:1});if(!a.ok)return E(a.error);let s=a.value?.available;return typeof s!="boolean"?gi("the availability response carried no usable answer"):M(Object.freeze({available:s}))},async chatEntryOpen(){try{let o=await t.send("televet.visit.chat_entry",{method:"GET",path:kb},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(bd,"createVetVisitController");function Ab(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!Db(t)?null:Object.freeze({url:t,expiresAt:r})}i(Ab,"parseHandoff");var Ob=new Set(["localhost","127.0.0.1","[::1]"]),Fb=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,Mb=/[\s\u0000-\u001f\u007f]/;function Db(e){if(Mb.test(e))return false;let t=Fb.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let o=n.replace(/:\d+$/,"").toLowerCase(),a=r==="https",s=r==="http"&&Ob.has(o);if(!a&&!s)return false;let l=e.indexOf("#");if(l<0)return false;let u=e.slice(l);return u.startsWith("#h=")&&u.length>3}i(Db,"isOpenableVisitUrl");function hd(e,t,r){if(e)try{e.track(t,r);}catch{}}i(hd,"safeTrack");var vd=false;function Ed(e,t){return t!==void 0?(se(t,e),"onStartInApp"):nd(e)==="presented"?"presenter":id(e)?"experience":(vd||(vd=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(Ed,"openVetVisitInApp");var bi=Object.freeze({status:"idle",error:null,errorReason:null});function Nb(e,t,r){let{usState:n,chat:o,scope:a}=r,s=t&&(n!==null||o),l=`${n??""}|${o?"chat":""}`,[u,d]=useState(null);if(useEffect(()=>{if(!s)return;let p=true,f=e.current;return d(null),i(async()=>{try{if(o&&!(f.chatEntryOpen&&await f.chatEntryOpen()))return !1;if(n===null)return !0;if(!f.checkAvailability)return !1;let y=await f.checkAvailability(n);return y.ok&&y.value.available}catch{return false}},"ask")().then(y=>{p&&d({key:l,open:y});}),()=>{p=false;}},[s,l,n,o,a,e]),!s)return null;let c=u!==null&&u.key===l;return {open:c&&u.open,pending:!c}}i(Nb,"usePreflight");var Ub=Object.freeze({status:"opening",error:null,errorReason:null});function Rd(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=X(),a=Ft("televet"),s=a.enabled&&n!==null,l=t.usState??null,u=t.entry==="chat",d=t.petRef??null,c=t.prefer==="redirect",p=useMemo(()=>{if(t.controller)return t.controller;let{services:C}=r.registry;return bd({auth:C.authFor(n),telemetry:C.telemetry,...C.errorPolicy?{errorPolicy:C.errorPolicy}:{}})},[r,n,o,t.controller]),f=useRef(p);f.current=p;let m=useMemo(()=>({runtime:r,userRef:n,scopeEpoch:o}),[r,n,o]),y=Nb(f,s,{usState:l,chat:u,scope:m}),S=s&&(y===null||y.open)&&(!u||d!==null),g=t.returnTo??null,[T,R]=useState(bi),_=useRef(null),w=useRef({runtime:r,userRef:n,scopeEpoch:o});w.current={runtime:r,userRef:n,scopeEpoch:o};let b=useRef(p);b.current=p;let x=useRef(S);x.current=S;let A=useCallback((C,I)=>{if(_.current)return _.current;let O=i(($,be)=>(R({status:$==="cancelled"?"idle":"error",error:be,errorReason:$==="cancelled"?null:$}),Object.freeze({opened:false,reason:$,error:be})),"fail");if(!x.current)return Promise.resolve(O("unavailable",null));let B=e.prepare();if(!B.ok)return Promise.resolve(O(B.reason,null));let V=w.current,Z=b.current;R(Ub);let Be=(async()=>{let $,be={...g!==null?{returnTo:g}:{},...u?{entry:"chat"}:{},...I!==null?{visitRef:I.visitRef}:{},...I!==null&&I.intent!==null&&I.intent!==void 0?{intent:I.intent}:{}},we=Object.keys(be).length===0?void 0:be,lt=C===void 0?d:C;try{$=await(we===void 0?Z.createHandoff(lt):Z.createHandoff(lt,we));}catch{return e.abandon(B.value),O("unknown",null)}let ut=w.current;if(ut.runtime!==V.runtime||ut.userRef!==V.userRef||ut.scopeEpoch!==V.scopeEpoch)return e.abandon(B.value),O("cancelled",null);if(!$.ok)return e.abandon(B.value),O(hi($.error),$.error);let Ze=await e.finish(B.value,$.value);return Ze!==null?O(Ze,null):(R(bi),Object.freeze($.value.flowId===void 0?{opened:true}:{opened:true,flowId:$.value.flowId}))})().finally(()=>{_.current===Be&&(_.current=null);});return _.current=Be,Be},[e,d,g,u]),F=useCallback((C,I)=>{if(!x.current)return R({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let O=C===void 0?d:C,B={...O!==null?{petRef:O}:{},...l!==null?{usState:l}:{},...I!==null?{visitRef:I.visitRef,intent:I.intent}:{}};return Ed(B)===null?(R({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(R(bi),Promise.resolve(Object.freeze({opened:true})))},[d,l]),P=useCallback(C=>c?A(C,null):F(C,null),[c,A,F]),v=useCallback((C,I)=>c?A(void 0,{visitRef:C,intent:I??null}):F(void 0,{visitRef:C,intent:I??null}),[c,A,F]);return {available:S,isPending:a.isPending||(y?.pending??false),status:T.status,error:T.error,errorReason:T.errorReason,open:P,openVisit:v}}i(Rd,"useVetVisitWith");function xd(e){try{e.closed||e.close();}catch{}}i(xd,"closeQuietly");var Hb=Object.freeze({prepare(){let e=null;try{e=typeof window>"u"?null:window.open("about:blank","_blank");}catch{e=null;}if(e===null)return {ok:false,reason:"popupBlocked"};try{e.opener=null;}catch{}return {ok:true,value:{tab:e}}},async finish({tab:e},t){if(e.closed)return "cancelled";try{return e.location.replace(t.url),null}catch{return xd(e),"popupBlocked"}},abandon({tab:e}){xd(e);}});function Td(e){return Rd(Hb,e)}i(Td,"useVetVisit");var Pd='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function _d(e){return e.tagName==="DIALOG"}i(_d,"isDialogElement");function qe(e,t,r){let n=useRef(null),o=useRef(false),a=useRef(null),s=useRef(r);s.current=r;let l=useCallback(()=>{if(!o.current)return;o.current=false;let c=s.current===void 0?a.current:s.current.current;a.current=null,c&&c.isConnected&&c.focus();},[]);useEffect(()=>{if(!e){l();return}if(!o.current){let f=typeof document>"u"?null:document.activeElement;a.current=f instanceof HTMLElement?f:null;}o.current=true;let c=n.current;if(c===null)return;if(!_d(c)){c.contains(document.activeElement)||(c.querySelector(Pd)??c).focus();return}let p=c;typeof p.showModal=="function"?p.open||p.showModal():p.setAttribute("open","");},[e,l]),useEffect(()=>l,[l]);let u=useCallback(c=>{let p=n.current;if(p===null)return;if(c.key==="Escape"&&!_d(p)){c.preventDefault(),c.stopPropagation(),t();return}if(c.key!=="Tab")return;let f=Array.from(p.querySelectorAll(Pd)),m=f[0],y=f[f.length-1];if(!m||!y){c.preventDefault();return}let S=document.activeElement;c.shiftKey&&(S===m||!p.contains(S))?(c.preventDefault(),y.focus()):!c.shiftKey&&(S===y||!p.contains(S))&&(c.preventDefault(),m.focus());},[t]),d=useCallback(c=>{c.preventDefault(),t();},[t]);return {dialogRef:n,onKeyDown:u,onCancel:d}}i(qe,"useModalDialog");var zb=Object.freeze({check:jsx("polyline",{points:"20 6 9 17 4 12"}),copy:jsxs(Fragment,{children:[jsx("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),jsx("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),thumbsUp:jsxs(Fragment,{children:[jsx("path",{d:"M7 10v12"}),jsx("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),thumbsDown:jsxs(Fragment,{children:[jsx("path",{d:"M17 14V2"}),jsx("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),info:jsxs(Fragment,{children:[jsx("circle",{cx:"12",cy:"12",r:"10"}),jsx("path",{d:"M12 16v-4"}),jsx("path",{d:"M12 8h.01"})]}),x:jsxs(Fragment,{children:[jsx("path",{d:"M18 6 6 18"}),jsx("path",{d:"m6 6 12 12"})]}),mapPin:jsxs(Fragment,{children:[jsx("path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}),jsx("circle",{cx:"12",cy:"10",r:"3"})]}),bookOpen:jsxs(Fragment,{children:[jsx("path",{d:"M12 7v14"}),jsx("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]}),chevronDown:jsx("path",{d:"m6 9 6 6 6-6"}),arrowUpRight:jsxs(Fragment,{children:[jsx("path",{d:"M7 7h10v10"}),jsx("path",{d:"M7 17 17 7"})]}),upload:jsxs(Fragment,{children:[jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),jsx("polyline",{points:"17 8 12 3 7 8"}),jsx("line",{x1:"12",x2:"12",y1:"3",y2:"15"})]}),mic:jsxs(Fragment,{children:[jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),jsx("line",{x1:"12",x2:"12",y1:"19",y2:"22"})]}),square:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),search:jsxs(Fragment,{children:[jsx("circle",{cx:"11",cy:"11",r:"8"}),jsx("path",{d:"m21 21-4.3-4.3"})]}),squarePen:jsxs(Fragment,{children:[jsx("path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),jsx("path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z"})]}),history:jsxs(Fragment,{children:[jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),jsx("path",{d:"M3 3v5h5"}),jsx("path",{d:"M12 7v5l4 2"})]}),plus:jsxs(Fragment,{children:[jsx("path",{d:"M5 12h14"}),jsx("path",{d:"M12 5v14"})]}),send:jsx("path",{d:"M17.306 1.98864C17.7329 0.807956 16.5887 -0.336175 15.408 0.0916395L0.977949 5.31038C-0.206691 5.73918 -0.349954 7.35559 0.739836 7.98694L5.346 10.6536L9.45914 6.54047C9.64549 6.36049 9.89506 6.26091 10.1541 6.26316C10.4132 6.26541 10.661 6.36932 10.8442 6.55251C11.0274 6.73569 11.1313 6.9835 11.1335 7.24256C11.1358 7.50162 11.0362 7.75119 10.8562 7.93754L6.74307 12.0507L9.41073 16.6568C10.0411 17.7466 11.6575 17.6024 12.0863 16.4187L17.306 1.98864Z"})}),Bb=Object.freeze({send:Object.freeze({viewBox:"0 0 17.3973 19.8995"})});function z({name:e,size:t,color:r,fill:n,strokeWidth:o,style:a}){let s=Bb[e];return jsx("svg",{"aria-hidden":"true",focusable:"false",width:t,height:t,viewBox:s?.viewBox??"0 0 24 24",fill:s!==void 0?r:n??"none",stroke:s!==void 0?"none":r,strokeWidth:o??2,strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0,...a},"data-glyph":e,children:zb[e]})}i(z,"Glyph");var Dt=44,hn=36,Vb=12,$b=16,wd="#FFFFFF";function Id({image:e,onClose:t,returnFocusTo:r}){let n=N(),o=useMemo(()=>Wb(n),[n]),a=qe(e!==null,t,r);return e===null?null:jsxs("dialog",{ref:a.dialogRef,"aria-label":K(h.previewAttachment,{filename:e.filename}),onCancel:a.onCancel,onKeyDown:a.onKeyDown,style:o.lightbox,"data-ef-focus-ring-color":wd,children:[jsx("img",{src:e.uri,alt:e.filename,style:o.image}),jsx("button",{type:"button",onClick:t,"aria-label":h.closePreview,style:o.closeHit,children:jsx("span",{"aria-hidden":"true",style:o.closeDisc,children:jsx(z,{name:"x",size:18,color:wd})})})]})}i(Id,"AttachmentImageLightbox");function Wb(e){let t=e.radius;return {lightbox:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,margin:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",padding:0,border:0,backgroundColor:"#000000",display:"flex",alignItems:"center",justifyContent:"center"},image:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",objectFit:"contain"},closeHit:{position:"absolute",top:Vb-(Dt-hn)/2,right:$b-(Dt-hn)/2,boxSizing:"border-box",width:Dt,height:Dt,minWidth:Dt,minHeight:Dt,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},closeDisc:{boxSizing:"border-box",width:hn,height:hn,borderRadius:t.pill,backgroundColor:"rgba(0,0,0,0.45)",display:"inline-flex",alignItems:"center",justifyContent:"center"}}}i(Wb,"makeStyles");var Gb="file",qb="chat attachment upload: the file handle carries no bytes",Ei="chat attachment upload failed";function vn(e={}){let t=e.fetch??((r,n)=>fetch(r,n));return Object.freeze({postMultipart(r,n,o){let a=n.blob;if(a===void 0)return Promise.reject(new Error(qb));if(o.signal?.aborted===true)return Promise.reject(new Error(Ei));let s=new FormData;for(let[l,u]of Object.entries(r.upload_fields))s.append(l,u);return s.append(Gb,a,"image"),t(r.upload_url,{method:"POST",body:s,mode:"cors",credentials:"omit",...o.signal?{signal:o.signal}:{}}).then(l=>{if(!(l.status>=200&&l.status<300))return Promise.reject(new Error(Ei));o.onProgress?.(1);},()=>Promise.reject(new Error(Ei)))}})}i(vn,"createWebAttachmentTransport");function En(e){return Object.freeze({uri:URL.createObjectURL(e),mimeType:e.type,sizeBytes:e.size,name:e.name,blob:e})}i(En,"fileToAttachmentHandle");function gr(e){try{URL.revokeObjectURL(e);}catch{}}i(gr,"revokeObjectUrl");function Ci(e){return er(e)==="cat"?"cat":"dog"}i(Ci,"speciesOf");function Si(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(Si,"petAgeYears");function Od(e){let t=Si(e.ageYears),r=Ci(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(Od,"formatPetMeta");var Ad=Object.freeze([Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),Object.freeze({background:"#fbc558",foreground:"#10462e"}),Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function Yb(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return Ad[t%Ad.length]}i(Yb,"pickInitialsPalette");function Ri(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(Ri,"getInitial");function Cn(e){return {...Yb(e.petRef),initial:Ri(e.name)}}i(Cn,"petInitials");var Fd=Object.freeze({visitButton:"Talk to a vet"});var Sn=44,xi=44,Rn=48,Qb=18,Md=22,Zb="80vh";function Dd(e){let{open:t,pets:r,activePetRef:n,onClose:o,onSelect:a,onAddPet:s=null,returnFocusTo:l}=e,u=N(),d=useMemo(()=>Jb(u),[u]),c=qe(t,o,l);return t?jsxs("dialog",{ref:c.dialogRef,"aria-label":h.yourPets,onCancel:c.onCancel,onKeyDown:c.onKeyDown,style:d.sheet,children:[jsx("h2",{style:d.title,children:h.yourPets}),jsx("ul",{style:d.list,children:r.map(p=>{let f=p.petRef===n,m=p.name?.trim()||h.yourPet,y=Cn(p);return jsx("li",{children:jsxs("button",{type:"button","aria-current":f?"true":void 0,"aria-label":K(f?h.petCurrentlyActive:h.switchToPet,{name:m}),onClick:()=>a(p.petRef),style:{...d.row,...f?d.rowActive:null},children:[jsx("span",{style:d.ring,children:jsx("span",{style:{...d.disc,backgroundColor:y.background,color:y.foreground},children:y.initial})}),jsxs("span",{style:d.text,children:[jsx("span",{style:d.name,children:m}),jsx("span",{style:d.meta,children:`${f?h.activePrefix:""}${Od(p)}`})]}),f?jsx(z,{name:"check",size:Qb,color:u.color.brandInk,strokeWidth:2.5}):null]})},p.petRef)})}),s!==null?jsxs("button",{type:"button","aria-label":h.addAnotherPet,onClick:s,style:d.addRow,children:[jsx("span",{style:d.addDisc,children:"+"}),jsx("span",{style:d.addLabel,children:h.addAnotherPet})]}):null,jsx("button",{type:"button",onClick:o,style:d.close,children:h.close})]}):null}i(Dd,"PetSwitcherDialog");function Jb(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return {sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:Zb,overflowY:"auto",padding:`${r.lg+4}px ${r.lg+4}px ${r.xxl}px`,border:0,borderRadius:`${Md}px ${Md}px 0 0`,backgroundColor:t.surface,color:t.text.primary,display:"flex",flexDirection:"column",gap:r.md+2},title:{margin:0,...k(e,"bold"),fontSize:o.tierSizes.heading.heading,lineHeight:`${Math.round(o.tierSizes.heading.heading*1.22)}px`,color:t.brandInk},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:r.sm},row:{boxSizing:"border-box",width:"100%",minHeight:Sn,display:"flex",flexDirection:"row",alignItems:"center",gap:r.md,margin:0,padding:r.md,borderRadius:n.md,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surfaceCream,color:t.text.primary,textAlign:"left",cursor:"pointer",font:"inherit"},rowActive:{border:`1px solid ${t.brandInk}`,backgroundColor:t.brandSoft},ring:{boxSizing:"border-box",flexShrink:0,width:Rn,height:Rn,borderRadius:n.pill,border:`2px solid ${t.success}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:xi,height:xi,borderRadius:n.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...k(e,"bold"),fontSize:Math.round(xi*.42),lineHeight:1,textTransform:"uppercase"},text:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:2},name:{...k(e,"bold"),fontSize:o.size.body+1,lineHeight:`${o.size.body+4}px`,color:t.text.primary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},meta:{...k(e,"monoBold"),fontSize:o.tierSizes.compact.tiny,lineHeight:`${o.tierSizes.compact.tiny+2}px`,letterSpacing:.4,textTransform:"uppercase",color:t.text.muted},addRow:{boxSizing:"border-box",display:"flex",alignItems:"center",gap:r.sm,width:"100%",minHeight:Sn,padding:`${r.xs}px ${r.sm}px`,background:"none",border:"none",borderRadius:n.lg,cursor:"pointer",textAlign:"left"},addDisc:{boxSizing:"border-box",width:Rn,height:Rn,borderRadius:n.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",border:`2px dashed ${t.brandBorder}`,backgroundColor:t.surfaceCream,color:t.brandInk,fontSize:o.size.subtitle,lineHeight:1},addLabel:{...k(e,"bold"),fontSize:o.size.body,color:t.text.primary},close:{boxSizing:"border-box",alignSelf:"center",minHeight:Sn,minWidth:Sn,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${r.xl}px`,borderRadius:n.pill,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surface,color:t.text.primary,cursor:"pointer",...k(e,"medium"),fontSize:o.tierSizes.control.body}}}i(Jb,"makeStyles");var hr=35,jd=1.75,Ti=hr-jd*2,Ld=12.4,Nd=36,Ud=20,Hd=9,rv=1.5,at=44,Vd=28,nv=160;function $d(e){let{pets:t,activePet:r,unread:n,onOpenHistory:o,historyTriggerRef:a,onSelectPet:s,onAddPet:l=null,vetEntry:u=null}=e,{rail:d=false,historyOpen:c=false,onNewChat:p}=e,f=N(),m=useMemo(()=>av(f),[f]),y=jsxs("div",{style:m.historyControls,children:[p!==void 0?jsx("button",{type:"button",onClick:p,"aria-label":W.newChat,style:m.menuButton,children:jsx(z,{name:"squarePen",size:Ud,color:f.color.text.primary})}):null,jsx("button",{ref:a,type:"button",onClick:o,"aria-label":n?h.openMenuUnread:h.openMenu,"aria-expanded":c,style:m.menuButton,children:jsxs("span",{"aria-hidden":"true",style:m.menuDisc,children:[jsx(z,{name:"history",size:Ud,color:f.color.text.primary}),n?jsx("span",{style:m.unreadDot}):null]})})]});return jsxs("header",{style:m.bar,children:[d?null:y,jsx("div",{style:m.centre,children:jsx(ov,{logoUrl:f.meta.logoUrl,name:f.meta.displayName,styles:m})}),u!==null?jsx("button",{type:"button",onClick:u,style:m.vetEntry,children:Fd.visitButton}):null,jsx(iv,{pets:t,activePet:r,styles:m,onSelectPet:s,onAddPet:l}),d?y:null]})}i($d,"ChatHeader");function ov({logoUrl:e,name:t,styles:r}){let[n,o]=useState(null);return e===null||n===e?null:jsx("img",{src:e,alt:t,height:Vd,style:r.logo,decoding:"async",referrerPolicy:"no-referrer",onError:()=>o(e)})}i(ov,"BrandLogo");function iv({pets:e,activePet:t,styles:r,onSelectPet:n,onAddPet:o}){let[a,s]=useState(false),l=useRef(null),u=t?.name?.trim()||h.yourPet;return e.length<2&&o===null||t===null?jsx("div",{role:"img","aria-label":u,style:r.avatarSlot,children:jsx(zd,{pet:t,styles:r})}):jsxs("div",{style:r.avatarSlot,children:[jsxs("button",{ref:l,type:"button","aria-haspopup":"dialog","aria-expanded":a,"aria-label":K(h.switchActivePet,{name:u}),onClick:()=>s(true),style:r.avatarButton,children:[jsx(zd,{pet:t,styles:r}),jsx("span",{"aria-hidden":"true",style:r.addBadge,children:jsx("span",{style:r.addBadgeGlyph,children:"+"})})]}),jsx(Dd,{open:a,pets:e,activePetRef:t.petRef,returnFocusTo:l,onClose:()=>s(false),onSelect:d=>{s(false),n(d);},onAddPet:o===null?null:()=>{s(false),o();}})]})}i(iv,"PetAvatarSlot");function zd({pet:e,styles:t}){let r=e===null?null:Cn(e);return jsx("span",{style:t.ring,children:jsx("span",{style:{...t.disc,...r===null?t.discEmpty:{backgroundColor:r.background,color:r.foreground}},children:r===null?Ri(null):r.initial})})}i(zd,"AvatarRing");function av(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return {vetEntry:{boxSizing:"border-box",minHeight:44,padding:`0 ${r.md}px`,borderRadius:n.pill,backgroundColor:t.surfaceCream,border:`1px solid ${t.brandBorder}`,color:t.brandInk,cursor:"pointer",whiteSpace:"nowrap",...k(e,"bold"),fontSize:o.size.caption},bar:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,padding:`${r.sm+2}px ${r.lg}px`,backgroundColor:t.surfaceCream},menuButton:{boxSizing:"border-box",minWidth:at,minHeight:at,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer",color:t.text.primary},menuDisc:{position:"relative",boxSizing:"border-box",width:Nd,height:Nd,borderRadius:n.pill,display:"inline-flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4},historyControls:{display:"flex",flexDirection:"row",alignItems:"center",flexShrink:0},unreadDot:{position:"absolute",top:6,right:6,boxSizing:"border-box",width:Hd,height:Hd,borderRadius:n.pill,backgroundColor:t.danger,border:`${rv}px solid ${t.surfaceCream}`},centre:{flex:"1 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"center"},logo:{display:"block",height:Vd,width:"auto",maxWidth:nv,objectFit:"contain"},avatarSlot:{position:"relative",minWidth:at,minHeight:at,display:"inline-flex",alignItems:"center",justifyContent:"center"},avatarButton:{position:"relative",boxSizing:"border-box",minWidth:at,minHeight:at,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer"},ring:{boxSizing:"border-box",width:hr,height:hr,borderRadius:n.pill,border:`${jd}px solid ${t.success}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:Ti,height:Ti,borderRadius:n.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...k(e,"bold"),fontSize:Math.round(Ti*.42),lineHeight:1,textTransform:"uppercase"},discEmpty:{backgroundColor:t.surfaceSubtle,color:t.text.muted},addBadge:{position:"absolute",bottom:(at-hr)/2,right:(at-hr)/2,boxSizing:"border-box",width:Ld,height:Ld,borderRadius:n.pill,border:`0.5px solid ${t.success}`,backgroundColor:t.surface,display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},addBadgeGlyph:{...k(e,"bold"),fontSize:o.tierSizes.badge.small,lineHeight:1,color:t.brandInk}}}i(av,"makeStyles");var Wd=Object.freeze({kind:"static"}),Kd=createContext(Wd);function Gd(){return useContext(Kd)}i(Gd,"useCitationLinks");function cv(e){return useMemo(()=>e===void 0?Wd:Object.freeze({kind:"host",open:i(t=>{se(e,t,"citation");},"open")}),[e])}i(cv,"useCitationLinkMode");function qd({onOpenUrl:e,children:t}){let r=cv(e);return createElement(Kd.Provider,{value:r},t)}i(qd,"CitationLinksScope");function pv(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(pv,"slotBox");function Yd(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(Yd,"ownGroundSlot");function Ce(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Ce,"slotText");function Se(e,t){let r=pv(e,t),n={};return r.backgroundColor!==void 0&&(n.backgroundColor=r.backgroundColor),r.borderColor!==void 0&&(n.border=`${r.borderWidth??1}px solid ${r.borderColor}`),r.borderRadius!==void 0&&(n.borderRadius=r.borderRadius),n}i(Se,"slotBoxCss");var Xd=2;function ki(e){return typeof e!="number"||!Number.isInteger(e)?Xd:e<1?1:e>6?6:e}i(ki,"headingLevel");function mv(e){return e>=6?6:e+1}i(mv,"nextHeadingLevel");function Qd(e){return `h${String(e)}`}i(Qd,"headingTag");var yv=mv(Xd);createContext(yv);var vr=320,Cv=480,Sv=vr+Cv,Rv=1024,_i=768,Zd="72ch",wi=Object.freeze({rail:false,desktop:false}),xv=Object.freeze({rail:true,desktop:false}),Tv=Object.freeze({rail:true,desktop:true});function kv(e){return e===null||e<Sv?wi:e>=Rv?Tv:xv}i(kv,"layoutFor");var Tn=createContext({layout:wi,report:i(()=>{},"report"),headingLevel:ki(void 0)});function kn(){return useContext(Tn).layout}i(kn,"useChatLayout");function Jd(){return useContext(Tn).headingLevel}i(Jd,"useChatHeadingLevel");function ec({children:e,headingLevel:t}){let[r,n]=useState(wi),o=ki(t),a=useMemo(()=>({layout:r,report:n,headingLevel:o}),[r,o]);return createElement(Tn.Provider,{value:a},e)}i(ec,"ChatLayoutScope");function tc(e){let{report:t}=useContext(Tn);useEffect(()=>{let r=e.current;if(r===null||typeof ResizeObserver>"u")return;let n=i(()=>{let a=r.getBoundingClientRect().width;t(kv(a>0?Math.round(a):null));},"read");n();let o=new ResizeObserver(n);return o.observe(r),()=>o.disconnect()},[e,t]);}i(tc,"useMeasuredLayout");var Ii=Object.freeze({standard:vt.standard,emphasized:vt.emphasized,exit:vt.exit,outQuad:Object.freeze([.25,.46,.45,.94])}),Ai=ir,rc=Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,reduced:false}),Pv=Object.freeze({...rc,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,reduced:true});function nc(e){return e.motion.reducedMotion?Pv:rc}i(nc,"chatMotion");function oc(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(oc,"followUpDelayMs");function ic(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}i(ic,"nextRevealLength");function Q(){let e=N();return useMemo(()=>nc(e),[e])}i(Q,"useChatMotion");function Lt(e){return e!==null&&typeof e.animate=="function"}i(Lt,"canAnimate");function Re(e,t){if(!Lt(e)||t.durationMs<=0)return null;let r=[t.fromTranslateX!==void 0?`translateX(${t.fromTranslateX})`:"",t.fromTranslateY!==void 0&&t.fromTranslateY!==0?`translateY(${t.fromTranslateY}px)`:""].filter(a=>a.length>0).join(" "),n={...t.fromOpacity!==void 0?{opacity:t.fromOpacity}:{},...r.length>0?{transform:r}:{}},o={...t.fromOpacity!==void 0?{opacity:1}:{},...r.length>0?{transform:"none"}:{}};try{return e.animate([n,o],{duration:t.durationMs,delay:t.delayMs??0,easing:Ai(Ii.standard),fill:"backwards"})}catch{return null}}i(Re,"animateEnter");function Oi(e,t,r){if(!Lt(e)||t<=0)return Promise.resolve();try{let n=e.animate([{opacity:1,transform:"none"},{opacity:0,...r!==void 0?{transform:`translateX(${r})`}:{}}],{duration:t,easing:Ai(Ii.exit),fill:"forwards"});return new Promise(o=>{n.onfinish=()=>o(),n.oncancel=()=>o();})}catch{return Promise.resolve()}}i(Oi,"animateExit");function Fi(e,t){let[r,n]=useState(e),o=r&&!e;return useEffect(()=>{if(e){n(true);return}if(!r)return;if(t<=0){n(false);return}let a=setTimeout(()=>n(false),t);return ()=>clearTimeout(a)},[e,t,r]),{present:r,exiting:o}}i(Fi,"usePresence");function lc(e,t,r){let[n,o]=useState(t&&!r.reduced?0:e.length),a=useRef({text:e,active:t});return a.current={text:e,active:t},useEffect(()=>{if(!t||r.reduced||r.revealTickMs<=0){o(a.current.text.length);return}let s=setInterval(()=>{o(l=>ic(r,l,a.current.text.length));},r.revealTickMs);return ()=>clearInterval(s)},[t,r]),t&&!r.reduced?e.slice(0,Math.min(n,e.length)):e}i(lc,"useRevealedText");var Le=44,Fv="85%",Mi={y:16,blur:48,alpha:.18},Mv=.32,Dv=36,uc=8,Di=1.5,Lv=.08,Nv="50%";function cc({chat:e,history:t,mode:r,returnFocusTo:n}){let o=N(),a=r==="rail"?"brand":"surface",s=useMemo(()=>zv(o,a),[o,a]),l=Q(),u=qe(r==="dialog"&&t.open,t.close,n),d=useRef(null),c=t.open,p=l.drawerMs;if(useEffect(()=>{if(!c||r!=="dialog")return;let m=Re(d.current,{durationMs:p,fromOpacity:0,fromTranslateX:"-100%"});return ()=>m?.cancel()},[c,r,p]),!c)return null;let f=jsx(Uv,{chat:e,history:t,styles:s,theme:o,ink:a==="brand"?o.color.onPrimary:o.color.brandInk});return r==="rail"?jsx("aside",{ref:m=>{d.current=m;},"aria-label":W.heading,"data-ef-focus-ring-color":o.color.onPrimary,style:s.rail,children:f}):jsx("div",{style:s.scrim,onClick:t.close,children:jsx("div",{ref:m=>{u.dialogRef.current=m,d.current=m;},role:"dialog","aria-modal":"true","aria-label":W.heading,tabIndex:-1,onKeyDown:u.onKeyDown,onClick:m=>m.stopPropagation(),style:s.overlay,children:f})})}i(cc,"HistoryDrawer");function Uv({chat:e,history:t,styles:r,theme:n,ink:o}){let{filtered:a,loading:s,loadingMore:l,error:u,cursor:d,emptyKind:c,searching:p,query:f,setQuery:m}=t,y=!s&&u===null,[S,g]=useState(false);return jsxs(Fragment,{children:[jsxs("div",{style:r.toolbar,children:[jsxs("label",{style:{...r.searchPill,...S?di(o):null},children:[jsx(z,{name:"search",size:16,color:n.color.text.muted}),jsx("input",{type:"search",value:f,onChange:T=>m(T.target.value),onFocus:()=>g(true),onBlur:()=>g(false),"data-ef-focus-ring":"self","aria-label":W.search,placeholder:W.search,autoComplete:"off",style:r.searchInput})]}),jsx("button",{type:"button",onClick:t.newConversation,"aria-label":W.newChat,style:r.roundControl,children:jsx(z,{name:"squarePen",size:16,color:n.color.brandInk})}),jsx("button",{type:"button",onClick:t.close,"aria-label":W.closeA11y,style:r.roundControl,children:jsx(z,{name:"x",size:16,color:n.color.brandInk})})]}),jsx("p",{style:r.heading,children:W.heading}),s?jsx("p",{role:"status",style:r.state,children:W.loading}):null,u!==null?jsxs("div",{style:r.stateBlock,children:[jsx("p",{role:"alert",style:r.state,children:W.loadFailed}),jsx("button",{type:"button",onClick:()=>{t.load();},"aria-label":W.retryA11y,style:r.retryControl,children:W.retry})]}):null,y&&a.length===0?jsxs("div",{style:r.stateBlock,children:[jsx("p",{style:r.state,children:c==="noMatch"?W.noMatch:W.empty}),jsx("p",{style:r.stateBody,children:c==="noMatch"?W.noMatchBody:W.emptyBody})]}):null,y&&a.length>0?jsx(Hv,{rows:a,activeId:e.conversationId,onSelect:T=>{t.resume(T);},styles:r,canLoadMore:d!==null&&!p&&!l,onLoadMore:t.loadMore}):null,l?jsx("p",{role:"status",style:r.state,children:W.loadingMore}):null]})}i(Uv,"PanelBody");function Hv({rows:e,activeId:t,onSelect:r,styles:n,canLoadMore:o,onLoadMore:a}){let s=useRef(null),l=typeof IntersectionObserver=="function",u=useRef(a);u.current=a;let d=useCallback(c=>{s.current=c;},[]);return useEffect(()=>{let c=s.current;if(!l||!o||c===null)return;let p=new IntersectionObserver(f=>{f.some(m=>m.isIntersecting)&&u.current();},{rootMargin:Nv});return p.observe(c),()=>p.disconnect()},[l,o,e.length]),jsxs("ul",{style:n.list,children:[e.map(c=>{let p=c.unreadCount!==null&&c.unreadCount>0,f=c.id===t;return jsx("li",{children:jsxs("button",{type:"button","aria-label":zu(c),"aria-current":f?"true":void 0,onClick:()=>r(c.id),style:{...n.row,...f?n.rowActive:null},children:[jsx("span",{style:{...n.rowTitle,...p?n.rowTitleUnread:null},children:sn(c.title)}),p?jsx("span",{"aria-hidden":"true",style:n.unreadDot}):null]})},c.id)}),o?jsx("li",{ref:d,style:n.sentinel,children:l?null:jsx("button",{type:"button",onClick:a,style:n.textControl,children:W.more})}):null]})}i(Hv,"RowList");function zv(e,t){let r=e.color,n=e.space,o=e.radius,a=e.type,s=t==="brand",l=s?r.onPrimary:r.text.primary,u={boxSizing:"border-box",display:"flex",flexDirection:"column",gap:n.md,padding:`${n.lg}px ${n.lg}px ${n.lg}px`,backgroundColor:s?r.brand:r.surface,color:l,overflowY:"auto"},d={boxSizing:"border-box",minHeight:Le,minWidth:Le,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${n.md}px`,borderRadius:o.pill,border:`1px solid ${l}`,background:"transparent",color:l,cursor:"pointer",...k(e,"medium"),fontSize:a.tierSizes.control.body};return {rail:{...u,flex:`0 0 ${vr}px`,width:vr,minHeight:0,borderRadius:`${o.lg}px 0 0 ${o.lg}px`},scrim:{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden",zIndex:1,backgroundColor:$e(r.shadow,Mv)??"transparent"},overlay:{...u,position:"absolute",top:0,bottom:0,left:0,margin:0,width:vr,maxWidth:Fv,border:0,borderRadius:0,boxShadow:`0 ${Mi.y}px ${Mi.blur}px ${$e(r.brand,Mi.alpha)??"transparent"}`,outline:"none"},toolbar:{display:"flex",flexDirection:"row",alignItems:"center",gap:n.sm},searchPill:{flex:"1 1 auto",minWidth:0,minHeight:Le,display:"flex",flexDirection:"row",alignItems:"center",gap:n.sm,padding:`0 ${n.md+2}px`,borderRadius:o.pill,boxSizing:"border-box",...s?{backgroundColor:r.surface,border:`1px solid ${r.onPrimary}`}:{backgroundColor:r.surfaceCream,border:`1px solid ${r.brandBorderStrong}`},color:r.text.primary},searchInput:{boxSizing:"border-box",flex:"1 1 auto",minWidth:0,minHeight:Le,margin:0,padding:0,border:0,outline:"none",background:"transparent",...k(e,"regular"),fontSize:a.size.bodyTight,lineHeight:`${a.size.bodyTight+3}px`,color:r.text.primary},roundControl:{boxSizing:"border-box",flexShrink:0,width:Le,height:Le,minWidth:Le,minHeight:Le,margin:0,padding:(Le-Dv)/2,border:0,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",backgroundClip:"content-box",backgroundColor:s?r.surface:r.brandSoft,borderRadius:o.pill},heading:{margin:0,...k(e,"bold"),fontSize:a.tierSizes.heading.body,lineHeight:`${a.tierSizes.heading.body+3}px`,color:l},state:{margin:0,...k(e,"regular"),fontSize:a.size.body,lineHeight:`${a.size.body+4}px`,color:l},stateBody:{margin:0,...k(e,"regular"),fontSize:a.size.caption,lineHeight:`${a.size.caption+4}px`,color:l,opacity:.8},stateBlock:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:n.sm},textControl:d,retryControl:{...d,...Se(e.slots.primaryButton),...Ce(e.slots.primaryButton)},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},row:{boxSizing:"border-box",width:"100%",minHeight:Le,display:"flex",flexDirection:"row",alignItems:"center",gap:n.sm,margin:0,padding:`${n.md}px ${n.xs}px`,border:0,borderRadius:o.sm,background:"transparent",color:l,textAlign:"left",cursor:"pointer",font:"inherit"},rowActive:{backgroundColor:$e(l,Lv)??"transparent"},rowTitle:{flex:"1 1 auto",minWidth:0,...k(e,"regular"),fontSize:a.size.body,lineHeight:`${a.size.body+4}px`,color:l,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},rowTitleUnread:k(e,"bold"),unreadDot:{boxSizing:"border-box",flexShrink:0,width:uc+Di*2,height:uc+Di*2,borderRadius:o.pill,backgroundColor:r.danger,border:`${Di}px solid ${s?r.brand:r.surface}`},sentinel:{minHeight:1,display:"flex",justifyContent:"center",padding:`${n.xs}px 0`}}}i(zv,"makeStyles");var Ye=44,Nt=22,Vv=12,$v=20,Wv=13,Kv=16,Gv=.75;function fc({surface:e,vetEntry:t,renderVetAction:r,onFindVet:n}){let o=N(),a=useMemo(()=>Qv(o),[o]),s=Q(),l=Fi(e.showBanner,s.bannerOutMs),u=Fi(e.showCompactIcon,s.iconOutMs);return jsxs(Fragment,{children:[l.present&&e.tier!==null&&e.source!==null?jsx(qv,{surface:e,exiting:l.exiting,styles:a,action:e.showVetAction?jsx(Yv,{tier:e.tier,styles:a,vetEntry:t,renderVetAction:r,onFindVet:n}):null},e.signature??"banner"):null,u.present?jsx(Xv,{exiting:u.exiting,onExpand:e.expand,styles:a}):null]})}i(fc,"UrgencyBanner");function qv({surface:e,exiting:t,styles:r,action:n}){let o=useRef(null),a=Q();useEffect(()=>{let d=Re(o.current,{durationMs:a.bannerInMs,fromOpacity:0});return ()=>d?.cancel()},[a.bannerInMs]),useEffect(()=>{t&&Oi(o.current,a.bannerOutMs);},[t,a.bannerOutMs]);let s=e.tier,l=e.source;if(s===null||l===null)return null;let u=s.level==="emergency"||s.level==="schedule_soon";return jsxs("div",{ref:o,role:u?"alert":"status","aria-hidden":t?true:void 0,style:{...r.banner,borderColor:s.borderColor,backgroundColor:s.backgroundColor},children:[jsx("p",{style:{...r.label,color:s.textColor},children:s.label}),l.reason?jsx("p",{style:{...r.reason,color:s.reasonColor},children:l.reason}):null,n,jsx("button",{type:"button",onClick:e.dismiss,"aria-label":e.dismissLabel??h.close,style:r.dismissHit,children:jsx("span",{"aria-hidden":"true",style:r.dismissDisc,children:jsx(z,{name:"x",size:Vv,color:s.textColor,strokeWidth:2.25})})})]})}i(qv,"Banner");function Yv({tier:e,styles:t,vetEntry:r,renderVetAction:n,onFindVet:o}){let a=N(),s=e.level,l=r.available?r.open:o!==void 0?()=>{se(o,s);}:null,u=Yd(a.slots.vetVisitButton),d=u?.textColor??e.textColor,c=l===null?null:jsxs("button",{type:"button",onClick:l,"aria-label":h.findVetA11y,style:{...t.pill,borderColor:e.borderColor,backgroundColor:e.pillColor,color:e.textColor,...Se(u),...Ce(u)},children:[jsx(z,{name:"mapPin",size:Wv,color:d}),jsx("span",{children:h.findVet})]});return n!==void 0?jsx("div",{style:t.actionRow,children:jsx(xt,{render:()=>n(s),fallback:c,resetKey:s})}):c===null?null:jsx("div",{style:t.actionRow,children:c})}i(Yv,"VetAction");function Xv({exiting:e,onExpand:t,styles:r}){let n=useRef(null),o=Q(),a=N();return useEffect(()=>{let s=Re(n.current,{durationMs:o.iconInMs,fromOpacity:0});return ()=>s?.cancel()},[o.iconInMs]),useEffect(()=>{e&&Oi(n.current,o.iconOutMs);},[e,o.iconOutMs]),jsx("div",{ref:n,"aria-hidden":e?true:void 0,style:r.iconRow,children:jsx("button",{type:"button",onClick:t,"aria-label":h.showLatestVetAlert,style:r.iconButton,children:jsx(z,{name:"info",size:$v,color:a.color.text.muted})})})}i(Xv,"CompactIcon");function Qv(e){let t=e.space,r=e.radius,n=e.type,o=n.tierSizes.compact,a=n.tierSizes.control;return {banner:{position:"relative",boxSizing:"border-box",margin:`0 ${t.lg}px ${t.xs}px`,padding:`${t.sm}px ${t.md+2}px`,borderRadius:Kv,borderStyle:"solid",borderWidth:Gv,display:"flex",flexDirection:"column",gap:2},label:{margin:0,paddingRight:Nt,...k(e,"monoBold"),fontSize:o.caption,lineHeight:`${o.caption+3}px`},reason:{margin:0,paddingRight:Nt,...k(e,"regular"),fontSize:n.size.caption,lineHeight:`${n.size.caption+6}px`,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},actionRow:{display:"flex",flexDirection:"row",marginTop:t.xs},pill:{boxSizing:"border-box",minHeight:Ye,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:t.xs+2,margin:0,padding:`${t.xs+1}px ${t.sm+2}px`,borderRadius:r.pill,borderStyle:"solid",borderWidth:1,cursor:"pointer",...k(e,"monoBold"),fontSize:a.caption,lineHeight:`${a.caption+3}px`},dismissHit:{position:"absolute",top:6-(Ye-Nt)/2,right:6-(Ye-Nt)/2,boxSizing:"border-box",width:Ye,height:Ye,minWidth:Ye,minHeight:Ye,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},dismissDisc:{boxSizing:"border-box",width:Nt,height:Nt,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center"},iconRow:{display:"flex",flexDirection:"row",justifyContent:"flex-end",padding:`2px ${t.lg}px ${t.xs}px`},iconButton:{boxSizing:"border-box",minWidth:Ye,minHeight:Ye,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}}}i(Qv,"makeStyles");var Rc=300,mc=120,_n=44,ji=120,eE="12%",tE=480,rE=18,nE="min(75%, 34rem)",oE="lg",iE=15,aE=22,sE=17,lE=28,yc="-0.005em";var gc=1,Ui={y:2,blur:8,alpha:.04},uE=.6,dE="md",cE="xs",hc="lg",pE="xl",fE=60,Hi=1,mE="xs",yE=14,zi={y:1,blur:2,alpha:.08},gE=52,bc=16,vc=26,Ec="-0.01em",Bi=36,xc=24,Tc=22,hE=.4,bE=.5;var Cc=24,vE=3,kc=900,Pc=20,EE=14,CE="0.09em",SE=22,_c=24;function Ne(e,t){return Math.round(e*t*10)/10}i(Ne,"scaledPx");function fe(){let e=N(),{desktop:t}=kn(),r=useMemo(()=>RE(e,t),[e,t]);return {theme:e,styles:r}}i(fe,"useChatTheme");function Sc(e){return `max(${e}px, calc((100% - ${_i}px) / 2))`}i(Sc,"columnInset");function RE(e,t){let r=e.color,n=e.space,o=e.radius,a=e.type,s=e.slots,l=Xo(a.family),u=n[oE],d=t?sE:iE,c=t?lE:aE,p=a.tierSizes.control,f=a.tierSizes.compact,m={boxSizing:"border-box",minHeight:_n,minWidth:_n,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,border:0,cursor:"pointer",...k(e,"medium"),fontSize:p.body,lineHeight:`${Math.round(p.body*a.lineHeight.normal)}px`};return {container:{boxSizing:"border-box",position:"relative",display:"flex",flexDirection:"column",minHeight:mc,height:"100%",backgroundColor:r.chatGround,color:r.text.primary,fontFamily:l},split:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"row"},main:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:mc,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:n.xl},spinner:{boxSizing:"border-box",width:Cc,height:Cc,borderRadius:o.pill,border:`${vE}px solid ${r.brandSofter}`,borderTopColor:r.brandInk},emptyScroller:{boxSizing:"border-box",flex:"1 1 auto",minHeight:0,overflowY:"auto"},emptyContent:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"flex-start",minHeight:tE,paddingTop:eE,paddingLeft:n.lg,paddingRight:n.lg,paddingBottom:n.lg,gap:rE},errorText:{margin:`0 0 ${n.md}px`,...k(e,"regular"),fontSize:a.size.subtitle,lineHeight:`${Math.round(a.size.subtitle*a.lineHeight.snug)}px`,color:r.danger,textAlign:"center"},retryButton:{...m,padding:`${n.sm}px ${n.xl}px`,borderRadius:o.pill,backgroundColor:r.brand,color:r.onPrimary,...Se(s.primaryButton),...Ce(s.primaryButton)},setupNotice:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.sm,padding:`${n.sm}px ${n.lg}px`,backgroundColor:r.surfaceCream},setupNoticeText:{...k(e,"regular"),fontSize:a.size.caption,color:r.danger},setupNoticeAction:{...m,padding:0,background:"none",border:"none",color:r.brandInk,fontSize:a.size.caption,minHeight:_n},turnNotice:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"flex-start",gap:n.xs,padding:n.md,borderRadius:o.lg,backgroundColor:r.surfaceCream,border:`1px solid ${r.brandBorder}`},turnNoticeError:{border:`1px solid ${r.danger}`},turnNoticeTitle:{...k(e,"bold"),margin:0,fontSize:a.size.body,color:r.text.primary},turnNoticeTitleError:{color:r.danger},reconnectingCaption:{...k(e,"medium"),margin:0,fontSize:a.size.caption,color:r.text.secondary,textTransform:"uppercase",letterSpacing:"0.5px"},turnNoticeBody:{...k(e,"regular"),margin:0,fontSize:a.size.caption,color:r.text.secondary},turnNoticeAction:{...m,padding:0,background:"none",border:"none",color:r.brandInk,fontSize:a.size.body,minHeight:_n},earlierButton:{...m,alignSelf:"center",padding:`0 ${n.md+n.xs/2}px`,backgroundColor:"transparent",color:r.linkInk,...k(e,"monoBold"),fontSize:f.tiny,lineHeight:`${Math.round(f.tiny*a.lineHeight.snug)}px`,letterSpacing:bE,textTransform:"uppercase"},list:{boxSizing:"border-box",flex:"1 1 auto",minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column",gap:n[hc],paddingTop:n.lg,paddingBottom:n.lg,paddingLeft:Sc(n.lg),paddingRight:Sc(n.lg)},messageList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:n[hc]},row:{display:"flex",flexDirection:"column"},rowUser:{alignItems:"flex-end"},rowAssistant:{alignItems:"flex-start"},bubble:{boxSizing:"border-box",maxWidth:nE,paddingTop:u,paddingBottom:u,paddingLeft:u,paddingRight:u,borderRadius:o[dE],position:"relative"},bubbleUser:{backgroundColor:r.bubbleUser,borderBottomRightRadius:o[cE],boxShadow:`0 ${Ui.y}px ${Ui.blur}px ${$e(r.brand,Ui.alpha)??r.brandSoft}`,...Se(s.userBubble,gc)},bubbleAssistant:{...s.assistantBubble?.backgroundColor===void 0?{paddingTop:0,paddingBottom:0,paddingLeft:0,paddingRight:n[pE],maxWidth:`min(100%, ${Zd})`}:{},...Se(s.assistantBubble,gc)},bubblePending:{opacity:uE},bubbleTextUser:{margin:0,...k(e,"medium"),color:r.onPrimary,fontSize:Ne(d,a.scale),lineHeight:`${Ne(c,a.scale)}px`,letterSpacing:yc,whiteSpace:"pre-wrap",overflowWrap:"anywhere",...Ce(s.userBubble)},bubbleTextAssistant:{margin:0,...k(e,"medium"),color:r.text.primary,fontSize:Ne(d,a.scale),lineHeight:`${Ne(c,a.scale)}px`,letterSpacing:yc,whiteSpace:"pre-wrap",overflowWrap:"anywhere",...Ce(s.assistantBubble)},bubbleBold:k(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:k(e,"mono"),followUps:{boxSizing:"border-box",marginTop:n.sm},followUpsLabel:{margin:`0 0 ${n.xs}px`,...k(e,"monoBold"),color:r.text.secondary,fontSize:f.tiny,lineHeight:`${EE}px`,letterSpacing:CE,textTransform:"uppercase"},followUpList:{listStyle:"none",margin:0,padding:0},followUpRow:{...m,width:"100%",justifyContent:"flex-start",textAlign:"left",padding:`${n.sm}px ${n.md}px ${n.sm}px 0`,background:"transparent",color:r.text.primary,...k(e,"regular"),fontSize:a.size.body,lineHeight:`${Ne(SE,a.scale)}px`,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},followUpDivider:{borderTop:`1px solid ${r.brandBorder}`},composerBlock:{display:"flex",flexDirection:"column"},composerError:{margin:`${n.xs}px ${n.md}px 0`,...k(e,"regular"),fontSize:a.size.caption,lineHeight:`${Math.round(a.size.caption*a.lineHeight.normal)}px`,color:r.danger},composer:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",gap:yE,minHeight:fE,width:`calc(100% - ${n.md*2}px)`,maxWidth:_i,margin:`${n.xs}px auto ${n.sm}px`,padding:n[mE],backgroundColor:r.chatGround,border:`${Hi}px solid ${r.composerBorder}`,borderRadius:o.pill,boxShadow:`0 ${zi.y}px ${zi.blur}px ${$e(r.brand,zi.alpha)??r.brandSoft}`,...Se(s.composerInput,Hi)},composerFocused:{border:`${Hi}px solid ${s.composerInput?.borderColor??r.brandInk}`,outline:`${mr}px solid ${r.brandInk}`,outlineOffset:mr},inputWrap:{position:"relative",flex:"1 1 auto",minWidth:0,minHeight:Ne(gE,a.scale),display:"flex",alignItems:"center"},placeholder:{position:"absolute",top:"50%",left:0,right:0,transform:"translateY(-50%)",pointerEvents:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...k(e,"regular"),fontSize:Ne(bc,a.scale),lineHeight:`${Ne(vc,a.scale)}px`,letterSpacing:Ec,color:r.text.placeholder,...Ce(s.composerInput)},input:{boxSizing:"border-box",flex:"1 1 auto",width:"100%",maxHeight:ji,margin:0,padding:0,border:0,outline:"none",resize:"none",background:"transparent",...k(e,"regular"),fontSize:Ne(bc,a.scale),lineHeight:`${Ne(vc,a.scale)}px`,letterSpacing:Ec,color:r.text.primary,...Ce(s.composerInput)},iconControl:{...m,flexShrink:0,padding:0,borderRadius:o.pill,background:"transparent",color:r.brandInk},actionButton:{...m,flexShrink:0,padding:0,backgroundColor:"transparent"},sendDisc:{boxSizing:"border-box",width:Bi,height:Bi,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:Bi/2,...Se(s.sendButton)},actionButtonDisabled:{opacity:hE,cursor:"not-allowed"},poweredBy:{margin:0,padding:`0 0 ${n.xs}px`,...k(e,"regular"),color:r.text.muted,fontSize:f.micro,lineHeight:`${Math.round(f.micro*a.lineHeight.normal)}px`,textAlign:"center"}}}i(RE,"makeStyles");var xE=Object.freeze({kind:"live"}),TE=Object.freeze({kind:"folded"});function wc(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=lo(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(wc,"askOf");function Ic(e){let t=new Map,r=new Map;for(let o of e){let a=wc(o);if(a===null)continue;let s=r.get(a.caseId);(s===void 0||a.dueDay>=s.dueDay)&&r.set(a.caseId,{messageId:o.id,dueDay:a.dueDay});}if(r.size===0)return t;let n=null;for(let o of e){let a=wc(o);if(a===null){n=null;continue}if(r.get(a.caseId)?.messageId===o.id){t.set(o.id,xE),n=null;continue}if(n!==null&&n.caseId===a.caseId){n.days.push(a.dueDay),t.set(o.id,TE);continue}let s=[a.dueDay];n={id:o.id,caseId:a.caseId,days:s},t.set(o.id,{kind:"past",runDueDays:s});}return t}i(Ic,"placeCheckins");function Ac(e){let t=new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}i(Ac,"liveCheckinIds");var Ut=44,Ht=56,Oc=12,wn=22,Fc=18,PE=2,_E=900,Mc=220,wE=14,Dc=100,IE=10,AE=6,OE=.45,FE="rgba(7,193,104,0.55)",ME="rgba(185,28,28,0.55)",Uc=Object.freeze([]);function Hc({attachments:e,onRetry:t,onRemove:r,onPreview:n}){let o=N(),a=useMemo(()=>Bc(o),[o]);return e.length===0?null:jsx("ul",{style:a.tray,children:e.map(s=>jsx("li",{style:a.cardSlot,children:jsx(DE,{row:s,styles:a,theme:o,onRetry:t,onRemove:r,onPreview:n})},s.id))})}i(Hc,"AttachmentTray");function DE({row:e,styles:t,theme:r,onRetry:n,onRemove:o,onPreview:a}){let s=Q(),l=useRef(null),[u,d]=useState(false),c=useRef(e.status==="uploading");useEffect(()=>{if(e.status==="uploaded"&&c.current){d(true);let f=setTimeout(()=>d(false),s.uploadFlashMs);return c.current=false,()=>clearTimeout(f)}c.current=e.status==="uploading";},[e.status,s.uploadFlashMs]);let p={uri:e.previewUri,filename:e.filename};return jsxs("div",{style:t.card,children:[jsx("button",{ref:l,type:"button","aria-label":K(h.previewAttachment,{filename:e.filename}),onClick:()=>a(p,l.current),style:t.previewButton,children:jsx("img",{src:e.previewUri,alt:"",style:t.thumb})}),e.status==="uploading"?jsx("div",{role:"status","aria-busy":"true","aria-label":K(h.previewAttachment,{filename:e.filename}),style:{...t.wash,backgroundColor:$e(r.color.brandInk,OE)??r.color.brandSofter},children:jsx(LE,{styles:t})}):null,e.status==="uploaded"&&u?jsx("div",{"aria-hidden":"true",style:{...t.wash,backgroundColor:FE}}):null,e.status==="failed"?jsx("button",{type:"button","aria-label":K(h.retryUpload,{filename:e.filename}),onClick:()=>n(e.id),style:{...t.wash,...t.retry,backgroundColor:ME},children:jsx(z,{name:"upload",size:18,color:"#FFFFFF"})}):null,jsx("button",{type:"button","aria-label":K(h.removeAttachment,{filename:e.filename}),onClick:()=>o(e.id),style:t.removeHit,children:jsx("span",{"aria-hidden":"true",style:t.removeDisc,children:jsx(z,{name:"x",size:12,color:r.color.surface,strokeWidth:2.5})})})]})}i(DE,"TrayCard");function LE({styles:e}){let t=Q(),r=useRef(null);return useEffect(()=>{let n=r.current;if(t.reduced||!Lt(n))return;let o=n.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:_E,iterations:1/0,easing:"linear"});return ()=>o.cancel()},[t.reduced]),jsx("span",{ref:r,"aria-hidden":"true",style:e.spinner})}i(LE,"Spinner");function zc({images:e,onPreview:t}){let r=N(),n=useMemo(()=>Bc(r),[r]);if(e.length===0)return null;let o=e.length===1;return jsx("ul",{style:o?n.singleList:n.gridList,children:e.map((a,s)=>jsx("li",{children:jsx(NE,{image:a,style:o?n.singleImage:n.gridImage,onPreview:t})},`${a.uri}-${s}`))})}i(zc,"MessageAttachments");function NE({image:e,style:t,onPreview:r}){let n=useRef(null);return jsx("button",{ref:n,type:"button","aria-label":K(h.attachedImage,{filename:e.filename}),onClick:()=>r(e,n.current),style:t,children:jsx("img",{src:e.uri,alt:"",style:{display:"block",width:"100%",height:"100%",objectFit:"cover"}})})}i(NE,"ImageButton");function Bc(e){let t=e.color,r=e.space,n=e.radius,o={boxSizing:"border-box",display:"block",margin:0,padding:0,border:0,overflow:"hidden",cursor:"pointer",backgroundColor:t.surfaceSubtle};return {tray:{listStyle:"none",margin:`0 ${r.md}px`,padding:`${r.xs}px 0`,display:"flex",flexDirection:"row",flexWrap:"wrap",gap:r.sm},cardSlot:{flex:"0 0 auto"},card:{position:"relative",boxSizing:"border-box",width:Ht,height:Ht},previewButton:{...o,width:Ht,height:Ht,borderRadius:Oc,border:`1px solid ${t.brandBorder}`},thumb:{display:"block",width:"100%",height:"100%",objectFit:"cover"},wash:{position:"absolute",top:0,right:0,bottom:0,left:0,borderRadius:Oc,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},retry:{pointerEvents:"auto",margin:0,padding:0,border:0,cursor:"pointer",minWidth:Ht,minHeight:Ht},spinner:{boxSizing:"border-box",display:"block",width:Fc,height:Fc,borderRadius:n.pill,border:`${PE}px solid rgba(255,255,255,0.45)`,borderTopColor:"#FFFFFF"},removeHit:{position:"absolute",top:4-(Ut-wn)/2,right:4-(Ut-wn)/2,boxSizing:"border-box",width:Ut,height:Ut,minWidth:Ut,minHeight:Ut,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},removeDisc:{boxSizing:"border-box",width:wn,height:wn,borderRadius:n.pill,backgroundColor:"rgba(0,0,0,0.78)",border:`1.5px solid ${t.surface}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},singleList:{listStyle:"none",margin:`0 0 ${r.sm}px`,padding:0},gridList:{listStyle:"none",margin:`0 0 ${r.sm}px`,padding:0,display:"flex",flexWrap:"wrap",gap:AE},singleImage:{...o,width:Mc,height:Mc,maxWidth:"100%",borderRadius:wE},gridImage:{...o,width:Dc,height:Dc,borderRadius:IE}}}i(Bc,"makeStyles");var zt=Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" \xB7 ",answers:Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),jc=Object.freeze(Dr.map(e=>Object.freeze({answer:e,label:zt.answers[e]})));function Vc(e,t){let[r,n]=useState(null),[o,a]=useState(null),[s,l]=useState(null),u=useCallback(c=>{t!==null&&(n(c),a(null),t(e.caseId,c).then(p=>{n(null),p.ok?l(c):a(p.error);}));},[t,e.caseId]),d=s??e.answer;return {answer:d,answerable:!fs(e),escalated:d==="worse",pending:r,error:o,choose:u}}i(Vc,"useCheckinCard");var $c=44,BE=.6;function Wc({message:e,checkin:t,onAnswer:r,onFindVet:n}){let o=N(),a=useMemo(()=>jE(o),[o]),s=Vc(t,r),l=s.answer!==null||s.pending!==null,u=r!==null&&s.answerable;return jsx("li",{style:a.row,children:jsxs("div",{role:"group","aria-label":zt.eyebrow,"aria-busy":s.pending!==null?true:void 0,style:a.card,children:[jsx("p",{style:a.eyebrow,children:zt.eyebrow}),jsx("p",{style:a.question,children:e.text}),u?jsx("div",{style:{...a.answers,...s.pending?a.answersPending:null},children:jc.map(({answer:d,label:c})=>{let p=(s.pending??s.answer)===d;return jsx("button",{type:"button",onClick:()=>s.choose(d),disabled:l,"aria-pressed":p,style:{...a.pill,...p?a.pillSelected:null},children:c},d)})}):null,s.answer!==null?jsx("p",{style:a.logged,children:zt.logged}):null,t.resolutionText?jsx("p",{style:a.question,children:t.resolutionText}):null,s.escalated&&n?jsx("button",{type:"button",onClick:n,style:a.findVet,children:zt.findVet}):null,s.error?jsx("p",{role:"alert",style:a.error,children:s.error.displayMessage}):null]})})}i(Wc,"CheckinCard");function jE(e){let t=e.color,r=e.space,n=e.radius,o=e.type,a=k(e,"regular"),s={margin:0,...a,fontSize:o.size.body,lineHeight:`${Math.round(o.size.body*o.lineHeight.normal)}px`},l=o.tierSizes.compact,u=o.tierSizes.control;return {row:{display:"flex",justifyContent:"flex-start",listStyle:"none"},card:{boxSizing:"border-box",maxWidth:"92%",padding:r.md,display:"flex",flexDirection:"column",gap:r.sm,borderRadius:n.lg,backgroundColor:t.surface,border:`1px solid ${t.brandBorder}`},eyebrow:{margin:0,...a,color:t.text.secondary,fontSize:l.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...s,color:t.text.primary,whiteSpace:"pre-wrap"},answers:{display:"flex",gap:r.sm,marginTop:r.xs},answersPending:{opacity:BE},pill:{...s,fontSize:u.body,lineHeight:`${Math.round(u.body*o.lineHeight.normal)}px`,boxSizing:"border-box",flex:1,minHeight:$c,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:`0 ${r.md}px`,borderRadius:n.pill,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surfaceCream,color:t.text.primary,cursor:"pointer"},pillSelected:{backgroundColor:t.brand,borderColor:t.brand,color:t.onPrimary},logged:{margin:0,...a,color:t.text.secondary,fontSize:o.size.caption},error:{margin:0,...a,color:t.danger,fontSize:o.size.caption},findVet:{boxSizing:"border-box",alignSelf:"stretch",minHeight:$c,borderRadius:n.pill,border:`1.5px solid ${t.brandBorder}`,backgroundColor:t.surface,color:t.brandInk,cursor:"pointer",...k(e,"bold"),fontSize:o.size.body}}}i(jE,"makeStyles");var $E=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),Kc="#C8BEB4";function WE(e){return e?$E[e.toUpperCase()]??Kc:Kc}i(WE,"tierColor");function KE(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(KE,"tierLabel");function Ue(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(Ue,"text");function GE(e){let t=Ue(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(GE,"httpsUrl");function qE(e,t){let r=Ue(e.source_name)??Ue(e.sourceName),n=Ue(e.section),o=Ue(e.authority_tier)??Ue(e.authorityTier),a=KE(o),s=r??Ue(e.title)??`Source ${t+1}`,l=Ue(e.monograph_chunk_id)??Ue(e.chunkId),u=[n,a].filter(d=>d!==null).join(" \xB7 ");return Object.freeze({title:s,sourceName:r,section:n,authorityTier:o,tierLabel:a,meta:u.length===0?null:u,url:GE(e.url),excerpt:Ue(e.excerpt),tierColor:WE(o),key:`${s}-${l??"none"}-${t}`})}i(qE,"toCitationCard");function Gc(e){return e===void 0||e.length===0?YE:Object.freeze(e.map((t,r)=>qE(t,r)))}i(Gc,"toCitationCards");var YE=Object.freeze([]);function $i(e){return e===1?`1 ${h.sourceSingular}`:`${e} ${h.sourcePlural}`}i($i,"sourcesLabel");function qc(e,t){return `${t?h.hideSources:h.showSources} ${$i(e)}`}i(qc,"sourcesToggleLabel");function Yc(e){return [e.url!==null?`${h.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(Yc,"citationA11yLabel");var Qc=44,JE=244,Zc=8,Jc=13,eC=14,tC=2,rC=3,nC=.3;function rp({citations:e}){let t=useMemo(()=>Gc(e),[e]),r=N(),n=useMemo(()=>aC(r),[r]),[o,a]=useState(false);return t.length===0?null:jsxs("div",{style:n.wrap,children:[jsxs("button",{type:"button","aria-expanded":o,"aria-label":qc(t.length,o),onClick:()=>a(s=>!s),style:n.pill,children:[jsx(z,{name:"bookOpen",size:Jc,color:r.color.brandInk}),jsx("span",{style:n.pillLabel,children:$i(t.length)}),jsx(z,{name:"chevronDown",size:Jc,color:r.color.brandInk,style:o?{transform:"rotate(180deg)"}:void 0})]}),o?jsx(oC,{cards:t,styles:n,theme:r}):null]})}i(rp,"CitationCards");function oC({cards:e,styles:t,theme:r}){let n=useRef(null),o=Q(),a=Gd();return useEffect(()=>{let s=Re(n.current,{durationMs:o.citationsInMs,fromOpacity:0,fromTranslateY:o.citationsRisePx});return ()=>s?.cancel()},[o]),jsx("ul",{ref:n,style:t.deck,children:e.map(s=>{let l=a.kind==="static"?null:s.url;return jsx("li",{style:t.cardSlot,children:l!==null?jsx("a",{href:l,...iC(a,l),"aria-label":Yc(s),style:{...t.card,...t.cardLink},children:jsx(ep,{card:s,linked:true,styles:t,theme:r})}):jsx("div",{style:t.card,children:jsx(ep,{card:s,linked:false,styles:t,theme:r})})},s.key)})})}i(oC,"Deck");function iC(e,t){return e.kind==="static"?{}:{rel:"noopener noreferrer",onClick:i(r=>{r.defaultPrevented||r.button!==0||r.metaKey||r.ctrlKey||r.shiftKey||r.altKey||(r.preventDefault(),e.open(t));},"onClick")}}i(iC,"linkBehaviour");function ep({card:e,linked:t,styles:r,theme:n}){return jsxs(Fragment,{children:[jsxs("div",{style:r.cardHeader,children:[jsx("span",{"aria-hidden":"true",style:{...r.tierDot,backgroundColor:e.tierColor}}),jsx("span",{style:t?{...r.cardTitle,color:n.color.linkInk}:r.cardTitle,children:e.title}),t?jsx(z,{name:"arrowUpRight",size:eC,color:n.color.linkInk}):null]}),e.meta!==null?jsx("span",{style:r.cardMeta,children:e.meta}):null,e.excerpt!==null?jsx("span",{style:r.cardExcerpt,children:e.excerpt}):null]})}i(ep,"CardBody");function tp(e){return {display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:e,overflow:"hidden"}}i(tp,"clamp");function aC(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return {wrap:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:r.xs,marginTop:r.sm},pill:{boxSizing:"border-box",minHeight:Qc,minWidth:Qc,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:r.xs+2,margin:0,padding:`${r.xs+2}px ${r.md}px`,border:0,borderRadius:n.pill,backgroundColor:t.brandSoft,color:t.brandInk,cursor:"pointer",font:"inherit"},pillLabel:{...k(e,"monoBold"),fontSize:o.tierSizes.compact.micro,lineHeight:`${o.tierSizes.compact.micro}px`,letterSpacing:nC,textTransform:"uppercase",color:t.brandInk},deck:{listStyle:"none",margin:0,padding:`${r.xs}px ${r.xl}px 0 0`,maxWidth:"100%",display:"flex",flexDirection:"row",gap:r.sm,overflowX:"auto"},cardSlot:{flex:"0 0 auto"},card:{boxSizing:"border-box",width:JE,display:"flex",flexDirection:"column",gap:r.xs+2,padding:r.md,borderRadius:n.md,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surface,color:t.text.primary},cardLink:{textDecoration:"none",cursor:"pointer"},cardHeader:{display:"flex",flexDirection:"row",alignItems:"flex-start",gap:r.sm},tierDot:{flexShrink:0,width:Zc,height:Zc,borderRadius:n.pill,marginTop:7},cardTitle:{flex:"1 1 auto",minWidth:0,...k(e,"bold"),fontSize:o.size.bodyTight,lineHeight:`${Math.round(o.size.bodyTight*1.7)}px`,letterSpacing:-0.24,color:t.text.primary,...tp(tC)},cardMeta:{...k(e,"monoMedium"),fontSize:o.tierSizes.compact.nano,lineHeight:`${o.tierSizes.compact.nano+2}px`,letterSpacing:o.letterSpacing.monoWide,textTransform:"uppercase",color:t.text.metaCool,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},cardExcerpt:{...k(e,"regular"),fontSize:o.size.tiny,lineHeight:`${o.size.tiny+4}px`,color:t.text.muted,...tp(rC)}}}i(aC,"makeStyles");function np(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(np,"formatMessageTime");var Wi=44,op=20,uC=3,dC=.6;function ip(e){let{open:t,onSubmit:r,onClose:n,returnFocusTo:o}=e,a=N(),s=useMemo(()=>cC(a),[a]),l=qe(t,n,o),[u,d]=useState(null),[c,p]=useState(""),[f,m]=useState(false),[y,S]=useState(false);if(!t)return null;let g=i(()=>{if(f)return;m(true),S(false);let T=c.trim();r(u,T.length>0?T:null).then(R=>{m(false),R?n():S(true);});},"submit");return jsxs("dialog",{ref:l.dialogRef,"aria-label":h.feedbackTitle,"aria-busy":f?true:void 0,onCancel:l.onCancel,onKeyDown:l.onKeyDown,style:s.sheet,children:[jsx("h2",{style:s.title,children:h.feedbackTitle}),jsx("p",{style:s.subtitle,children:h.feedbackSubtitle}),jsx("div",{role:"group","aria-label":h.feedbackTitle,style:s.options,children:Jo.map(T=>{let R=T.key===u;return jsxs("button",{type:"button","aria-pressed":R,disabled:f,onClick:()=>d(R?null:T.key),style:{...s.option,...R?s.optionSelected:null},children:[jsx("span",{style:s.optionLabel,children:T.label}),jsx("span",{"aria-hidden":"true",style:{...s.radio,...R?s.radioSelected:null},children:R?jsx(z,{name:"check",size:12,color:a.color.surface,strokeWidth:3}):null})]},T.key)})}),jsx("textarea",{rows:uC,value:c,disabled:f,"aria-label":h.feedbackNotesPlaceholder,placeholder:h.feedbackNotesPlaceholder,onChange:T=>{let R=T.target.value;[...R].length<=Xt&&p(R);},style:s.notes}),y?jsx("p",{role:"alert",style:s.failed,children:h.feedbackFailed}):null,jsxs("div",{style:s.actions,children:[jsx("button",{type:"button",onClick:g,"aria-disabled":f,style:{...s.submit,...f?s.pending:null},children:h.feedbackSubmit}),jsx("button",{type:"button",onClick:n,"aria-label":h.feedbackSkipA11y,disabled:f,style:s.skip,children:h.feedbackSkip})]})]})}i(ip,"FeedbackReasons");function cC(e){let t=e.color,r=e.space,n=e.radius,o=e.type,a=`${Math.round(o.size.body*o.lineHeight.normal)}px`,s=o.tierSizes.heading.heading,l=o.tierSizes.control.body,u={boxSizing:"border-box",minHeight:Wi,minWidth:Wi,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,cursor:"pointer",...k(e,"medium"),fontSize:o.size.body,lineHeight:a};return {sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:"80vh",overflowY:"auto",padding:`${r.lg+4}px ${r.lg+4}px ${r.xxl}px`,border:0,borderRadius:`${n.lg}px ${n.lg}px 0 0`,backgroundColor:t.surface,color:t.text.primary,display:"flex",flexDirection:"column",gap:r.md},title:{margin:0,...k(e,"bold"),fontSize:s,lineHeight:`${Math.round(s*1.22)}px`,color:t.text.primary},subtitle:{margin:0,...k(e,"regular"),fontSize:o.size.body,lineHeight:a,color:t.text.muted},options:{display:"flex",flexDirection:"column",gap:r.sm},option:{...u,width:"100%",justifyContent:"space-between",gap:r.md,padding:`${r.sm}px ${r.md}px`,borderRadius:n.md,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surfaceCream,color:t.text.primary,textAlign:"left"},optionSelected:{border:`1px solid ${t.brandInk}`,backgroundColor:t.brandSoft},optionLabel:{flex:"1 1 auto",minWidth:0},radio:{boxSizing:"border-box",flexShrink:0,width:op,height:op,borderRadius:n.pill,border:`1.5px solid ${t.brandBorderStrong}`,backgroundColor:t.surface,display:"inline-flex",alignItems:"center",justifyContent:"center"},radioSelected:{border:`1.5px solid ${t.brandInk}`,backgroundColor:t.brandInk},notes:{boxSizing:"border-box",width:"100%",minHeight:Wi,margin:0,padding:`${r.sm}px ${r.md}px`,borderRadius:n.md,border:`1px solid ${t.brandBorderStrong}`,backgroundColor:t.surfaceCream,color:t.text.primary,resize:"vertical",...k(e,"regular"),fontSize:o.size.body,lineHeight:a},failed:{margin:0,...k(e,"regular"),fontSize:o.size.caption,color:t.danger},actions:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:r.sm},submit:{...u,fontSize:l,padding:`0 ${r.xl}px`,border:0,borderRadius:n.pill,backgroundColor:t.brand,color:t.onPrimary,...Se(e.slots.primaryButton),...Ce(e.slots.primaryButton)},pending:{opacity:dC,cursor:"progress"},skip:{...u,fontSize:l,padding:`0 ${r.xl}px`,border:0,borderRadius:n.pill,background:"transparent",color:t.text.secondary}}}i(cC,"makeStyles");var Er=44,qi=15,lp=16;function fC(){return typeof navigator<"u"&&typeof navigator.clipboard?.writeText=="function"}i(fC,"canCopyToClipboard");function dp(e){let{role:t,text:r,createdAt:n,responseId:o,sentiment:a,feedback:s}=e,l=N(),u=useMemo(()=>mC(l),[l]),d=Q(),c=useMemo(()=>np(n),[n]),p=fC()&&r.length>0,[f,m]=useState(false),y=useRef(null);useEffect(()=>()=>{y.current!==null&&clearTimeout(y.current);},[]);let S=useCallback(()=>{navigator.clipboard.writeText(r).catch(()=>{}),m(true),y.current!==null&&clearTimeout(y.current),y.current=setTimeout(()=>{m(false),y.current=null;},d.copiedMs);},[r,d.copiedMs]),[g,T]=useState(false),[R,_]=useState(false),[w,b]=useState(false),x=useRef(null),A=useCallback(P=>{if(o===void 0)return;_(false),b(false);let v=a===P;s(o,P).then(C=>{C.ok||b(true);}),P==="down"&&!v&&T(true);},[o,a,s]),F=useCallback(async(P,v)=>{if(o===void 0)return false;if(P===null&&v===null)return _(true),true;let C=await s(o,"down",P??"other",v);return C.ok&&_(true),C.ok},[o,s]);return jsxs("div",{style:{...u.footer,...t==="user"?u.footerUser:u.footerAssistant},children:[jsxs("div",{style:u.row,children:[c!==null?jsx("span",{style:u.timestamp,children:c}):null,p?jsx("button",{type:"button",onClick:S,"aria-label":f?h.copied:t==="user"?h.copyUserMessage:h.copyAssistantMessage,style:u.iconButton,children:f?jsx(z,{name:"check",size:qi,color:l.color.success}):jsx(z,{name:"copy",size:qi,color:l.color.text.timestamp})}):null,t==="assistant"&&o!==void 0?Cu.map(P=>{let v=a===P.sentiment,C=l.color.sentiment[P.sentiment];return jsx("button",{ref:P.sentiment==="down"?x:void 0,type:"button","aria-pressed":v,"aria-label":P.label,onClick:()=>A(P.sentiment),style:u.iconButton,children:jsx(z,{name:P.sentiment==="up"?"thumbsUp":"thumbsDown",size:qi,color:C,fill:v?C:"transparent",style:P.sentiment==="neutral"?{transform:"rotate(-90deg)"}:void 0})},P.sentiment)}):null]}),R?jsx("p",{role:"status",style:u.thanks,children:h.feedbackThanks}):null,w?jsx("p",{role:"alert",style:u.failed,children:h.feedbackFailed}):null,g?jsx(ip,{open:true,onSubmit:F,onClose:()=>T(false),returnFocusTo:x}):null]})}i(dp,"MessageFooter");function mC(e){let t=e.color,r=e.space,n=e.type;return {footer:{display:"flex",flexDirection:"column",gap:r.xs,paddingTop:r.xs+2},footerUser:{alignItems:"flex-end"},footerAssistant:{alignItems:"flex-start"},row:{display:"flex",flexDirection:"row",alignItems:"center",gap:r.sm+2,minHeight:lp},timestamp:{...k(e,"monoMedium"),fontSize:n.tierSizes.compact.nano,lineHeight:`${n.tierSizes.compact.nano+2}px`,color:e.color.text.timestamp},iconButton:{boxSizing:"border-box",width:Er,height:Er,minWidth:Er,minHeight:Er,margin:`${ -28/2}px 0`,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},thanks:{margin:0,...k(e,"regular"),fontSize:n.size.caption,color:t.text.secondary},failed:{margin:0,...k(e,"regular"),fontSize:n.size.caption,color:t.danger}}}i(mC,"makeStyles");var cp="#10462E",pp="#000000",yC="#83E0B4",gC=Object.freeze([Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:yC,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:cp,brandEdge:true,borderWidth:1}),Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}\u2019s vet visit.",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]),hC=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function bC(e){return e==null?e:e.replace(hC,"").trim()}i(bC,"formatBreedForPrompt");var vC=new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function EC(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return vC.has(t)}i(EC,"isUninformativeBreed");function CC(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(CC,"unspecifiedBreedLabel");function SC(e,t){return EC(e)?CC(t):String(e).replace(/\s+/gu," ").trim()}i(SC,"resolveBreedLabel");function fp(e){let t=e?.name?.trim()||h.emptyTitlePetFallback;return K(h.emptyTitle,{petName:t})}i(fp,"emptyStateTitle");function mp(e,t=cp){let r=Ci(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,a=o||n,s=SC(bC(e?.breed),r)||null,l=Si(e?.ageYears),u=l===null?null:String(l);return Object.freeze(gC.map(d=>{let c=d.label.includes("{breed}"),p=d.label.includes("{ageYears}"),m=d.fallbackLabel!==void 0&&(c&&!s||p&&!u)&&d.fallbackLabel?d.fallbackLabel:d.label,y=K(m,{petName:a,breed:s??n,species:r,ageYears:u??""}),S=!o&&m.startsWith("{petName}")?y.charAt(0).toUpperCase()+y.slice(1):y;return Object.freeze({id:d.id,intent:d.intent,label:S,background:d.background,borderColor:d.brandEdge===true?t:d.borderColor,borderWidth:d.borderWidth})}))}i(mp,"resolveQuickPrompts");var gp=44,kC=28,PC=34,_C=-0.8,wC=340;function hp({pet:e,onSend:t,onVetPrep:r}){let n=N(),o=useMemo(()=>AC(n),[n]),a=Q(),s=fp(e),l=Qd(Jd()),u=useId(),d=useMemo(()=>mp(e,n.color.brandInk).filter(c=>c.intent!=="vet_report"||r!==null),[e,r,n.color.brandInk]);return jsxs("div",{style:o.wrap,children:[jsx(l,{id:u,style:o.title,children:s}),jsx("ul",{"aria-labelledby":u,style:o.list,children:d.map((c,p)=>jsx("li",{children:jsx(IC,{chip:c,delayMs:oc(a,p),durationMs:a.followUpInMs,style:o.chip,onPress:()=>c.intent==="vet_report"?r?.():t(c.label)})},c.id))})]})}i(hp,"QuickPrompts");function IC({chip:e,delayMs:t,durationMs:r,style:n,onPress:o}){let a=useRef(null);return useEffect(()=>{let s=Re(a.current,{durationMs:r,delayMs:t,fromOpacity:0});return ()=>s?.cancel()},[r,t]),jsx("button",{ref:a,type:"button",onClick:o,style:{...n,backgroundColor:e.background,border:`${e.borderWidth}px solid ${e.borderColor}`},children:e.label})}i(IC,"Chip");function AC(e){let t=e.space,r=e.radius,n=e.type;return {wrap:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.lg+2},title:{margin:0,maxWidth:wC,...k(e,"bold"),fontSize:Yo(e,"heading",kC),lineHeight:`${Yo(e,"heading",PC)}px`,letterSpacing:_C,color:e.color.text.primary,textAlign:"center"},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",alignItems:"center",gap:t.md},chip:{boxSizing:"border-box",minHeight:gp,minWidth:gp,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`${t.sm+1}px ${t.md+2}px`,borderRadius:r.pill,cursor:"pointer",...k(e,"bold"),fontSize:n.tierSizes.compact.caption,lineHeight:`${n.tierSizes.compact.caption+2}px`,color:pp,textAlign:"center",whiteSpace:"normal"}}}i(AC,"makeStyles");var Yi=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function bp(e){return e.includes("*")||e.includes("`")}i(bp,"hasInlineMarkup");function vp(e){let t=[],r=0;Yi.lastIndex=0;for(let n=Yi.exec(e);n!==null;n=Yi.exec(e)){n.index>r&&t.push({kind:"text",text:e.slice(r,n.index)});let o=n[1],a=n[2],s=n[3];o!==void 0?t.push({kind:"bold",text:o}):a!==void 0?t.push({kind:"italic",text:a}):s!==void 0&&t.push({kind:"code",text:s}),r=n.index+n[0].length;}return r<e.length&&t.push({kind:"text",text:e.slice(r)}),t}i(vp,"tokenizeInlineMarkdown");function Ep(e,t){return bp(e)?vp(e).map((r,n)=>{switch(r.kind){case "bold":return jsx("strong",{style:t.bold,children:r.text},n);case "italic":return t.italic?jsx("em",{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsx("code",{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(Ep,"renderInlineMarkdown");var Cp=6,LC=3.5,Sp=520,NC=Math.round(Sp*.18),Qi=.44,UC=.5,HC=[0,1,2];function Rp(){let e=N(),t=useMemo(()=>BC(e),[e]),r=!e.motion.reducedMotion;return jsx("div",{role:"img","aria-label":h.typing,style:t.card,children:HC.map(n=>r?jsx(zC,{index:n,style:t.dot},n):jsx("div",{style:{...t.dot,...t.dotStatic}},n))})}i(Rp,"TypingIndicator");function zC({index:e,style:t}){let r=useRef(null);return useEffect(()=>{let n=r.current;if(n===null||typeof n.animate!="function")return;let o=n.animate([{opacity:Qi,transform:"translateY(0)"},{opacity:1,transform:`translateY(-${LC}px)`},{opacity:Qi,transform:"translateY(0)"}],{duration:Sp,iterations:1/0,delay:e*NC,easing:"ease-in-out"});return ()=>o.cancel()},[e]),jsx("div",{ref:r,style:{...t,opacity:Qi}})}i(zC,"AnimatedDot");function BC(e){let t=e.color,r=e.space,n=e.radius;return {card:{boxSizing:"border-box",alignSelf:"flex-start",display:"flex",flexDirection:"row",alignItems:"center",gap:r.xs,padding:`${r.sm}px ${r.md}px`,backgroundColor:t.surfaceCream,borderRadius:n.md,border:`1px solid ${t.brandBorder}`},dot:{width:Cp,height:Cp,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:UC}}}i(BC,"makeStyles");function GC({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=fe(),o=e.tone==="error";return jsxs("div",{role:"alert",style:{...n.turnNotice,...o?n.turnNoticeError:null},children:[jsx("p",{style:{...n.turnNoticeTitle,...o?n.turnNoticeTitleError:null},children:e.title}),jsx("p",{style:n.turnNoticeBody,children:e.body}),jsx("button",{type:"button",onClick:e.action==="startNew"?r:t,style:n.turnNoticeAction,children:e.actionLabel})]})}i(GC,"TurnNoticeCard");function Tp(e,t,r,n,o,a,s,l,u,d){switch(e){case "loading":return n?jsx(xt,{render:n,fallback:jsx(xp,{})}):jsx(xp,{});case "empty":return jsx(YC,{prompts:t.suggestedPrompts,onSelectPrompt:r,pet:o,onVetPrep:a});case "error":return jsx(QC,{error:t.error,onRetry:t.retryLast,onAddPet:u});case "populated":return jsx(ZC,{chat:t,onSelectPrompt:r,onAnswerCheckin:t.petRef?t.answerCheckin:null,imagesFor:s,onPreview:l,onCheckinFindVet:d});default:return Je(e)}}i(Tp,"renderView");function xp(){let{styles:e}=fe(),[t,r]=useState(false);return useEffect(()=>{let n=setTimeout(()=>r(true),Rc);return ()=>clearTimeout(n)},[]),jsx("div",{role:"status","aria-busy":"true","aria-label":h.loading,style:e.centered,children:t?jsx(qC,{}):null})}i(xp,"LoadingState");function qC(){let{theme:e,styles:t}=fe(),r=useRef(null),n=!e.motion.reducedMotion;return useEffect(()=>{let o=r.current;if(!n||o===null||typeof o.animate!="function")return;let a=o.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:kc,iterations:1/0,easing:"linear"});return ()=>a.cancel()},[n]),jsx("div",{ref:r,"aria-hidden":"true",style:t.spinner})}i(qC,"Spinner");function YC({prompts:e,onSelectPrompt:t,pet:r,onVetPrep:n}){let{styles:o}=fe();return jsx("div",{role:"region","aria-label":h.empty,style:o.emptyScroller,children:jsxs("div",{style:o.emptyContent,children:[jsx(hp,{pet:r,onSend:t,onVetPrep:n}),jsx(kp,{prompts:e,onSelectPrompt:t})]})})}i(YC,"EmptyState");function kp({prompts:e,onSelectPrompt:t}){let{styles:r}=fe(),n=useId();return e.length===0?null:jsxs("div",{style:r.followUps,children:[jsx("p",{id:n,style:r.followUpsLabel,children:h.followUps}),jsx("ul",{"aria-labelledby":n,style:r.followUpList,children:e.map((o,a)=>jsx(XC,{prompt:o,index:a,onSelectPrompt:t},o))})]})}i(kp,"FollowUps");function XC({prompt:e,index:t,onSelectPrompt:r}){let{styles:n}=fe(),o=Q(),a=useRef(null);return useEffect(()=>{let s=Re(a.current,{durationMs:o.followUpInMs,delayMs:t*o.followUpStaggerMs,fromOpacity:0});return ()=>s?.cancel()},[o,t]),jsx("li",{ref:a,style:n.followUpDivider,children:jsx("button",{type:"button",onClick:()=>r(e),style:n.followUpRow,children:e})})}i(XC,"FollowUpRow");function QC({error:e,onRetry:t,onAddPet:r}){let{styles:n}=fe(),o=r!==null&&wu(e)?r:null;return jsxs("div",{role:"alert",style:n.centered,children:[jsx("p",{style:n.errorText,children:e.displayMessage}),o!==null?jsx("button",{type:"button",onClick:o,style:n.retryButton,children:h.addPet}):null,e.retryable?jsx("button",{type:"button",onClick:t,style:n.retryButton,children:h.retry}):null]})}i(QC,"ErrorState");function ZC({chat:e,onSelectPrompt:t,onAnswerCheckin:r,imagesFor:n,onPreview:o,onCheckinFindVet:a}){let{styles:s}=fe(),{messages:l,suggestedPrompts:u,isStreaming:d}=e,c=dn(l,d),p=Gu(e),f=useMemo(()=>Ac(Ic(l)),[l]),m=useRef(null),y=useRef(true),S=useCallback(()=>{let R=m.current;R!==null&&(y.current=R.scrollHeight-R.scrollTop-R.clientHeight<=_c);},[]);useLayoutEffect(()=>{let R=m.current;R!==null&&y.current&&(R.scrollTop=R.scrollHeight);},[l,c,d]);let g=l[l.length-1],T=d&&g!==void 0&&g.role==="assistant"?g.id:null;return jsxs("div",{ref:m,onScroll:S,role:"region","aria-label":h.transcript,tabIndex:0,style:s.list,children:[e.historyCursor?jsx("button",{type:"button",disabled:e.isLoadingHistory,onClick:()=>{e.loadOlderMessages();},style:s.earlierButton,children:e.isLoadingHistory?W.loadingEarlier:W.earlier}):null,jsx("ol",{style:s.messageList,children:l.map(R=>R.checkin&&f.has(R.id)?jsx(Wc,{message:R,checkin:R.checkin,onAnswer:r,onFindVet:a},R.id):jsx(JC,{message:R,streaming:R.id===T,chat:e,images:n(R),onPreview:o},R.id))}),e.reconnecting===true?jsx("p",{style:s.reconnectingCaption,children:h.reconnecting}):null,c?jsx(Rp,{}):null,p!==null?jsx(GC,{notice:p,onRetry:e.retryLast,onStartNew:e.newConversation}):null,d?null:jsx(kp,{prompts:u,onSelectPrompt:t})]})}i(ZC,"PopulatedState");function JC({message:e,streaming:t,chat:r,images:n,onPreview:o}){let{styles:a}=fe(),s=Q(),l=useRef(null),u=e.role==="user";useEffect(()=>{let f=Re(l.current,{durationMs:s.messageInMs,fromOpacity:0});return ()=>f?.cancel()},[]);let d=lc(e.text,t&&!u,s),c=u?h.senderUser:h.senderAssistant,p=e.pending!==true&&!t;return jsxs("li",{ref:l,style:{...a.row,...u?a.rowUser:a.rowAssistant},"aria-busy":e.pending===true?true:void 0,children:[jsxs("div",{style:{...a.bubble,...u?a.bubbleUser:a.bubbleAssistant,...e.pending?a.bubblePending:null},children:[jsx("span",{style:it,children:`${c}: `}),n.length>0?jsx(zc,{images:n,onPreview:o}):null,jsx("p",{style:u?a.bubbleTextUser:a.bubbleTextAssistant,children:u?d:Ep(d,{bold:a.bubbleBold,italic:a.bubbleItalic,code:a.bubbleCode})})]}),!u&&!t?jsx(rp,{citations:e.citations}):null,p?jsx(dp,{role:e.role,text:e.text,createdAt:e.createdAt,...e.responseId!==void 0?{responseId:e.responseId}:{},sentiment:r.sentimentByMessage[e.id]??null,feedback:r.feedback}):null]})}i(JC,"MessageRow");function wp(e,t,r){let[n,o]=useState({send:e,conversationId:t,text:r??"",seeded:r??null}),a=n.send===e&&(n.conversationId===null||n.conversationId===t);useEffect(()=>{o(l=>{let u=l.send===e&&(l.conversationId===null||l.conversationId===t),d=u?l.text:"",c=u?l.seeded:null,p=r!=null&&r!==c&&d.length===0;return {send:e,conversationId:t,text:p?r:d,seeded:p?r:c}});},[e,t,r]);let s=useCallback(l=>o(u=>({send:e,conversationId:t,text:l,seeded:u.seeded})),[e,t]);return [a?n.text:"",s]}i(wp,"useChatDraft");function Ip(e,t,r,n){let o=useRef({draft:r,setDraft:n});o.current={draft:r,setDraft:n};let a=useRef(null),[s,l]=useState(null);useEffect(()=>{if(e===void 0)return;let u=`${t??""}`;if(a.current===u)return;a.current=u;let d=true;return (async()=>{let c=await Mu(()=>e.read(t));if(!d)return;let p=c.ok&&typeof c.value=="string"?c.value:"";p.length>0&&o.current.draft.length===0&&o.current.setDraft(p),l(u);})(),()=>{d=false;}},[e,t]),useEffect(()=>{e===void 0||s!==`${t??""}`||se(()=>e.write(t,r));},[e,t,r,s]);}i(Ip,"usePersistedDraft");var Ln=44,oS=18,iS=14,Nn=6,aS=1200,sS=.4;function lS(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return `${r}:${n.toString().padStart(2,"0")}`}i(lS,"formatDictationElapsed");function Op(e){switch(e){case "permissionDenied":return h.micBlocked;case "noSpeech":return h.noSpeech;case "unavailable":return h.dictationUnavailable}}i(Op,"dictationErrorMessage");function Fp({active:e,listening:t,elapsedMs:r,disabled:n=false,onToggle:o}){let a=N(),s=useMemo(()=>dS(a),[a]);return jsxs("span",{style:s.wrap,children:[t?jsx("span",{"aria-hidden":"true",style:s.timer,children:lS(r)}):null,jsx("button",{type:"button",disabled:n,onClick:()=>o(),"aria-label":e?h.stopDictation:h.dictate,"aria-pressed":e,style:{...s.button,...n?s.buttonDisabled:null},children:e?jsxs(Fragment,{children:[jsx(uS,{style:s.pulse}),jsx(z,{name:"square",size:iS,color:a.color.brandInk,fill:a.color.brandInk,style:{position:"relative"}})]}):jsx(z,{name:"mic",size:oS,color:a.color.brandInk})}),jsx("span",{role:"status","aria-live":"polite",style:it,children:t?h.listening:""})]})}i(Fp,"DictationButton");function uS({style:e}){let t=useRef(null),r=Q();return useEffect(()=>{let n=t.current;if(r.reduced||!Lt(n))return;let o=n.animate([{opacity:1},{opacity:.4},{opacity:1}],{duration:aS,iterations:1/0,easing:"ease-in-out"});return ()=>o.cancel()},[r.reduced]),jsx("span",{ref:t,"aria-hidden":"true",style:e})}i(uS,"Pulse");function dS(e){let t=e.color,r=e.radius,n=e.type;return {wrap:{display:"inline-flex",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...k(e,"mono"),fontSize:n.tierSizes.compact.micro,lineHeight:`${n.tierSizes.compact.micro+2}px`,fontVariantNumeric:"tabular-nums",color:t.text.muted},button:{position:"relative",boxSizing:"border-box",width:Ln,height:Ln,minWidth:Ln,minHeight:Ln,margin:0,padding:0,border:0,borderRadius:r.pill,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:t.brandInk},buttonDisabled:{opacity:sS,cursor:"not-allowed"},pulse:{position:"absolute",top:Nn,right:Nn,bottom:Nn,left:Nn,borderRadius:r.pill,backgroundColor:t.brandSofter}}}i(dS,"makeStyles");function Mp(e){if(!e)return null;let t=e.SpeechRecognition??e.webkitSpeechRecognition;return typeof t=="function"?t:null}i(Mp,"getRecognitionConstructor");function Ji(e){return typeof e=="string"&&e.toLowerCase().startsWith("en")?e:"en-US"}i(Ji,"resolveDictationLang");async function Dp(e,t){let r=Mp(e);if(!r)return "none";if(typeof r.available!="function")return "browser";try{let n=await r.available({langs:[t],processLocally:!0});return n==="available"?"on_device":n==="downloadable"?"downloadable":"browser"}catch{return "browser"}}i(Dp,"probeDictationCapability");function pS(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e[r]?.[0]?.transcript?.trim();if(!n)continue;let o=t[t.length-1];o&&n.toLowerCase().startsWith(o.toLowerCase())?t[t.length-1]=n:t.push(n);}return t.join(" ")}i(pS,"joinRecognitionResults");function Lp(e,t,r){let n=t.trim();if(!n)return e;let o=e===""||/\s$/.test(e)?"":" ",a=`${e}${o}${n}`;return typeof r=="number"&&r>0?a.slice(0,r):a}i(Lp,"composeDictatedText");function fS(e){return e==="not-allowed"||e==="service-not-allowed"?"permissionDenied":e==="no-speech"?"noSpeech":"unavailable"}i(fS,"mapDictationError");var mS=new Set(["language-not-supported","service-not-allowed"]),yS={setTimeout:i((e,t)=>globalThis.setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>globalThis.clearTimeout(e),"clearTimeout")};function Np(e){let{env:t,capability:r,lang:n,callbacks:o}=e,a=e.timers??yS,s=e.maxDurationMs??6e4,l=Mp(t),u=r==="on_device"?"on_device":"browser",d=u==="on_device"&&(e.phrases?.length??0)>0&&typeof t.SpeechRecognitionPhrase=="function",c=false,p=false,f=false,m=null,y=0,S=false,g=false,T=false,R=false,_=false,w="",b=null,x=null,A=i(()=>{if(g)return;g=true,y+=1,x!==null&&a.clearTimeout(x),x=null;let C=b;C===null&&!R&&w.trim()===""&&(C="noSpeech"),o.onEnd?.({mode:u,transcript:w,error:C});},"finish"),F=i(()=>{if(!l){b="unavailable",A();return}y+=1;let C=y,I=i(()=>C===y&&!g,"live"),O=new l;if(m=O,O.lang=n,O.continuous=true,O.interimResults=true,u==="on_device")try{O.processLocally=!0;}catch{u="browser";}if(u==="on_device"&&d)try{let B=t.SpeechRecognitionPhrase;O.phrases=(e.phrases??[]).map(V=>new B(V));}catch{d=false,p=true;}O.onstart=()=>{!I()||S||(S=true,o.onStart?.(u));},O.onresult=B=>{I()&&(_=true,w=pS(B.results),o.onTranscript?.(w));},O.onerror=B=>{if(!I())return;let V=B?.error??"";if(!(V==="aborted"&&T)){if(V==="phrases-not-supported"&&!p&&!_&&!T){d=false,p=true,f=true;return}if(u==="on_device"&&!c&&!_&&!T&&mS.has(V)){u="browser",d=false,c=true,f=true;return}V==="no-speech"&&w.trim()!==""||(b=fS(V));}},O.onend=()=>{if(I()){if(f&&!T){f=false,F();return}A();}};try{O.start();}catch{if(u==="on_device"&&!c){u="browser",d=false,c=true,F();return}b="unavailable",A();}},"launch");if(r==="downloadable"&&l&&typeof l.install=="function")try{Promise.resolve(l.install({langs:[n],processLocally:!0})).catch(()=>{});}catch{}let P=i(()=>{if(!(g||T)){T=true,f=false,x!==null&&a.clearTimeout(x),x=null;try{m?.stop();}catch{A();}}},"stopListening");x=a.setTimeout(()=>{x=null,P();},s);let v={get mode(){return u},stop(){g||T||(R=true,P());},cancel(){if(g)return;T=true,R=true,f=false;let C=m;A();try{C?.abort();}catch{}}};return F(),v}i(Np,"startDictation");var gS=6e3;function ea(e,t,r){if(e)try{e.track(t,{...r});}catch{}}i(ea,"trackDictationEvent");function hS(){return typeof window>"u"?null:window}i(hS,"browserEnv");function Up({enabled:e,input:t,setInput:r,phrases:n,maxLength:o,telemetry:a,env:s}){let[l,u]=useState("none"),[d,c]=useState("idle"),[p,f]=useState(null),[m,y]=useState(0),S=useRef(null),g=useRef(null),T=useRef(t);T.current=t;let R=useRef(r);R.current=r;let _=useRef(a);_.current=a;let[w,b]=useState(0),x=useCallback(()=>s??hS(),[s]);useEffect(()=>{if(!e){u("none");return}let I=x();if(!I)return;let O=true;return Dp(I,Ji(I.navigator?.language)).then(B=>{O&&u(B);}),()=>{O=false;}},[e,x,w]);let A=useCallback(()=>{let I=x();if(!I||l==="none")return;f(null),y(0),g.current=null,c("starting");let O=T.current,B=l,V=false,Z=Np({env:I,capability:l,lang:Ji(I.navigator?.language),...n!==void 0?{phrases:n}:{},callbacks:{onStart:i(q=>{g.current=Date.now(),c("listening"),ea(_.current,"chat_dictation_started",{mode:q});},"onStart"),onTranscript:i(q=>{R.current(Lp(O,q,o));},"onTranscript"),onEnd:i(({mode:q,transcript:Be,error:$})=>{V=true,S.current=null;let be=g.current;g.current=null,$?(f($),c("error"),ea(_.current,"chat_dictation_failed",{mode:q,error:$})):(c("idle"),ea(_.current,"chat_dictation_completed",{mode:q,duration_ms:be===null?0:Date.now()-be,char_count:Be.trim().length})),B==="downloadable"&&b(we=>we+1);},"onEnd")}});V||(S.current=Z);},[l,o,n,x]),F=useCallback(()=>{S.current?.stop();},[]),P=useCallback(()=>{S.current?.cancel();},[]),v=d==="starting"||d==="listening",C=useCallback(()=>{if(S.current){S.current.stop();return}A();},[A]);return useEffect(()=>{if(d!=="listening")return;let I=i(()=>{let B=g.current;B!==null&&y(Date.now()-B);},"tick");I();let O=setInterval(I,1e3);return ()=>clearInterval(O)},[d]),useEffect(()=>{if(!v||typeof document>"u")return;let I=i(()=>{document.visibilityState==="hidden"&&S.current?.stop();},"onVisibility");return document.addEventListener("visibilitychange",I),()=>document.removeEventListener("visibilitychange",I)},[v]),useEffect(()=>{if(!v||typeof document>"u")return;let I=i(O=>{O.key==="Escape"&&S.current?.stop();},"onKey");return document.addEventListener("keydown",I),()=>document.removeEventListener("keydown",I)},[v]),useEffect(()=>{if(d!=="error")return;let I=setTimeout(()=>{f(null),c("idle");},gS);return ()=>clearTimeout(I)},[d]),useEffect(()=>()=>{S.current?.cancel();},[]),{supported:e&&l!=="none",status:d,active:v,error:p,elapsedMs:m,toggle:C,stop:F,cancel:P}}i(Up,"useDictation");var bS=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function Hp(e={}){let t=new Set,r=[];for(let n of [e.name,e.breed,...bS]){let o=(n??"").trim();if(!o)continue;let a=o.toLowerCase();if(!t.has(a)&&(t.add(a),r.push(o),r.length>=100))break}return r}i(Hp,"buildDictationPhrases");function Bp({send:e,draftScope:t,stop:r,isStreaming:n,inputRef:o,conversationId:a,seed:s,draftStore:l,attachments:u,onPreview:d,dictation:c,pet:p,telemetry:f}){let{theme:m,styles:y}=fe(),[S,g]=wp(t,a,s);Ip(l,a===null?null:String(a),S,g);let[T,R]=useState(false),_=m.meta.placeholder??h.placeholder,w=useMemo(()=>Hp({name:p?.name??null,breed:p?.breed??null}),[p?.name,p?.breed]),b=Up({enabled:c,input:S,setInput:g,phrases:w,maxLength:pt,telemetry:f}),x=b.cancel,A=b.active,F=useRef(null),P=useRef(new Set),v=useRef(new Set);useEffect(()=>()=>{for(let j of P.current)gr(j);for(let j of v.current)gr(j);},[]);let C=useCallback(j=>{if(u===null)return;let oe=Array.from(j.target.files??[]);if(j.target.value="",oe.length===0)return;u.dismissRejected();let dt=oe.map(En),xe=u.add(dt);dt.forEach((kr,zn)=>{xe[zn]?.ok===true?P.current.add(kr.uri):gr(kr.uri);});},[u]),I=useCallback(j=>{if(u===null)return;let oe=u.attachments.find(dt=>dt.id===j);u.remove(j),oe!==void 0&&P.current.delete(oe.previewUri)&&gr(oe.previewUri);},[u]),O=u!==null&&u.uploading,B=u!==null&&u.failed,V=O||B,Z=useMemo(()=>[...S].length>pt,[S]),q=useCallback(()=>{if(S.trim().length===0||[...S].length>pt||V)return;A&&x();let j=u===null?Uc:u.attachments.flatMap(oe=>oe.status==="uploaded"?[{uri:oe.previewUri,filename:oe.filename}]:[]);for(let oe of j)P.current.delete(oe.uri),v.current.add(oe.uri);e(S,j),g("");},[S,e,V,A,x,u,g]),Be=useCallback(()=>{r();},[r]),$=useCallback(j=>{j.key!=="Enter"||j.shiftKey||j.altKey||j.ctrlKey||j.metaKey||j.nativeEvent.isComposing||(j.preventDefault(),q());},[q]),be=useCallback(j=>{A&&x(),g(j.target.value);},[A,x,g]);useLayoutEffect(()=>{let j=o.current;j!==null&&(j.style.height="auto",j.style.height=`${Math.min(j.scrollHeight,ji)}px`);},[S,o]);let we=Z||V,lt=u!==null&&u.attachments.length>=u.maxPerMessage,ut=useCallback(j=>{j.target===j.currentTarget&&(j.preventDefault(),o.current?.focus());},[o]),Ze=m.slots.sendButton?.textColor??m.color.brandInk;return jsxs("div",{style:y.composerBlock,children:[B?jsx("p",{role:"alert",style:y.composerError,children:h.attachmentsFailedBlocked}):null,u!==null&&u.rejected!==null?jsx("p",{role:"alert",style:y.composerError,children:Tu(u.rejected)}):null,b.supported&&b.error!==null?jsx("p",{role:"alert",style:y.composerError,children:Op(b.error)}):null,u!==null?jsx(Hc,{attachments:u.attachments,onRetry:u.retry,onRemove:I,onPreview:d}):null,jsxs("div",{style:{...y.composer,...T?y.composerFocused:null},onMouseDown:ut,children:[u!==null?jsxs(Fragment,{children:[jsx("input",{ref:F,type:"file",accept:_s,multiple:u.maxPerMessage>1,onChange:C,tabIndex:-1,"aria-hidden":"true",style:it}),jsx("button",{type:"button",onClick:()=>F.current?.click(),"aria-label":ku(u.attachments.length,u.maxPerMessage),"aria-disabled":lt,style:{...y.iconControl,...lt?y.actionButtonDisabled:null},children:jsx(z,{name:"upload",size:Pc,color:m.color.brandInk})})]}):null,jsxs("div",{style:y.inputWrap,children:[S.length===0?jsx("span",{"aria-hidden":"true",style:y.placeholder,children:_}):null,jsx("textarea",{ref:o,rows:1,value:S,onChange:be,onKeyDown:$,onFocus:()=>R(true),onBlur:()=>R(false),"data-ef-focus-ring":"self","aria-label":_,style:y.input})]}),b.supported?jsx(Fp,{active:b.active,listening:b.status==="listening",elapsedMs:b.elapsedMs,onToggle:b.toggle}):null,n?jsx("button",{type:"button",onClick:Be,"aria-label":h.stop,style:y.actionButton,children:jsx("span",{"data-everfur-send-disc":"",style:y.sendDisc,children:jsx(z,{name:"square",size:Tc,color:Ze,fill:Ze})})}):jsx("button",{type:"button",onClick:q,"aria-label":h.send,"aria-disabled":we,style:{...y.actionButton,...we?y.actionButtonDisabled:null},children:jsx("span",{"data-everfur-send-disc":"",style:y.sendDisc,children:jsx(z,{name:"send",size:xc,color:Ze})})})]})]})}i(Bp,"Composer");var xS=vn(),ra=Object.freeze([]),TS=Object.freeze({display:"contents"});function Vp(e){let{style:t,className:r,renderPending:n}=e;return jsx(Zo,{capability:"chat",style:t,className:r,...n?{renderPending:n}:{},children:jsx(qd,{onOpenUrl:e.onOpenUrl,children:jsx(ec,{headingLevel:e.headingLevel,children:jsx(kS,{...e})})})})}i(Vp,"EverfurChat");function kS(e){let{petRef:t,conversationId:r,style:n,className:o,renderPending:a,onPetChange:s,onVetPrep:l,onFindVet:u,renderVetAction:d,pet:c,onAddPet:p,checkinTarget:f,initialAsk:m,composerSeed:y,lifecycle:S,draftStore:g,vetReturnTo:T,vetUsState:R,vetPrefer:_}=e,w=e.attachments!==false,b=e.attachments===false?void 0:e.attachments?.maxPerMessage,x=e.dictation!==false,{theme:A,styles:F}=fe(),P=useMemo(()=>qu(t,r),[t,r]),v=pr(P),C=Ku(v),I=useRef(null),O=_S(v),B=X(),V=cn(),Z=useMemo(()=>Yu(V.pets,v.petRef),[V.pets,v.petRef]),q=useMemo(()=>p===void 0?null:()=>{se(p);},[p]),Be=useCallback(ve=>{B.handle.setActivePet(ve),se(s,ve);},[B.handle,s]),$=Bu(v),be=kn(),we=useRef(null),lt=(v.hasUnreadThreads??false)||(v.unreadCount??0)>0||$.rows.some(ve=>ve.unreadCount!==null&&ve.unreadCount>0);Uu(v.openCheckin,f),Ou(v.askEverfur,v.isBootstrapping,m);let ut=useMemo(()=>ii(y),[y]);Lu(S,{conversationId:v.conversationId===null?null:String(v.conversationId),isTurnInFlight:v.isStreaming,refresh:v.refreshActiveThread});let Ze=Wu(useMemo(()=>$u(v.messages),[v.messages])),j=useMemo(()=>td(v.petRef,T===void 0&&R===void 0&&_===void 0?void 0:{returnTo:T,usState:R,prefer:_}),[v.petRef,T,R,_]),oe=Td(j),dt=oe.open,xe=useMemo(()=>({available:oe.available,open:i(()=>{dt();},"open")}),[oe.available,dt]),kr=useMemo(()=>xe.available?xe.open:u!==void 0?()=>{se(u,"emergency");}:null,[xe,u]),zn=useMemo(()=>l!==void 0?()=>{se(l,v.petRef);}:xe.available?xe.open:null,[l,v.petRef,xe]),It=on({transport:xS,...b!==void 0?{maxPerMessage:b}:{}}),Bn=PS(v.messages),[$p,oa]=useState(null),ia=useRef(null),aa=useCallback((ve,Vn)=>{ia.current=Vn,oa(ve);},[]),Wp=useCallback(()=>oa(null),[]),Kp=useCallback(ve=>{v.send(ve),I.current?.focus();},[v.send]),Gp=useCallback((ve,Vn)=>{Bn.record(ve,Vn),It.s3Keys.length>0?v.send(ve,{imageS3Keys:It.s3Keys}):v.send(ve),It.clear();},[v.send,It,Bn]),qp=B.runtime.registry?.services?.telemetry??null,jn=useRef(null);return Zu(jn,A.color.brandInk),tc(jn),jsxs("div",{ref:jn,className:o,style:{...F.container,...n},children:[jsx($d,{pets:V.pets,activePet:Z,unread:lt,onOpenHistory:$.open?$.close:$.show,historyTriggerRef:we,onSelectPet:Be,onAddPet:q,rail:be.rail,historyOpen:$.open,onNewChat:$.newConversation,vetEntry:xe.available?xe.open:null}),c!==void 0?jsx(wS,{petRef:t??null,pet:c,onRegistered:V.refresh}):null,jsxs("div",{style:F.split,children:[jsxs("div",{style:F.main,children:[jsx(fc,{surface:Ze,vetEntry:xe,renderVetAction:d,onFindVet:u}),jsx("div",{style:F.body,children:Tp(C,v,Kp,a,Z,zn,Bn.imagesFor,aa,q,kr)}),jsx(Bp,{send:Gp,draftScope:v.send,stop:v.stop,isStreaming:v.isStreaming,inputRef:I,conversationId:v.conversationId,seed:ut,draftStore:g,attachments:w&&It.available?It:null,onPreview:aa,dictation:x,pet:Z,telemetry:qp}),jsx(ed,{}),A.meta.hidePoweredBy?null:jsx("p",{style:F.poweredBy,children:h.poweredBy})]}),jsx(cc,{chat:v,history:$,mode:be.rail?"rail":"dialog",returnFocusTo:we})]}),jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:it,children:O}),jsx(Id,{image:$p,onClose:Wp,returnFocusTo:ia}),jsx("div",{"data-ef-focus-ring":"self",style:TS,children:jsx(pd,{})})]})}i(kS,"ChatBody");function PS(e){let t=useRef({pending:[],byMessage:new Map}),r=useRef(e);r.current=e;let n=useCallback((a,s)=>{s.length!==0&&t.current.pending.push({text:a,images:s,before:new Set(r.current.map(l=>l.id))});},[]),o=useCallback(a=>{let s=t.current,l=s.byMessage.get(a.id);if(l!==void 0)return l;if(a.role!=="user")return ra;let u=s.pending.findIndex(c=>c.text===a.text&&!c.before.has(a.id));if(u<0)return ra;let[d]=s.pending.splice(u,1);return d===void 0?ra:(s.byMessage.set(a.id,d.images),d.images)},[]);return useMemo(()=>({record:n,imagesFor:o}),[n,o])}i(PS,"useSentImages");function _S(e){let t=dn(e.messages,e.isStreaming),[r,n]=useState({send:e.send,id:e.conversationId,text:""}),o=useRef(false),a=useRef({send:e.send,id:e.conversationId});return useEffect(()=>{let s=a.current;if((s.send!==e.send||s.id!==e.conversationId)&&(o.current=false),a.current={send:e.send,id:e.conversationId},o.current&&!e.isStreaming){let l=e.messages[e.messages.length-1];n({send:e.send,id:e.conversationId,text:l!==void 0&&l.role==="assistant"?l.text:""});}o.current=e.isStreaming;},[e.isStreaming,e.messages,e.send,e.conversationId]),t?h.typing:r.send===e.send&&r.id===e.conversationId?r.text:""}i(_S,"useReplyAnnouncement");function wS({petRef:e,pet:t,onRegistered:r}){let{styles:n}=fe(),o=Iu(e,t,r);return o.status!=="failed"||o.error===null?null:jsxs("div",{role:"alert",style:n.setupNotice,children:[jsx("span",{style:n.setupNoticeText,children:o.error.displayMessage}),jsx("button",{type:"button",onClick:o.retry,style:n.setupNoticeAction,children:h.retry})]})}i(wS,"PetSetupNotice");function MS(e){let{runtime:t,userRef:r,scopeEpoch:n}=X(),o=useMemo(()=>et(t.registry.services.authFor(r)),[t,r,n]),a=useMemo(()=>({repository:o,petRef:e}),[o,e]),[s,l]=useState({key:a,profile:null,loading:e!==null,error:null}),u=s.key===a?s:{profile:null,loading:e!==null,error:null},d=useRef(0),c=useCallback(async()=>{let p=++d.current;if(a.petRef===null){l({key:a,profile:null,loading:false,error:null});return}l(m=>({key:a,profile:m.key===a?m.profile:null,loading:true,error:null}));let f=await a.repository.getPetProfile(a.petRef);p===d.current&&l(f.ok?{key:a,profile:f.value,loading:false,error:null}:{key:a,profile:null,loading:false,error:f.error});},[a]);return useEffect(()=>(c(),()=>{d.current+=1;}),[c]),useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:c}),[u.profile,u.loading,u.error,c])}i(MS,"useEverfurPetProfile");function LS(e){return createElement(Zr,{clientTheme:e.clientTheme??null,seams:nn,children:e.children})}i(LS,"EverfurThemeProvider");export{Zo as CapabilityGate,Vp as EverfurChat,J as EverfurConfigError,Eh as EverfurProvider,LS as EverfurThemeProvider,Pr as EverfurThrownError,Dy as THEME_SLOT_KEYS,Ct as THEME_SLOT_NAMES,er as canonicalPetSpecies,Wn as categoryFor,Cm as conversationId,Wo as createLocalStorageKv,vn as createWebAttachmentTransport,qg as face,k as faceCss,En as fileToAttachmentHandle,Qp as isErr,Xp as isOk,Kn as isRetryableCode,vm as petRef,ug as previewTheme,Zp as unwrap,Ft as useCapability,on as useChatAttachments,eu as useEverfur,pr as useEverfurChat,MS as useEverfurPetProfile,cn as useEverfurPets,N as useEverfurTheme,At as userFacingError,Em as userRef};
14
+ ${r}`,a=cu.get(o);if(a===void 0){if(a=Promise.resolve(false),t!==null&&n!==""&&n!=="System"&&ih(t))try{let s=document.fonts;a=new FontFace(n,`url("${t}") format("woff2")`,{display:"swap",weight:r}).load().then(l=>(s.add(l),!0)).catch(()=>!1);}catch{}cu.set(o,a);}return a}i(ah,"loadBrandFont");var sh=["regular","medium","bold","mono","monoMedium","monoBold"];function pu(e){let{families:t,fontUrls:r,weight:n,namedFaces:o}=e.type;useEffect(()=>{for(let a of sh){let s=r[a];s!=null&&ah(t[a],s,o[a]?n.regular:n[pr[a]]);}},[t,r,n,o]);}i(pu,"useBrandFont");function fr(e){if(typeof window>"u"||typeof window.matchMedia!="function")return null;try{return window.matchMedia(e)??null}catch{return null}}i(fr,"queryFor");function qo(e){return t=>{let r=fr(e);return r===null||typeof r.addEventListener!="function"?()=>{}:(r.addEventListener("change",t),()=>r.removeEventListener?.("change",t))}}i(qo,"subscribeTo");var fu="(prefers-color-scheme: dark)",lh="(prefers-color-scheme: light)",mu="(prefers-reduced-motion: reduce)",yu="(prefers-contrast: more)",uh=qo(fu),dh=qo(mu),ch=qo(yu);function ph(){let e=fr(fu);return e===null?null:e.matches?"dark":fr(lh)?.matches?"light":null}i(ph,"readColorScheme");function fh(){return fr(mu)?.matches===true}i(fh,"readReducedMotion");function mh(){return fr(yu)?.matches===true}i(mh,"readMoreContrast");var yh=16,gh=false;var rn=null;function gu(e){return Number.parseFloat(window.getComputedStyle(e).fontSize)}i(gu,"fontPx");function hh(){let e=document.body??document.documentElement,t=document.createElement("span");t.setAttribute("aria-hidden","true"),t.style.setProperty("position","absolute","important"),t.style.setProperty("visibility","hidden","important"),t.style.setProperty("font-size","medium","important"),e.appendChild(t);try{return gu(t)}finally{t.remove();}}i(hh,"probeDefaultPx");function bh(){if(typeof document>"u"||typeof window>"u"||typeof window.getComputedStyle!="function")return 1;try{let e=gh?gu(document.documentElement):hh();return Number.isFinite(e)&&e>0?e/yh:1}catch{return 1}}i(bh,"measureTextScale");function vh(){return rn===null&&(rn=bh()),rn}i(vh,"readTextScale");function Eh(e){if(typeof window>"u"||typeof window.addEventListener!="function")return ()=>{};let t=i(()=>{rn=null,e();},"onResize");return window.addEventListener("resize",t),()=>window.removeEventListener("resize",t)}i(Eh,"subscribeTextScale");function Ch(){return useSyncExternalStore(uh,ph,()=>null)}i(Ch,"useWebColorScheme");function Rh(){return useSyncExternalStore(dh,fh,()=>false)}i(Rh,"useWebReducedMotion");function Sh(){return useSyncExternalStore(ch,mh,()=>false)}i(Sh,"useWebHighContrast");function xh(){return useSyncExternalStore(Eh,vh,()=>1)}i(xh,"useWebTextScale");var on=Object.freeze({useColorScheme:Ch,useReducedMotion:Rh,useTextScale:xh,useHighContrast:Sh,scaleTypeSizes:true,useResolvedTheme:pu});function kh(e){return e.storage===void 0?{...e,storage:Go()}:e}i(kh,"withWebDefaults");var Ph=Object.freeze({platform:"web",withDefaults:kh,theme:on});function _h(e){return createElement(uu,{...e,seams:Ph})}i(_h,"EverfurProvider");function Ft(e){let{runtime:t}=X(),r=t.entitlements,n=useSyncExternalStore(r.subscribe,r.getSnapshot,r.getSnapshot);return useMemo(()=>nl(e,n.decisions,{isPending:n.isPending}),[e,n])}i(Ft,"useCapability");var Xo=class Xo extends Component{constructor(){super(...arguments);this.state={failed:false,key:this.props.resetKey};}static getDerivedStateFromError(){return {failed:true}}static getDerivedStateFromProps(r,n){return Object.is(r.resetKey,n.key)?null:{failed:false,key:r.resetKey}}render(){return this.state.failed?this.props.fallback:this.props.children}};i(Xo,"HostRenderBoundary");var Yo=Xo;function Oh({render:e}){return e()}i(Oh,"RenderHost");function xt({render:e,fallback:t,resetKey:r}){return createElement(Yo,{fallback:t,resetKey:r,children:createElement(Oh,{render:e})})}i(xt,"HostRender");function Qo(e,t,r){return Math.round(r*du(e,t)*10)/10}i(Qo,"tierPx");var bu='system-ui, -apple-system, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',Fh="System";function Zo(e){let t=e.trim();return t.length===0||t===Fh?bu:`${vu(t)}, ${bu}`}i(Zo,"cssFontFamily");function Mh(e){let t=e.trim();return t.length===0||t==="monospace"?"ui-monospace, Menlo, Consolas, monospace":`${vu(t)}, ui-monospace, Menlo, Consolas, monospace`}i(Mh,"cssMonoFamily");function vu(e){return `"${e.replace(/[\\"]/g,"\\$&")}"`}i(vu,"quote");function P(e,t){let r=e.type,n=r.families[t];return {fontFamily:t==="mono"||t==="monoMedium"||t==="monoBold"?Mh(n):Zo(n),fontWeight:r.namedFaces[t]?r.weight.regular:r.weight[pr[t]]}}i(P,"faceCss");var Mt=Object.freeze({textAlign:"start"});var Dh=48;function Lh(e){return e.isPending?"pending":e.enabled?"enabled":"disabled"}i(Lh,"selectView");function ei(e){let{capability:t,children:r,renderDisabled:n,renderPending:o,style:a,className:s}=e,l=Ft(t),u=useMemo(()=>Lh(l),[l]);switch(u){case "enabled":return r;case "pending":return o?jsx(xt,{render:o,fallback:jsx(Eu,{capability:t,style:a,className:s})}):jsx(Eu,{capability:t,style:a,className:s});case "disabled":return n?jsx(xt,{render:()=>n(l),fallback:jsx(Cu,{decision:l,style:a,className:s}),resetKey:l}):jsx(Cu,{decision:l,style:a,className:s});default:return Je(u)}}i(ei,"CapabilityGate");function Eu({capability:e,style:t,className:r}){let n=N(),o=useMemo(()=>Ru(n),[n]);return jsx("div",{role:"status","aria-busy":"true","aria-label":`Loading ${e}`,className:r,style:{...o.offstate,...t},children:jsx("div",{style:o.skeletonBar})})}i(Eu,"PendingSkeleton");function Cu({decision:e,style:t,className:r}){let n=N(),o=useMemo(()=>Ru(n),[n]),a=e.disabled?.reason??"";return jsx("div",{className:r,style:{...o.offstate,...t},children:a.length>0?jsx("p",{style:o.offstateText,children:a}):null})}i(Cu,"OffState");function Ru(e){let{color:t,space:r,radius:n,type:o}=e;return {offstate:{...Mt,boxSizing:"border-box",minHeight:Dh,display:"flex",flexDirection:"column",justifyContent:"center",padding:`${r.md}px ${r.lg}px`,backgroundColor:t.surfaceCream,borderRadius:n.md,border:`1px solid ${t.brandBorder}`},offstateText:{margin:0,...P(e,"regular"),fontSize:o.size.body,lineHeight:`${Math.round(o.size.body*o.lineHeight.normal)}px`,color:t.text.muted},skeletonBar:{height:r.md,borderRadius:n.xs,backgroundColor:t.brandSofter}}}i(Ru,"makeStyles");var h=Object.freeze({placeholder:"Ask me anything!",send:"Send",stop:"Stop",retry:"Try again",followUps:"Helpful follow-ups",poweredBy:"powered by everfur",senderUser:"You",senderAssistant:"Assistant",typing:"Assistant is typing",loading:"Loading",empty:"No messages yet",transcript:"Conversation",emptyTitle:"What can we help {petName} with today?",emptyTitlePetFallback:"your pet",copied:"Copied",copyUserMessage:"Copy your message",copyAssistantMessage:"Copy assistant message",feedbackHelpful:"Helpful",feedbackNeutral:"Neutral",feedbackNotHelpful:"Not helpful",feedbackTitle:"What went wrong?",feedbackSubtitle:"Your feedback helps make answers more reliable.",feedbackReasonInaccurate:"Inaccurate",feedbackReasonOutdated:"Out of date",feedbackReasonUnsafe:"Unsafe advice",feedbackReasonUnclear:"Confusing or unclear",feedbackReasonOther:"Something else",feedbackNotesPlaceholder:"Add details (optional)",feedbackSubmit:"Submit feedback",feedbackSkip:"Skip",feedbackSkipA11y:"Skip feedback",feedbackThanks:"Thanks for the feedback",feedbackFailed:"Couldn't send feedback. Please try again.",turnFailedTitle:"Message failed",turnRetry:"Retry",turnUnreachableTitle:"Couldn't reach this chat",turnStartNewChat:"Start a new chat",reconnecting:"Reconnecting\u2026",turnStoppedTitle:"Response stopped",turnStoppedBody:"You stopped this response before it finished. Tap retry to try again.",sourceSingular:"source",sourcePlural:"sources",showSources:"Show",hideSources:"Hide",openSource:"Open source",urgencyGeneralReason:"Just general info about {petName}. Nothing here needs action right now.",findVet:"Find a vet",findVetA11y:"Find a vet near you",showLatestVetAlert:"Show latest vet alert",dismissBanner:"Dismiss {label} banner",openMenu:"Open menu",openMenuUnread:"Open menu, unread chats",yourPets:"Your Pets",yourPet:"Your pet",switchActivePet:"Switch active pet, {name}",petCurrentlyActive:"{name}, currently active",switchToPet:"Switch to {name}",activePrefix:"Active \xB7 ",close:"Close",addAnotherPet:"Add another pet",addPet:"Add a pet",attachmentPhoto:"Photo",attachmentCamera:"Camera",closeAttachmentPicker:"Close attachment picker",addAttachment:"Add attachment, {used} of {total} used",attachmentsFull:"Attachments full, {used} of {total} used",retryUpload:"Retry uploading {filename}",removeAttachment:"Remove {filename}",previewAttachment:"Preview {filename}",closePreview:"Close preview",attachedImage:"Attached image: {filename}, opens a full-screen preview",attachmentTooLarge:"Files must be under {max}. {filename} is {size}.",attachmentTooMany:"You can attach up to {max} files per message.",attachmentUnsupported:"{filename} isn't a supported file type yet.",attachmentNetwork:"Couldn't reach the server. Check your connection and try again.",attachmentServer:"Upload failed{status}. Please try again.",attachmentCancelled:"Upload cancelled.",attachmentRateLimited:"Slow down. Please wait a moment and try again.",attachmentQuota:"Daily image limit reached. Try again tomorrow.",attachmentConflict:"Something went wrong. Tap to retry.",attachmentUnknown:"Something went wrong. Please try again.",attachmentsFailedBlocked:"Some attachments failed to upload. Remove or retry them before sending.",dictate:"Dictate a message",stopDictation:"Stop dictation",listening:"Listening",micBlocked:"Microphone access is blocked. Allow it in your browser settings to dictate.",noSpeech:"We didn't catch that. Tap the mic and try again.",dictationUnavailable:"Voice typing isn't available right now."});function K(e,t){return e.replace(/\{(\w+)\}/g,(r,n)=>{let o=t[n];return o===void 0?r:String(o)})}i(K,"fillCopy");var ti=Object.freeze([Object.freeze({key:"inaccurate",label:h.feedbackReasonInaccurate,feedbackType:"wrong"}),Object.freeze({key:"outdated",label:h.feedbackReasonOutdated,feedbackType:"outdated"}),Object.freeze({key:"unsafe",label:h.feedbackReasonUnsafe,feedbackType:"dangerous"}),Object.freeze({key:"unclear",label:h.feedbackReasonUnclear,feedbackType:"unclear"}),Object.freeze({key:"other",label:h.feedbackReasonOther,feedbackType:"not_helpful"})]),Su=Object.freeze([Object.freeze({sentiment:"up",label:h.feedbackHelpful}),Object.freeze({sentiment:"neutral",label:h.feedbackNeutral}),Object.freeze({sentiment:"down",label:h.feedbackNotHelpful})]);function Nh(e){switch(e){case "up":return "helpful";case "neutral":return "neutral";case "down":return "not_helpful"}}i(Nh,"sentimentToFeedbackType");function xu(e,t){if(e==="down"&&t!==null){let r=ti.find(n=>n.key===t);if(r!==void 0)return r.feedbackType}return Nh(e)}i(xu,"feedbackTypeFor");var Bh=Object.freeze({status:"idle",messages:Object.freeze([]),conversationId:null,error:null,isStreaming:false,isBootstrapping:true,suggestedPrompts:Object.freeze([]),unreadCount:null});function mr(e){let{runtime:t,userRef:r,activePet:n,scopeEpoch:o}=X(),a=e?.petRef??n??null,s=e?.conversationId??null,l=useMemo(()=>({runtime:t,userRef:r,petRef:a,conversationId:s,scopeEpoch:o}),[t,r,a,s,o]),[u,c]=useState(null),d=u?.scope===l?u.controller:t.registry.peekChat({userRef:r,petRef:a,conversationId:s}),p=useRef(null);useEffect(()=>{let k=t.registry.acquireChat({userRef:r,petRef:a,conversationId:s});return p.current=k,c({scope:l,controller:k}),()=>{p.current=null,c(v=>v?.controller===k?null:v),t.registry.releaseChat(k);}},[t,r,a,s,o,l]);let f=useCallback(k=>d?d.subscribe(k):jh,[d]),m=useCallback(()=>d?d.getSnapshot():Bh,[d]),y=useSyncExternalStore(f,m,m),R=useCallback((k,v)=>d&&p.current===d&&!d.getSnapshot().isBootstrapping?ni(d,d.send(k,v?.imageS3Keys===void 0?{}:{imageS3Keys:v.imageS3Keys}),()=>p.current===d):Promise.resolve(oi()),[d]),b=useCallback(k=>d&&p.current===d&&!d.getSnapshot().isBootstrapping?ni(d,d.askEverfur(k),()=>p.current===d):Promise.resolve(oi()),[d]),T=useCallback(()=>d&&p.current===d?ni(d,d.retryLast(),()=>p.current===d):Promise.resolve(oi()),[d]),x=useCallback(()=>{d&&p.current===d&&d.stop();},[d]),_=useCallback(()=>{d&&p.current===d&&d.newConversation();},[d]),[w,g]=useState({controller:null,byMessage:{}}),S=w.controller===d?w.byMessage:Vh,I=useCallback(async(k,v,C,A)=>{if(!d||p.current!==d)return E(D("accessDenied"));let F=String(k),B=w.controller===d?w.byMessage[F]:void 0;if(B===v&&C==null)return g(Z=>{let q={...Z.controller===d?Z.byMessage:{}};return delete q[F],{controller:d,byMessage:q}}),M(Object.freeze({feedbackId:""}));g(Z=>({controller:d,byMessage:{...Z.controller===d?Z.byMessage:{},[F]:v}}));let V=await d.submitFeedback(k,xu(v,C??null),A??null);return p.current!==d?E(D("accessDenied")):(V.ok||g(Z=>{let q={...Z.controller===d?Z.byMessage:{}};return B===void 0?delete q[F]:q[F]=B,{controller:d,byMessage:q}}),V)},[d,w]),O=useMemo(()=>{let k=i(async v=>{if(!d||p.current!==d)return E(D("accessDenied"));let C=await v(d);return p.current===d?C:E(D("accessDenied"))},"run");return {listConversations:i(v=>k(C=>C.listConversations({...a?{petRef:a}:{},...v})),"listConversations"),getMessages:i((v,C)=>k(A=>A.getMessages(v,C)),"getMessages"),resumeConversation:i(v=>k(C=>C.resumeConversation(v)),"resumeConversation"),loadOlderMessages:i(()=>k(v=>v.loadOlderMessages()),"loadOlderMessages"),markRead:i(()=>k(v=>v.markRead()),"markRead"),refreshActiveThread:i(()=>k(v=>v.refreshActiveThread()),"refreshActiveThread"),answerCheckin:i((v,C)=>k(A=>A.answerCheckin(v,C)),"answerCheckin"),openCheckin:i(v=>k(C=>C.openCheckin(v)),"openCheckin")}},[d,a]);return useMemo(()=>({status:y.status,messages:y.messages,conversationId:y.conversationId,petRef:a,error:y.error,isStreaming:y.isStreaming,isBootstrapping:y.isBootstrapping,historyCursor:y.historyCursor??null,isLoadingHistory:y.isLoadingHistory??false,stopped:y.stopped??false,reconnecting:y.reconnecting??false,...O,suggestedPrompts:y.suggestedPrompts,unreadCount:y.unreadCount,hasUnreadThreads:y.hasUnreadThreads??false,newConversation:_,sentimentByMessage:S,feedback:I,send:R,askEverfur:b,retryLast:T,stop:x}),[y,a,R,b,T,x,O,_,S,I])}i(mr,"useEverfurChat");var jh=i(()=>{},"NOOP_UNSUBSCRIBE"),Vh=Object.freeze({});async function ni(e,t,r){for await(let o of t);if(!r())return E(D("accessDenied"));let n=e.getSnapshot();return n.status==="error"&&n.error!==null?E(n.error):M($h(n.messages))}i(ni,"driveToResult");function $h(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r&&r.role==="assistant"&&r.responseId!==void 0)return r.responseId}return null}i($h,"lastAssistantResponseId");function oi(){return E(D("internalError",{retryable:true}))}i(oi,"notReadyError");function _u(e){switch(e.code){case "too_large":return K(h.attachmentTooLarge,{max:vo(Br),filename:e.filename,size:vo(e.sizeBytes??0)});case "too_many":return K(h.attachmentTooMany,{max:jr});case "unsupported_type":return K(h.attachmentUnsupported,{filename:e.filename});case "network":return h.attachmentNetwork;case "server":return K(h.attachmentServer,{status:e.httpStatus?` (${e.httpStatus})`:""});case "cancelled":return h.attachmentCancelled;case "rate_limited":return h.attachmentRateLimited;case "quota_exceeded":return h.attachmentQuota;case "idempotency_conflict":return h.attachmentConflict;case "unknown":return h.attachmentUnknown}}i(_u,"attachmentErrorMessage");function wu(e,t){return K(e>=t?h.attachmentsFull:h.addAttachment,{used:e,total:t})}i(wu,"attachControlLabel");var qh=Object.freeze({attachments:Object.freeze([])});function an(e={}){let{runtime:t,userRef:r,scopeEpoch:n}=X(),o=e.maxPerMessage??jr,a=useCallback(()=>{let{services:g}=t.registry;return As({funnel:Te({auth:g.authFor(r),...g.errorPolicy?{errorPolicy:g.errorPolicy}:{}}),transport:e.transport??g.uploadTransport,maxPerMessage:o})},[t,r,n,o,e.transport]),s=useMemo(()=>e.queue??a(),[e.queue,a]),l=useRef(new WeakSet),[u,c]=useState(null),d=u!==null&&u.of===s?u.queue:s;useEffect(()=>{if(d!==e.queue){if(l.current.has(d)){c({of:s,queue:a()});return}return ()=>{d.dispose(),l.current.add(d);}}},[d,s,a,e.queue]);let p=useSyncExternalStore(d.subscribe,d.getSnapshot,()=>qh),[f,m]=useState(null),y=useCallback(g=>{let I=(Array.isArray(g)?g:[g]).map(k=>d.add(k)),O=I.find(k=>!k.ok);return O!==void 0&&!O.ok&&m(O.error),I},[d,m]),R=useCallback(g=>d.retry(g),[d]),b=useCallback(g=>d.remove(g),[d]),T=useCallback(()=>d.clear(),[d]),x=useCallback(()=>m(null),[m]),_=p.attachments.some(g=>g.status==="uploading"),w=p.attachments.some(g=>g.status==="failed");return useMemo(()=>({available:d.available,attachments:p.attachments,maxPerMessage:o,uploading:_,failed:w,blocked:_||w,s3Keys:p.attachments.flatMap(g=>g.status==="uploaded"&&g.s3Key!==null?[g.s3Key]:[]),rejected:f,add:y,retry:R,remove:b,clear:T,dismissRejected:x}),[d.available,p,o,_,w,f,y,R,b,T,x])}i(an,"useChatAttachments");var Qh="pet_not_registered";function Ou(e){return e!=null&&e.reasonCode===Qh}i(Ou,"isPetNotRegistered");var Zh=Object.freeze({status:"idle",error:null,registered:null,retry:i(()=>{},"retry")});function Fu(e,t,r){let{runtime:n,userRef:o,scopeEpoch:a}=X(),s=useCallback(()=>et(n.registry.services.authFor(o)),[n,o,a]),l=useMemo(()=>t===void 0?null:ai(t),[t]),[u,c]=useState({key:null,status:"idle",error:null,registered:null}),d=useRef(0),p=useRef(r);p.current=r;let f=e===null||l===null?null:`${String(o)}|${a}|${e}|${l}`,m=useCallback(()=>{if(e===null||t===void 0||f===null)return;let R=++d.current;c({key:f,status:"registering",error:null,registered:null}),s().registerPet(e,t).then(b=>{R===d.current&&(b.ok?(c({key:f,status:"registered",error:null,registered:b.value}),p.current?.()):c({key:f,status:"failed",error:b.error,registered:null}));});},[s,e,f]);useEffect(()=>{if(f===null){d.current+=1;return}return m(),()=>{d.current+=1;}},[f,m]);let y=useCallback(()=>{u.status==="failed"&&m();},[u.status,m]);return useMemo(()=>f===null?Zh:u.key!==f?{status:"registering",error:null,registered:null,retry:y}:{status:u.status,error:u.error,registered:u.registered,retry:y},[f,u,y])}i(Fu,"useChatPetRegistration");function ai(e){return e===null||typeof e!="object"?JSON.stringify(e)??"undefined":Array.isArray(e)?`[${e.map(ai).join(",")}]`:`{${Object.entries(e).filter(([,r])=>r!==void 0).sort(([r],[n])=>r<n?-1:r>n?1:0).map(([r,n])=>`${JSON.stringify(r)}:${ai(n)}`).join(",")}}`}i(ai,"stableKey");var eb=500;function si(e){if(!e)return null;let t=e.replace(/[\u0000-\u001F\u007F-\u009F\u200E\u200F\u202A-\u202E\u2066-\u2069\uFEFF]/g," ").replace(/\s+/g," ").trim();return t?t.slice(0,eb):null}i(si,"sanitizeSeedPrompt");function Du(e,t,r){let n=si(r),o=useRef(e);o.current=e;let a=useRef(null);useEffect(()=>{if(n===null||t||a.current===n)return;let s=o.current;s!==void 0&&(a.current=n,Promise.resolve(s(n)).catch(()=>{}));},[n,t]);}i(Du,"useInitialAsk");function tb(e,t,r){if(e==="announced")return false;let n=r.lastRefresh;return n===null||n.conversationId!==t?false:r.now-n.at<15e3}i(tb,"isCoalesced");function Lu(e,t){let r=t.activeConversationId;return r===null||r.length===0?{action:"skip",reason:"no_thread"}:t.isTurnInFlight?{action:"defer",reason:"turn_in_flight"}:t.isOffline?{action:"defer",reason:"offline"}:tb(e,r,t)?{action:"skip",reason:"coalesced"}:{action:"refresh",conversationId:r}}i(Lu,"decideChatRefresh");function li(e){let t=globalThis.console;try{t?.error?.("[everfur] A host callback threw; the SDK ignored it.",e);}catch{}}i(li,"reportHostFailure");function rb(e){return (typeof e=="object"||typeof e=="function")&&e!==null&&typeof e.then=="function"}i(rb,"isThenable");function se(e,...t){if(typeof e=="function")try{let r=e(...t);return rb(r)&&Promise.resolve(r).then(void 0,li),r}catch(r){li(r);return}}i(se,"callHost");function Nu(e,...t){let r;try{r=e(...t);}catch(n){return li(n),Promise.resolve({ok:false,error:n})}return Promise.resolve(r).then(n=>({ok:true,value:n}),n=>({ok:false,error:n}))}i(Nu,"callHostAsync");function Uu(e,t){let r=useRef(t);r.current=t;let n=useRef(null),o=useRef(null),a=e?.isOffline===void 0?false:se(()=>e.isOffline?.()===!0)===true,s=useRef(()=>{});s.current=l=>{let{conversationId:u,isTurnInFlight:c,refresh:d}=r.current,p=Lu(l,{activeConversationId:u,isTurnInFlight:c,isOffline:a,lastRefresh:n.current,now:Date.now()});if(p.action!=="skip"){if(p.action==="defer"){o.current!=="announced"&&(o.current=l);return}o.current=null,n.current={conversationId:p.conversationId,at:Date.now()},d!==void 0&&Promise.resolve(d()).catch(()=>{});}},useEffect(()=>{if(t.isTurnInFlight||a)return;let l=o.current;l!==null&&s.current(l);},[t.isTurnInFlight,a]),useEffect(()=>{if(e===void 0)return;let l=[],u=i((c,d)=>{if(c===void 0)return;let p=se(()=>c(()=>{s.current(d);}));typeof p=="function"&&l.push(p);},"subscribe");return u(e.onForeground?.bind(e),"foreground"),u(e.onOnline?.bind(e),"foreground"),u(e.onAnnounced?.bind(e),"announced"),()=>{for(let c of l)se(c);}},[e]);}i(Uu,"useChatLifecycle");function ob(e){if(e===void 0)return null;let t=e.conversationId??"",r=e.petRef??"";return t===""&&r===""?null:`${String(t)}|${String(r)}`}i(ob,"targetKey");function Bu(e,t){let r=ob(t),n=useRef({openCheckin:e,target:t});n.current={openCheckin:e,target:t};let o=useRef(null);useEffect(()=>{if(r===null||o.current===r)return;o.current=r;let{openCheckin:a,target:s}=n.current;a===void 0||s===void 0||Promise.resolve(a(s)).catch(()=>{});},[r]);}i(Bu,"useCheckinTarget");var W=Object.freeze({heading:"Chat History",empty:"No chats yet",emptyBody:"Start a new conversation to see it here.",noMatch:"No matching chats",noMatchBody:"Try a different title or start a new conversation.",loading:"Loading your chats\u2026",loadFailed:"Couldn\u2019t load your chats",loadingMore:"Loading more\u2026",untitled:"New conversation",newConversation:"New conversation",newChat:"New chat",search:"Search",retry:"Try again",retryA11y:"Retry loading chats",close:"Close",closeA11y:"Close history",more:"Load more",earlier:"Load earlier messages",loadingEarlier:"Loading earlier messages\u2026",openConversation:"Open conversation",unreadPrefix:"Unread. "});function ln(e){let t=e?.replace(/\s+/g," ").trim();return t||W.untitled}i(ln,"conversationTitle");function Vu(e){return `${e.unreadCount!==null&&e.unreadCount>0?W.unreadPrefix:""}${W.openConversation} ${ln(e.title)}`}i(Vu,"openConversationLabel");function ju(e){return e.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[\u2018\u2019]/g,"'").replace(/[\u201c\u201d]/g,'"').toLowerCase().trim().replace(/\s+/g," ")}i(ju,"normalizeForSearch");function ub(e,t){let r=ju(t);if(r.length===0)return e;let n=[[],[],[]];for(let o of e){let a=ju(ln(o.title)),s=a.indexOf(r);if(s<0)continue;let l=s===0?0:a.charAt(s-1)===" "?1:2;n[l]?.push(o);}return n.flat()}i(ub,"filterConversations");function di(e){return {scope:e,rows:[],cursor:null,loading:false,loadingMore:false,error:null}}i(di,"fresh");function $u(e){let[t,r]=useState(false),[n,o]=useState(""),a=e.listConversations,s=useRef(0),[l,u]=useState(()=>di(a)),c=l.scope===a?l:di(a);useEffect(()=>(s.current+=1,r(false),o(""),u(di(a)),()=>{s.current+=1;}),[a]);let d=useCallback(async _=>{let w=++s.current,g=_!==void 0;u(I=>({...I,scope:a,loading:!g,loadingMore:g,error:null}));let S=await e.listConversations(_?{cursor:_}:void 0);if(w===s.current){if(!S.ok){u(I=>({...I,loading:false,loadingMore:false,error:S.error.displayMessage}));return}u(I=>{let O=_&&I.scope===a?I.rows:[],k=new Set(O.map(v=>v.id));return {scope:a,loading:false,loadingMore:false,error:null,rows:[...O,...S.value.conversations.filter(v=>!k.has(v.id))],cursor:S.value.nextCursor===_?null:S.value.nextCursor}});}},[e.listConversations,a]),p=i(()=>{r(true),o(""),d();},"show"),f=i(()=>{s.current+=1,r(false);},"close"),m=i(async _=>{let w=++s.current;u(S=>({...S,loading:true,error:null}));let g=await e.resumeConversation(_);w===s.current&&(u(S=>({...S,loading:false,error:g.ok?null:g.error.displayMessage})),g.ok&&r(false));},"resume"),y=i(async()=>{let _=s.current,w=await e.loadOlderMessages();_===s.current&&!w.ok&&u(g=>({...g,error:w.error.displayMessage}));},"earlier"),R=i(()=>{e.newConversation(),s.current+=1,r(false);},"newConversation"),b=i(()=>{c.cursor===null||c.loading||c.loadingMore||n.trim().length>0||d(c.cursor);},"loadMore"),T=useMemo(()=>ub(c.rows,n),[c.rows,n]),x=n.trim().length>0;return {...c,open:t,show:p,close:f,load:d,resume:m,earlier:y,newConversation:R,loadMore:b,query:n,setQuery:o,searching:x,filtered:T,emptyKind:c.rows.length===0?"empty":"noMatch"}}i($u,"useHistoryPanel");var un="#111111",dn="#FFFFFF",pb=Object.freeze({emergency:Object.freeze({level:"emergency",label:"Vet care now",borderColor:"#FCA5A5",backgroundColor:"#FEF2F2",textColor:"#991B1B",reasonColor:un,pillColor:dn,showsVetAction:true}),schedule_soon:Object.freeze({level:"schedule_soon",label:"Vet care suggested soon",borderColor:"#FCD34D",backgroundColor:"#FFFBEB",textColor:"#92400E",reasonColor:un,pillColor:dn,showsVetAction:true}),home_care:Object.freeze({level:"home_care",label:"Monitor at home",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:un,pillColor:dn,showsVetAction:false}),general:Object.freeze({level:"general",label:"Good to know",borderColor:"#86EFAC",backgroundColor:"#F0FDF4",textColor:"#166534",reasonColor:un,pillColor:dn,showsVetAction:false})});function fb(e){return `${e.messageId}:${e.level}:${e.reason??""}`}i(fb,"urgencySignature");function mb(e){return K(h.urgencyGeneralReason,{petName:e?.trim()||h.emptyTitlePetFallback})}i(mb,"generalUrgencyReason");function Gu(e,t){for(let r=e.length-1;r>=0;r-=1){let n=e[r];if(n?.role!=="assistant"||n.responseId===void 0)continue;let o=n.urgencyLevel;return o?{messageId:n.id,level:o,reason:n.urgencyReason??null}:n.urgencyProvided===true?{messageId:n.id,level:"general",reason:mb(t)}:null}return null}i(Gu,"latestUrgencySource");function qu(e){let t=e===null?null:fb(e),[r,n]=useState(null),[o,a]=useState(false);useEffect(()=>a(false),[t]);let l=e!==null&&(o||!(r!==null&&r===t)),u=e===null?null:pb[e.level],c=e!==null&&!l&&e.level!=="general",d=useCallback(()=>{t!==null&&n(t),a(false);},[t]),p=useCallback(()=>a(true),[]);return useMemo(()=>({source:e,tier:u,signature:t,showBanner:l,showCompactIcon:c,showVetAction:l&&u!==null&&u.showsVetAction,dismissLabel:u===null?null:K(h.dismissBanner,{label:u.label}),dismiss:d,expand:p}),[e,u,t,l,c,d,p])}i(qu,"useUrgencySurface");function Yu(e){return e.isBootstrapping?"loading":e.status==="error"&&e.error&&e.messages.length===0?"error":e.messages.length===0?"empty":"populated"}i(Yu,"selectView");function yb(e){return e.code==="accessDenied"||e.code==="conversationNotFound"}i(yb,"needsNewConversation");function Xu(e){if(e.messages.length===0)return null;let t=e.status==="error"?e.error:null;if(t!==null){let r=yb(t);return {tone:"error",title:r?h.turnUnreachableTitle:h.turnFailedTitle,body:t.displayMessage,actionLabel:r?h.turnStartNewChat:h.turnRetry,action:r?"startNew":"retry"}}return e.stopped===true?{tone:"neutral",title:h.turnStoppedTitle,body:h.turnStoppedBody,actionLabel:h.turnRetry,action:"retry"}:null}i(Xu,"turnNotice");function cn(e,t){let r=e[e.length-1];return t&&(r===void 0||r.role==="user")}i(cn,"awaitingAssistant");function Qu(e,t){let r={};return e!==void 0&&(r.petRef=e),t!==void 0&&(r.conversationId=t),r}i(Qu,"buildChatOpts");function pn(){let{runtime:e,userRef:t,activePet:r,scopeEpoch:n}=X(),o=useMemo(()=>et(e.registry.services.authFor(t)),[e,t,n]),[a,s]=useState({repository:o,pets:[],loading:true,error:null}),l=a.repository===o?a:{pets:[],loading:true,error:null},u=useRef(0),c=useCallback(async()=>{let p=++u.current;s(m=>({...m,repository:o,loading:true,error:null,pets:m.repository===o?m.pets:[]}));let f=await o.list();p===u.current&&s(f.ok?{repository:o,pets:f.value,loading:false,error:null}:m=>({repository:o,pets:m.repository===o?m.pets:[],loading:false,error:f.error}));},[o]);useEffect(()=>(c(),()=>{u.current+=1;}),[c]);let d=useMemo(()=>r===null?null:l.pets.find(p=>p.petRef===r)??null,[r,l.pets]);return useMemo(()=>({pets:l.pets,activePet:d,loading:l.loading,error:l.error,refresh:c}),[l.pets,l.loading,l.error,d,c])}i(pn,"useEverfurPets");function Zu(e,t){if(t!==null){let r=e.find(n=>n.petRef===t);if(r!==void 0)return r}return e[0]??null}i(Zu,"headerPetOf");var it=Object.freeze({position:"absolute",width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",border:0});var yr=2,Cb="data-ef-focus-ring",Ju="data-ef-focus-ring-color";function pi(e){return {outline:`${yr}px solid ${e}`,outlineOffset:yr}}i(pi,"focusRingStyle");var mn=false,fn=0;function ed(e){e.metaKey||e.ctrlKey||e.altKey||(mn=true);}i(ed,"onKeyDown");function Lt(){mn=false;}i(Lt,"onPointerDown");function Rb(){return typeof document>"u"?()=>{}:(fn===0&&(document.addEventListener("keydown",ed,true),document.addEventListener("pointerdown",Lt,true),document.addEventListener("mousedown",Lt,true),document.addEventListener("touchstart",Lt,true)),fn+=1,()=>{fn-=1,!(fn>0)&&(document.removeEventListener("keydown",ed,true),document.removeEventListener("pointerdown",Lt,true),document.removeEventListener("mousedown",Lt,true),document.removeEventListener("touchstart",Lt,true),mn=false);})}i(Rb,"bindModality");var Sb=new Set(["","text","search","email","tel","url","password","number"]);function xb(e){return e.tagName==="TEXTAREA"||e.isContentEditable?true:e.tagName!=="INPUT"?false:Sb.has((e.getAttribute("type")??"").toLowerCase())}i(xb,"isTextField");function td(e,t){useEffect(()=>{let r=e.current;if(r===null)return;let n=Rb(),o=new Map,a=i(l=>{let u=l.target;if(!(u instanceof HTMLElement)||o.has(u)||u.closest(`[${Cb}="self"]`)!==null||!mn&&!xb(u))return;o.set(u,{outline:u.style.outline,outlineOffset:u.style.outlineOffset});let c=u.closest(`[${Ju}]`),d=pi(c?.getAttribute(Ju)||t);u.style.outline=d.outline,u.style.outlineOffset=`${d.outlineOffset}px`;},"onFocusIn"),s=i(l=>{let u=l.target;if(!(u instanceof HTMLElement))return;let c=o.get(u);c!==void 0&&(o.delete(u),u.style.outline=c.outline,u.style.outlineOffset=c.outlineOffset);},"onFocusOut");return r.addEventListener("focusin",a),r.addEventListener("focusout",s),()=>{r.removeEventListener("focusin",a),r.removeEventListener("focusout",s);for(let[l,u]of o)l.style.outline=u.outline,l.style.outlineOffset=u.outlineOffset;o.clear(),n();}},[e,t]);}i(td,"useKeyboardFocusRing");var fi=Object.freeze({title:"For educational use only",body:"Everfur is for educational purposes only. It helps you track visible changes through AI checkups. It does not diagnose, treat, prescribe, or replace veterinary care. For urgent symptoms or emergencies, contact a veterinarian immediately."});function nd(e){let t=N(),r=useMemo(()=>kb(t),[t]);return jsxs("div",{role:"note",className:e.className,style:{...r.container,...e.style},children:[jsx("p",{style:r.title,children:fi.title}),jsx("p",{style:r.body,children:fi.body})]})}i(nd,"ClinicalDisclaimer");function kb(e){let{color:t,space:r,type:n}=e,o=`${Math.round(n.size.caption*n.lineHeight.snug)}px`;return {container:{...Mt,boxSizing:"border-box",display:"flex",flexDirection:"column",gap:r.xs,padding:`${r.md}px ${r.lg}px`,borderTop:`1px solid ${t.borderHairlineGreen}`,backgroundColor:t.surfaceCream},title:{margin:0,...P(e,"bold"),fontSize:n.size.caption,lineHeight:o,color:t.text.secondary,letterSpacing:n.letterSpacing.eyebrow},body:{margin:0,...P(e,"regular"),fontSize:n.size.caption,lineHeight:o,color:t.text.muted}}}i(kb,"makeStyles");function od(e,t){let r={entry:"chat",petRef:e};return t?.returnTo!==void 0&&(r.returnTo=t.returnTo),t?.usState!==void 0&&(r.usState=t.usState),t?.prefer!==void 0&&(r.prefer=t.prefer),r}i(od,"chatVetVisitOptions");var id=Symbol.for("@everfur/sdk/televet");function Ge(){let e=globalThis,t=e[id];if(t!==void 0)return t;let r={presenter:null,snapshot:Object.freeze({request:null,serial:0,activeHost:null}),hosts:[],nextHost:1,listeners:new Set,dailyRegistered:false};return e[id]=r,r}i(Ge,"televetGlobal");function yn(e){let t=Ge();t.snapshot=Object.freeze({...t.snapshot,...e});for(let r of [...t.listeners])try{r();}catch{}}i(yn,"publish");function ad(e){let t=Ge().presenter;if(t===null)return "absent";try{return t(e)===!1?"declined":"presented"}catch(r){return console.warn("[everfur] Your registerEverfurTelevetFlow presenter threw; the in-app visit opened instead.",r),"threw"}}i(ad,"callTelevetPresenter");function sd(e){let t=Ge();return t.listeners.add(e),()=>{t.listeners.delete(e);}}i(sd,"subscribeTelevetExperience");function mi(){return Ge().snapshot}i(mi,"televetExperienceSnapshot");function _b(){return Ge().hosts.length>0}i(_b,"hasTelevetHost");function ld(e){if(!_b())return false;let t=Object.freeze({...e});return yn({request:t,serial:Ge().snapshot.serial+1}),true}i(ld,"presentTelevetExperience");function yi(){Ge().snapshot.request!==null&&yn({request:null});}i(yi,"dismissTelevetExperience");function ud(){let e=Ge(),t=e.nextHost;return e.nextHost+=1,e.hosts=[...e.hosts,t],yn({activeHost:e.hosts[0]??null}),t}i(ud,"claimTelevetHost");function dd(e){let t=Ge();t.hosts=t.hosts.filter(n=>n!==e);let r=t.hosts[0]??null;yn(r===null?{activeHost:r,request:null}:{activeHost:r});}i(dd,"releaseTelevetHost");function fd(e){let t=null;return ()=>{if(t!==null)return t;let r=e();return t=r,r.then(void 0,()=>{t===r&&(t=null);}),r}}i(fd,"memoizeTelevetLoader");function md(e){let[t,r]=useState(null);useEffect(()=>{let c=ud();return r(c),()=>{dd(c);}},[]);let n=useSyncExternalStore(sd,mi,mi),a=t!==null&&n.activeHost===t?n.request:null,[s,l]=useState(null),u=a!==null&&s===null;return useEffect(()=>{if(!u)return;let c=true;return e().then(d=>{c&&l(()=>d);},d=>{c&&(console.warn("[everfur] The in-app vet visit could not load its screens.",d),yi());}),()=>{c=false;}},[u,e]),a===null||s===null?null:{module:s,request:a,serial:n.serial,dismiss:yi}}i(md,"useTelevetExperienceHost");var Ib=fd(()=>import('@everfur/sdk/web/televet/booking'));function yd({onAddToCalendar:e}){let t=md(Ib);if(t===null)return null;let{EverfurTelevetDialog:r}=t.module;return jsx(r,{request:t.request,onClose:t.dismiss,...e?{onAddToCalendar:e}:{}},t.serial)}i(yd,"EverfurTelevetHost");var gi=Object.freeze(["visit","join","summary","messages"]);function hi(e){return typeof e=="string"&&gi.includes(e)}i(hi,"isVetVisitIntent");var Ob="/widget/v1/televet/handoffs",Fb="/widget/v1/televet/availability",Mb="/widget/v1/televet/chat-entry",Db=/^[a-z0-9][a-z0-9_-]{0,39}$/,Lb=/^[A-Za-z0-9_-]{22}$/;var gd=32,hd=128,bd=64;function vi(e){let t=e.httpStatus;switch(e.code){case "sessionRequired":return "sessionRequired";case "authExpired":case "authRejected":return "authRejected";case "sdkUpdateRequired":return "sdkUpdateRequired";case "validationFailed":return "invalidRequest";case "rateLimited":case "quotaExceeded":return "rateLimited";}return t===void 0?e.code==="internalError"?"network":"unknown":t===429?"rateLimited":t===404?"unavailable":t===403?"accessDenied":t===401?"authRejected":t===400||t===422?"invalidRequest":t>=500?"serverError":"unknown"}i(vi,"vetVisitErrorReasonOf");function vd(e){return E(D("validationFailed",{retryable:false,wireMessage:e}))}i(vd,"invalid");function bi(e){return E(D("internalError",{retryable:false,httpStatus:502,wireMessage:e}))}i(bi,"unusable");function Nb(e,t){let r={};e!==void 0&&(r.pet_ref=e);let n=t?.returnTo;if(n!=null){if(typeof n!="string"||!Db.test(n))return {ok:false,message:"returnTo must be a registered return destination key"};r.return_to=n;}let o=t?.entry;if(o!=null){if(o!=="chat"||e===void 0)return {ok:false,message:"entry 'chat' needs the pet the chat is about"};r.entry=o;}let a=t?.visitRef,s=t?.intent,l=a!=null;if(l){let u=typeof a=="string"?a.trim():"";if(u.length<1||[...u].length>bd)return {ok:false,message:`visitRef must be 1..${bd} characters`};r.visit_ref=u;}if(s!=null){if(!l)return {ok:false,message:"intent needs the visitRef it opens"};if(!hi(s))return {ok:false,message:`intent must be one of ${gi.join(", ")}`};r.intent=s;}return {ok:true,body:r}}i(Nb,"handoffBody");function Hb(e){if(typeof e!="object"||e===null)return null;let{visit_ref:t,intent:r}=e;return typeof t!="string"||t.length===0||!hi(r)?null:Object.freeze({visitRef:t,intent:r})}i(Hb,"parseVisitEcho");function Cd(e){let t=e.funnel??Te({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),r=e.telemetry,n=i(o=>(Ed(r,"televet.visit.handoff_failed",{reason:vi(o)}),E(o)),"failed");return {async createHandoff(o,a){let s;if(o!=null){let b=typeof o=="string"?[...o].length:0;if(b<1||b>hd)return n(D("validationFailed",{retryable:false,wireMessage:`pet_ref must be 1..${hd} characters`}));s=o;}let l=Nb(s,a);if(!l.ok){let b=vd(l.message);return b.ok?b:n(b.error)}let u=l.body,c=await t.send("televet.visit.handoff",{method:"POST",path:Ob,body:u},{idempotent:false,maxAttempts:1});if(!c.ok)return n(c.error);let d=Ub(c.value),p=u.return_to!==void 0,f=p?c.value?.flow_id:void 0;if(p&&(typeof f!="string"||!Lb.test(f))){let b=bi("the handoff response carried no usable return flow id");return b.ok?b:n(b.error)}let m=u.visit_ref!==void 0,y=m?Hb(c.value?.visit):null;if(m&&y===null){let b=bi("the handoff response did not confirm the visit it opens");return b.ok?b:n(b.error)}let R=d===null?null:Object.freeze({...d,...p?{flowId:f}:{},...y!==null?{visit:y}:{}});return R===null?n(D("internalError",{retryable:false,httpStatus:502,wireMessage:"the handoff response carried no usable visit url"})):(Ed(r,"televet.visit.handoff_created",{pet_scoped:u.pet_ref!==void 0}),M(R))},async checkAvailability(o){if(typeof o!="string"||o.length>gd)return vd(`state must be at most ${gd} characters`);let a=await t.send("televet.visit.availability",{method:"POST",path:Fb,body:{state:o}},{idempotent:false,maxAttempts:1});if(!a.ok)return E(a.error);let s=a.value?.available;return typeof s!="boolean"?bi("the availability response carried no usable answer"):M(Object.freeze({available:s}))},async chatEntryOpen(){try{let o=await t.send("televet.visit.chat_entry",{method:"GET",path:Mb},{maxAttempts:1});return o.ok&&o.value?.open===!0}catch{return false}}}}i(Cd,"createVetVisitController");function Ub(e){if(typeof e!="object"||e===null)return null;let{url:t,expires_at:r}=e;return typeof t!="string"||typeof r!="string"||r.length===0||!Vb(t)?null:Object.freeze({url:t,expiresAt:r})}i(Ub,"parseHandoff");var zb=new Set(["localhost","127.0.0.1","[::1]"]),Bb=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/,jb=/[\s\u0000-\u001f\u007f]/;function Vb(e){if(jb.test(e))return false;let t=Bb.exec(e);if(t===null)return false;let r=(t[1]??"").toLowerCase(),n=t[2]??"";if(n.length===0||n.includes("@"))return false;let o=n.replace(/:\d+$/,"").toLowerCase(),a=r==="https",s=r==="http"&&zb.has(o);if(!a&&!s)return false;let l=e.indexOf("#");if(l<0)return false;let u=e.slice(l);return u.startsWith("#h=")&&u.length>3}i(Vb,"isOpenableVisitUrl");function Ed(e,t,r){if(e)try{e.track(t,r);}catch{}}i(Ed,"safeTrack");var Rd=false;function Sd(e,t){return t!==void 0?(se(t,e),"onStartInApp"):ad(e)==="presented"?"presenter":ld(e)?"experience":(Rd||(Rd=true,console.warn("[everfur] A vet visit had nowhere to open: mount <EverfurTelevetHost /> in your EverfurProvider, or pass prefer: 'redirect'.")),null)}i(Sd,"openVetVisitInApp");var Ei=Object.freeze({status:"idle",error:null,errorReason:null});function Wb(e,t,r){let{usState:n,chat:o,scope:a}=r,s=t&&(n!==null||o),l=`${n??""}|${o?"chat":""}`,[u,c]=useState(null);if(useEffect(()=>{if(!s)return;let p=true,f=e.current;return c(null),i(async()=>{try{if(o&&!(f.chatEntryOpen&&await f.chatEntryOpen()))return !1;if(n===null)return !0;if(!f.checkAvailability)return !1;let y=await f.checkAvailability(n);return y.ok&&y.value.available}catch{return false}},"ask")().then(y=>{p&&c({key:l,open:y});}),()=>{p=false;}},[s,l,n,o,a,e]),!s)return null;let d=u!==null&&u.key===l;return {open:d&&u.open,pending:!d}}i(Wb,"usePreflight");var Kb=Object.freeze({status:"opening",error:null,errorReason:null});function kd(e,t={}){let{runtime:r,userRef:n,scopeEpoch:o}=X(),a=Ft("televet"),s=a.enabled&&n!==null,l=t.usState??null,u=t.entry==="chat",c=t.petRef??null,d=t.prefer==="redirect",p=useMemo(()=>{if(t.controller)return t.controller;let{services:C}=r.registry;return Cd({auth:C.authFor(n),telemetry:C.telemetry,...C.errorPolicy?{errorPolicy:C.errorPolicy}:{}})},[r,n,o,t.controller]),f=useRef(p);f.current=p;let m=useMemo(()=>({runtime:r,userRef:n,scopeEpoch:o}),[r,n,o]),y=Wb(f,s,{usState:l,chat:u,scope:m}),R=s&&(y===null||y.open)&&(!u||c!==null),b=t.returnTo??null,[T,x]=useState(Ei),_=useRef(null),w=useRef({runtime:r,userRef:n,scopeEpoch:o});w.current={runtime:r,userRef:n,scopeEpoch:o};let g=useRef(p);g.current=p;let S=useRef(R);S.current=R;let I=useCallback((C,A)=>{if(_.current)return _.current;let F=i(($,be)=>(x({status:$==="cancelled"?"idle":"error",error:be,errorReason:$==="cancelled"?null:$}),Object.freeze({opened:false,reason:$,error:be})),"fail");if(!S.current)return Promise.resolve(F("unavailable",null));let B=e.prepare();if(!B.ok)return Promise.resolve(F(B.reason,null));let V=w.current,Z=g.current;x(Kb);let Be=(async()=>{let $,be={...b!==null?{returnTo:b}:{},...u?{entry:"chat"}:{},...A!==null?{visitRef:A.visitRef}:{},...A!==null&&A.intent!==null&&A.intent!==void 0?{intent:A.intent}:{}},we=Object.keys(be).length===0?void 0:be,lt=C===void 0?c:C;try{$=await(we===void 0?Z.createHandoff(lt):Z.createHandoff(lt,we));}catch{return e.abandon(B.value),F("unknown",null)}let ut=w.current;if(ut.runtime!==V.runtime||ut.userRef!==V.userRef||ut.scopeEpoch!==V.scopeEpoch)return e.abandon(B.value),F("cancelled",null);if(!$.ok)return e.abandon(B.value),F(vi($.error),$.error);let Ze=await e.finish(B.value,$.value);return Ze!==null?F(Ze,null):(x(Ei),Object.freeze($.value.flowId===void 0?{opened:true}:{opened:true,flowId:$.value.flowId}))})().finally(()=>{_.current===Be&&(_.current=null);});return _.current=Be,Be},[e,c,b,u]),O=useCallback((C,A)=>{if(!S.current)return x({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}));let F=C===void 0?c:C,B={...F!==null?{petRef:F}:{},...l!==null?{usState:l}:{},...A!==null?{visitRef:A.visitRef,intent:A.intent}:{}};return Sd(B)===null?(x({status:"error",error:null,errorReason:"unavailable"}),Promise.resolve(Object.freeze({opened:false,reason:"unavailable",error:null}))):(x(Ei),Promise.resolve(Object.freeze({opened:true})))},[c,l]),k=useCallback(C=>d?I(C,null):O(C,null),[d,I,O]),v=useCallback((C,A)=>d?I(void 0,{visitRef:C,intent:A??null}):O(void 0,{visitRef:C,intent:A??null}),[d,I,O]);return {available:R,isPending:a.isPending||(y?.pending??false),status:T.status,error:T.error,errorReason:T.errorReason,open:k,openVisit:v}}i(kd,"useVetVisitWith");function Pd(e){try{e.closed||e.close();}catch{}}i(Pd,"closeQuietly");var Gb=Object.freeze({prepare(){let e=null;try{e=typeof window>"u"?null:window.open("about:blank","_blank");}catch{e=null;}if(e===null)return {ok:false,reason:"popupBlocked"};try{e.opener=null;}catch{}return {ok:true,value:{tab:e}}},async finish({tab:e},t){if(e.closed)return "cancelled";try{return e.location.replace(t.url),null}catch{return Pd(e),"popupBlocked"}},abandon({tab:e}){Pd(e);}});function _d(e){return kd(Gb,e)}i(_d,"useVetVisit");var Id='button:not([disabled]), input:not([disabled]), textarea:not([disabled]), select:not([disabled]), a[href], [tabindex]:not([tabindex="-1"])';function Ad(e){return e.tagName==="DIALOG"}i(Ad,"isDialogElement");function qe(e,t,r){let n=useRef(null),o=useRef(false),a=useRef(null),s=useRef(r);s.current=r;let l=useCallback(()=>{if(!o.current)return;o.current=false;let d=s.current===void 0?a.current:s.current.current;d&&d.isConnected&&d.focus(),(!d||!d.isConnected||document.activeElement===d)&&(a.current=null);},[]);useEffect(()=>{if(!e){l();return}let d=n.current;if(!o.current){let f=typeof document>"u"?null:document.activeElement;f!==null&&d!==null&&d.contains(f)||(a.current=f instanceof HTMLElement?f:null);}if(o.current=true,d===null)return;if(!Ad(d)){d.contains(document.activeElement)||(d.querySelector(Id)??d).focus();return}let p=d;typeof p.showModal=="function"?p.open||p.showModal():p.setAttribute("open","");},[e,l]),useEffect(()=>l,[l]);let u=useCallback(d=>{let p=n.current;if(p===null)return;if(d.key==="Escape"&&!Ad(p)){d.preventDefault(),d.stopPropagation(),t();return}if(d.key!=="Tab")return;let f=Array.from(p.querySelectorAll(Id)),m=f[0],y=f[f.length-1];if(!m||!y){d.preventDefault();return}let R=document.activeElement;d.shiftKey&&(R===m||!p.contains(R))?(d.preventDefault(),y.focus()):!d.shiftKey&&(R===y||!p.contains(R))&&(d.preventDefault(),m.focus());},[t]),c=useCallback(d=>{d.preventDefault(),t();},[t]);return {dialogRef:n,onKeyDown:u,onCancel:c}}i(qe,"useModalDialog");var qb=Object.freeze({check:jsx("polyline",{points:"20 6 9 17 4 12"}),copy:jsxs(Fragment,{children:[jsx("rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2"}),jsx("path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"})]}),thumbsUp:jsxs(Fragment,{children:[jsx("path",{d:"M7 10v12"}),jsx("path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z"})]}),thumbsDown:jsxs(Fragment,{children:[jsx("path",{d:"M17 14V2"}),jsx("path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z"})]}),info:jsxs(Fragment,{children:[jsx("circle",{cx:"12",cy:"12",r:"10"}),jsx("path",{d:"M12 16v-4"}),jsx("path",{d:"M12 8h.01"})]}),x:jsxs(Fragment,{children:[jsx("path",{d:"M18 6 6 18"}),jsx("path",{d:"m6 6 12 12"})]}),mapPin:jsxs(Fragment,{children:[jsx("path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0"}),jsx("circle",{cx:"12",cy:"10",r:"3"})]}),bookOpen:jsxs(Fragment,{children:[jsx("path",{d:"M12 7v14"}),jsx("path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z"})]}),chevronDown:jsx("path",{d:"m6 9 6 6 6-6"}),arrowUpRight:jsxs(Fragment,{children:[jsx("path",{d:"M7 7h10v10"}),jsx("path",{d:"M7 17 17 7"})]}),upload:jsxs(Fragment,{children:[jsx("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),jsx("polyline",{points:"17 8 12 3 7 8"}),jsx("line",{x1:"12",x2:"12",y1:"3",y2:"15"})]}),mic:jsxs(Fragment,{children:[jsx("path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z"}),jsx("path",{d:"M19 10v2a7 7 0 0 1-14 0v-2"}),jsx("line",{x1:"12",x2:"12",y1:"19",y2:"22"})]}),square:jsx("rect",{width:"18",height:"18",x:"3",y:"3",rx:"2"}),search:jsxs(Fragment,{children:[jsx("circle",{cx:"11",cy:"11",r:"8"}),jsx("path",{d:"m21 21-4.3-4.3"})]}),squarePen:jsxs(Fragment,{children:[jsx("path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"}),jsx("path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z"})]}),history:jsxs(Fragment,{children:[jsx("path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"}),jsx("path",{d:"M3 3v5h5"}),jsx("path",{d:"M12 7v5l4 2"})]}),plus:jsxs(Fragment,{children:[jsx("path",{d:"M5 12h14"}),jsx("path",{d:"M12 5v14"})]}),send:jsx("path",{d:"M17.306 1.98864C17.7329 0.807956 16.5887 -0.336175 15.408 0.0916395L0.977949 5.31038C-0.206691 5.73918 -0.349954 7.35559 0.739836 7.98694L5.346 10.6536L9.45914 6.54047C9.64549 6.36049 9.89506 6.26091 10.1541 6.26316C10.4132 6.26541 10.661 6.36932 10.8442 6.55251C11.0274 6.73569 11.1313 6.9835 11.1335 7.24256C11.1358 7.50162 11.0362 7.75119 10.8562 7.93754L6.74307 12.0507L9.41073 16.6568C10.0411 17.7466 11.6575 17.6024 12.0863 16.4187L17.306 1.98864Z"})}),Yb=Object.freeze({send:Object.freeze({viewBox:"0 0 17.3973 19.8995"})});function z({name:e,size:t,color:r,fill:n,strokeWidth:o,style:a}){let s=Yb[e];return jsx("svg",{"aria-hidden":"true",focusable:"false",width:t,height:t,viewBox:s?.viewBox??"0 0 24 24",fill:s!==void 0?r:n??"none",stroke:s!==void 0?"none":r,strokeWidth:o??2,strokeLinecap:"round",strokeLinejoin:"round",style:{display:"block",flexShrink:0,...a},"data-glyph":e,children:qb[e]})}i(z,"Glyph");var Nt=44,bn=36,Qb=12,Zb=16,Od="#FFFFFF";function Fd({image:e,onClose:t,returnFocusTo:r}){let n=N(),o=useMemo(()=>Jb(n),[n]),a=qe(e!==null,t,r);return e===null?null:jsxs("dialog",{ref:a.dialogRef,"aria-label":K(h.previewAttachment,{filename:e.filename}),onCancel:a.onCancel,onKeyDown:a.onKeyDown,style:o.lightbox,"data-ef-focus-ring-color":Od,children:[jsx("img",{src:e.uri,alt:e.filename,style:o.image}),jsx("button",{type:"button",onClick:t,"aria-label":h.closePreview,style:o.closeHit,children:jsx("span",{"aria-hidden":"true",style:o.closeDisc,children:jsx(z,{name:"x",size:18,color:Od})})})]})}i(Fd,"AttachmentImageLightbox");function Jb(e){let t=e.radius;return {lightbox:{boxSizing:"border-box",position:"fixed",top:0,right:0,bottom:0,left:0,margin:0,width:"100%",height:"100%",maxWidth:"100%",maxHeight:"100%",padding:0,border:0,backgroundColor:"#000000",display:"flex",alignItems:"center",justifyContent:"center"},image:{display:"block",maxWidth:"100%",maxHeight:"100%",width:"auto",height:"auto",objectFit:"contain"},closeHit:{position:"absolute",top:Qb-(Nt-bn)/2,right:Zb-(Nt-bn)/2,boxSizing:"border-box",width:Nt,height:Nt,minWidth:Nt,minHeight:Nt,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},closeDisc:{boxSizing:"border-box",width:bn,height:bn,borderRadius:t.pill,backgroundColor:"rgba(0,0,0,0.45)",display:"inline-flex",alignItems:"center",justifyContent:"center"}}}i(Jb,"makeStyles");var tv="file",rv="chat attachment upload: the file handle carries no bytes",Ri="chat attachment upload failed";function En(e={}){let t=e.fetch??((r,n)=>fetch(r,n));return Object.freeze({postMultipart(r,n,o){let a=n.blob;if(a===void 0)return Promise.reject(new Error(rv));if(o.signal?.aborted===true)return Promise.reject(new Error(Ri));let s=new FormData;for(let[l,u]of Object.entries(r.upload_fields))s.append(l,u);return s.append(tv,a,"image"),t(r.upload_url,{method:"POST",body:s,mode:"cors",credentials:"omit",...o.signal?{signal:o.signal}:{}}).then(l=>{if(!(l.status>=200&&l.status<300))return Promise.reject(new Error(Ri));o.onProgress?.(1);},()=>Promise.reject(new Error(Ri)))}})}i(En,"createWebAttachmentTransport");function Cn(e){return Object.freeze({uri:URL.createObjectURL(e),mimeType:e.type,sizeBytes:e.size,name:e.name,blob:e})}i(Cn,"fileToAttachmentHandle");function hr(e){try{URL.revokeObjectURL(e);}catch{}}i(hr,"revokeObjectUrl");function Si(e){return rr(e)==="cat"?"cat":"dog"}i(Si,"speciesOf");function xi(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:Math.floor(e)}i(xi,"petAgeYears");function Dd(e){let t=xi(e.ageYears),r=Si(e.species)==="cat"?"Cat":"Dog";if(t==null)return r;let n=t===1?"1 yr":`${t} yrs`;return `${r} \xB7 ${n}`}i(Dd,"formatPetMeta");var Md=Object.freeze([Object.freeze({background:"#ffbdbd",foreground:"#6d1d14"}),Object.freeze({background:"#a0c4f6",foreground:"#0b3a73"}),Object.freeze({background:"#fbc558",foreground:"#10462e"}),Object.freeze({background:"#bde7c5",foreground:"#0e3b22"}),Object.freeze({background:"#dcc7f4",foreground:"#3a1d6a"}),Object.freeze({background:"#ffd8a8",foreground:"#5a2a04"})]);function nv(e){let t=0;for(let r=0;r<e.length;r+=1)t=t*31+e.charCodeAt(r)>>>0;return Md[t%Md.length]}i(nv,"pickInitialsPalette");function Ti(e){let t=(e??"").trim();return (Array.from(t)[0]??"?").toUpperCase()}i(Ti,"getInitial");function Rn(e){return {...nv(e.petRef),initial:Ti(e.name)}}i(Rn,"petInitials");var Ld=Object.freeze({visitButton:"Talk to a vet"});var Sn=44,ki=44,xn=48,iv=18,Nd=22,av="80vh";function Hd(e){let{open:t,pets:r,activePetRef:n,onClose:o,onSelect:a,onAddPet:s=null,returnFocusTo:l}=e,u=N(),c=useMemo(()=>sv(u),[u]),d=qe(t,o,l);return t?jsxs("dialog",{ref:d.dialogRef,"aria-label":h.yourPets,onCancel:d.onCancel,onKeyDown:d.onKeyDown,style:c.sheet,children:[jsx("h2",{style:c.title,children:h.yourPets}),jsx("ul",{style:c.list,children:r.map(p=>{let f=p.petRef===n,m=p.name?.trim()||h.yourPet,y=Rn(p);return jsx("li",{children:jsxs("button",{type:"button","aria-current":f?"true":void 0,"aria-label":K(f?h.petCurrentlyActive:h.switchToPet,{name:m}),onClick:()=>a(p.petRef),style:{...c.row,...f?c.rowActive:null},children:[jsx("span",{style:c.ring,children:jsx("span",{style:{...c.disc,backgroundColor:y.background,color:y.foreground},children:y.initial})}),jsxs("span",{style:c.text,children:[jsx("span",{style:c.name,children:m}),jsx("span",{style:c.meta,children:`${f?h.activePrefix:""}${Dd(p)}`})]}),f?jsx(z,{name:"check",size:iv,color:u.color.brandInk,strokeWidth:2.5}):null]})},p.petRef)})}),s!==null?jsxs("button",{type:"button","aria-label":h.addAnotherPet,onClick:s,style:c.addRow,children:[jsx("span",{style:c.addDisc,children:"+"}),jsx("span",{style:c.addLabel,children:h.addAnotherPet})]}):null,jsx("button",{type:"button",onClick:o,style:c.close,children:h.close})]}):null}i(Hd,"PetSwitcherDialog");function sv(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return {sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:av,overflowY:"auto",padding:`${r.lg+4}px ${r.lg+4}px ${r.xxl}px`,border:0,borderRadius:`${Nd}px ${Nd}px 0 0`,backgroundColor:t.surface,color:t.text.primary,display:"flex",flexDirection:"column",gap:r.md+2},title:{margin:0,...P(e,"bold"),fontSize:o.tierSizes.heading.heading,lineHeight:`${Math.round(o.tierSizes.heading.heading*1.22)}px`,color:t.brandInk},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:r.sm},row:{boxSizing:"border-box",width:"100%",minHeight:Sn,display:"flex",flexDirection:"row",alignItems:"center",gap:r.md,margin:0,padding:r.md,borderRadius:n.md,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surfaceCream,color:t.text.primary,textAlign:"left",cursor:"pointer",font:"inherit"},rowActive:{border:`1px solid ${t.brandInk}`,backgroundColor:t.brandSoft},ring:{boxSizing:"border-box",flexShrink:0,width:xn,height:xn,borderRadius:n.pill,border:`2px solid ${t.success}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:ki,height:ki,borderRadius:n.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...P(e,"bold"),fontSize:Math.round(ki*.42),lineHeight:1,textTransform:"uppercase"},text:{flex:"1 1 auto",minWidth:0,display:"flex",flexDirection:"column",gap:2},name:{...P(e,"bold"),fontSize:o.size.body+1,lineHeight:`${o.size.body+4}px`,color:t.text.primary,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},meta:{...P(e,"monoBold"),fontSize:o.tierSizes.compact.tiny,lineHeight:`${o.tierSizes.compact.tiny+2}px`,letterSpacing:.4,textTransform:"uppercase",color:t.text.muted},addRow:{boxSizing:"border-box",display:"flex",alignItems:"center",gap:r.sm,width:"100%",minHeight:Sn,padding:`${r.xs}px ${r.sm}px`,background:"none",border:"none",borderRadius:n.lg,cursor:"pointer",textAlign:"left"},addDisc:{boxSizing:"border-box",width:xn,height:xn,borderRadius:n.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",border:`2px dashed ${t.brandBorder}`,backgroundColor:t.surfaceCream,color:t.brandInk,fontSize:o.size.subtitle,lineHeight:1},addLabel:{...P(e,"bold"),fontSize:o.size.body,color:t.text.primary},close:{boxSizing:"border-box",alignSelf:"center",minHeight:Sn,minWidth:Sn,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${r.xl}px`,borderRadius:n.pill,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surface,color:t.text.primary,cursor:"pointer",...P(e,"medium"),fontSize:o.tierSizes.control.body}}}i(sv,"makeStyles");var br=35,Wd=1.75,Pi=br-Wd*2,Ud=12.4,zd=36,Bd=20,jd=9,dv=1.5,at=44,Kd=28,cv=160;function Gd(e){let{pets:t,activePet:r,unread:n,onOpenHistory:o,historyTriggerRef:a,onSelectPet:s,onAddPet:l=null,vetEntry:u=null}=e,{rail:c=false,historyOpen:d=false,onNewChat:p}=e,f=N(),m=useMemo(()=>mv(f),[f]),y=jsxs("div",{style:m.historyControls,children:[p!==void 0?jsx("button",{type:"button",onClick:p,"aria-label":W.newChat,style:m.menuButton,children:jsx(z,{name:"squarePen",size:Bd,color:f.color.text.primary})}):null,jsx("button",{ref:a,type:"button",onClick:o,"aria-label":n?h.openMenuUnread:h.openMenu,"aria-expanded":d,style:m.menuButton,children:jsxs("span",{"aria-hidden":"true",style:m.menuDisc,children:[jsx(z,{name:"history",size:Bd,color:f.color.text.primary}),n?jsx("span",{style:m.unreadDot}):null]})})]});return jsxs("header",{style:m.bar,children:[c?null:y,jsx("div",{style:m.centre,children:jsx(pv,{logoUrl:f.meta.logoUrl,name:f.meta.displayName,styles:m})}),u!==null?jsx("button",{type:"button",onClick:u,style:m.vetEntry,children:Ld.visitButton}):null,jsx(fv,{pets:t,activePet:r,styles:m,onSelectPet:s,onAddPet:l}),c?y:null]})}i(Gd,"ChatHeader");function pv({logoUrl:e,name:t,styles:r}){let[n,o]=useState(null);return e===null||n===e?null:jsx("img",{src:e,alt:t,height:Kd,style:r.logo,decoding:"async",referrerPolicy:"no-referrer",onError:()=>o(e)})}i(pv,"BrandLogo");function fv({pets:e,activePet:t,styles:r,onSelectPet:n,onAddPet:o}){let[a,s]=useState(false),l=useRef(null),u=t?.name?.trim()||h.yourPet;return e.length<2&&o===null||t===null?jsx("div",{role:"img","aria-label":u,style:r.avatarSlot,children:jsx(Vd,{pet:t,styles:r})}):jsxs("div",{style:r.avatarSlot,children:[jsxs("button",{ref:l,type:"button","aria-haspopup":"dialog","aria-expanded":a,"aria-label":K(h.switchActivePet,{name:u}),onClick:()=>s(true),style:r.avatarButton,children:[jsx(Vd,{pet:t,styles:r}),jsx("span",{"aria-hidden":"true",style:r.addBadge,children:jsx("span",{style:r.addBadgeGlyph,children:"+"})})]}),jsx(Hd,{open:a,pets:e,activePetRef:t.petRef,returnFocusTo:l,onClose:()=>s(false),onSelect:c=>{s(false),n(c);},onAddPet:o===null?null:()=>{s(false),o();}})]})}i(fv,"PetAvatarSlot");function Vd({pet:e,styles:t}){let r=e===null?null:Rn(e);return jsx("span",{style:t.ring,children:jsx("span",{style:{...t.disc,...r===null?t.discEmpty:{backgroundColor:r.background,color:r.foreground}},children:r===null?Ti(null):r.initial})})}i(Vd,"AvatarRing");function mv(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return {vetEntry:{boxSizing:"border-box",minHeight:44,padding:`0 ${r.md}px`,borderRadius:n.pill,backgroundColor:t.surfaceCream,border:`1px solid ${t.brandBorder}`,color:t.brandInk,cursor:"pointer",whiteSpace:"nowrap",...P(e,"bold"),fontSize:o.size.caption},bar:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",justifyContent:"space-between",gap:r.sm,padding:`${r.sm+2}px ${r.lg}px`,backgroundColor:t.surfaceCream},menuButton:{boxSizing:"border-box",minWidth:at,minHeight:at,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer",color:t.text.primary},menuDisc:{position:"relative",boxSizing:"border-box",width:zd,height:zd,borderRadius:n.pill,display:"inline-flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:4},historyControls:{display:"flex",flexDirection:"row",alignItems:"center",flexShrink:0},unreadDot:{position:"absolute",top:6,right:6,boxSizing:"border-box",width:jd,height:jd,borderRadius:n.pill,backgroundColor:t.danger,border:`${dv}px solid ${t.surfaceCream}`},centre:{flex:"1 1 auto",minWidth:0,display:"flex",alignItems:"center",justifyContent:"center"},logo:{display:"block",height:Kd,width:"auto",maxWidth:cv,objectFit:"contain"},avatarSlot:{position:"relative",minWidth:at,minHeight:at,display:"inline-flex",alignItems:"center",justifyContent:"center"},avatarButton:{position:"relative",boxSizing:"border-box",minWidth:at,minHeight:at,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:0,border:0,background:"transparent",cursor:"pointer"},ring:{boxSizing:"border-box",width:br,height:br,borderRadius:n.pill,border:`${Wd}px solid ${t.success}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},disc:{boxSizing:"border-box",width:Pi,height:Pi,borderRadius:n.pill,display:"inline-flex",alignItems:"center",justifyContent:"center",...P(e,"bold"),fontSize:Math.round(Pi*.42),lineHeight:1,textTransform:"uppercase"},discEmpty:{backgroundColor:t.surfaceSubtle,color:t.text.muted},addBadge:{position:"absolute",bottom:(at-br)/2,right:(at-br)/2,boxSizing:"border-box",width:Ud,height:Ud,borderRadius:n.pill,border:`0.5px solid ${t.success}`,backgroundColor:t.surface,display:"inline-flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},addBadgeGlyph:{...P(e,"bold"),fontSize:o.tierSizes.badge.small,lineHeight:1,color:t.brandInk}}}i(mv,"makeStyles");var qd=Object.freeze({kind:"static"}),Yd=createContext(qd);function Xd(){return useContext(Yd)}i(Xd,"useCitationLinks");function vv(e){return useMemo(()=>e===void 0?qd:Object.freeze({kind:"host",open:i(t=>{se(e,t,"citation");},"open")}),[e])}i(vv,"useCitationLinkMode");function Qd({onOpenUrl:e,children:t}){let r=vv(e);return createElement(Yd.Provider,{value:r},t)}i(Qd,"CitationLinksScope");function Ev(e,t){if(e===void 0)return {};let r={};return e.backgroundColor!==void 0&&(r.backgroundColor=e.backgroundColor),e.borderColor!==void 0&&(r.borderColor=e.borderColor,r.borderWidth=t??1),e.borderRadius!==void 0&&(r.borderRadius=e.borderRadius),r}i(Ev,"slotBox");function Zd(e){return e===void 0||e.backgroundColor!==void 0?e:e.borderRadius===void 0?void 0:{borderRadius:e.borderRadius}}i(Zd,"ownGroundSlot");function Ce(e){return e?.textColor===void 0?{}:{color:e.textColor}}i(Ce,"slotText");function Re(e,t){let r=Ev(e,t),n={};return r.backgroundColor!==void 0&&(n.backgroundColor=r.backgroundColor),r.borderColor!==void 0&&(n.border=`${r.borderWidth??1}px solid ${r.borderColor}`),r.borderRadius!==void 0&&(n.borderRadius=r.borderRadius),n}i(Re,"slotBoxCss");var Jd=2;function _i(e){return typeof e!="number"||!Number.isInteger(e)?Jd:e<1?1:e>6?6:e}i(_i,"headingLevel");function Rv(e){return e>=6?6:e+1}i(Rv,"nextHeadingLevel");function ec(e){return `h${String(e)}`}i(ec,"headingTag");var Sv=Rv(Jd);createContext(Sv);var Er=320,wv=480,Iv=Er+wv,Av=1024,Ii=768,tc="72ch",Ai=Object.freeze({rail:false,desktop:false}),Ov=Object.freeze({rail:true,desktop:false}),Fv=Object.freeze({rail:true,desktop:true});function Mv(e){return e===null||e<Iv?Ai:e>=Av?Fv:Ov}i(Mv,"layoutFor");var kn=createContext({layout:Ai,report:i(()=>{},"report"),headingLevel:_i(void 0)});function Pn(){return useContext(kn).layout}i(Pn,"useChatLayout");function rc(){return useContext(kn).headingLevel}i(rc,"useChatHeadingLevel");function nc({children:e,headingLevel:t}){let[r,n]=useState(Ai),o=_i(t),a=useMemo(()=>({layout:r,report:n,headingLevel:o}),[r,o]);return createElement(kn.Provider,{value:a},e)}i(nc,"ChatLayoutScope");function oc(e){let{report:t}=useContext(kn);useEffect(()=>{let r=e.current;if(r===null||typeof ResizeObserver>"u")return;let n=i(()=>{let a=r.getBoundingClientRect().width;t(Mv(a>0?Math.round(a):null));},"read");n();let o=new ResizeObserver(n);return o.observe(r),()=>o.disconnect()},[e,t]);}i(oc,"useMeasuredLayout");var Oi=Object.freeze({standard:vt.standard,emphasized:vt.emphasized,exit:vt.exit,outQuad:Object.freeze([.25,.46,.45,.94])}),Fi=sr,ic=Object.freeze({layoutMs:220,messageInMs:200,bannerInMs:220,bannerOutMs:160,iconInMs:180,iconOutMs:120,followUpInMs:180,followUpStaggerMs:70,citationsInMs:220,citationsRisePx:6,drawerMs:220,pressScale:.97,pressMs:140,revealTickMs:24,revealDivisor:12,dotsCycleMs:520,dotsMinOpacity:.44,dotsLiftPx:3.5,dotsStagger:Object.freeze([0,.18,.36]),copiedMs:1500,uploadFlashMs:600,reduced:false}),Dv=Object.freeze({...ic,layoutMs:0,messageInMs:0,bannerInMs:0,bannerOutMs:0,iconInMs:0,iconOutMs:0,followUpInMs:0,followUpStaggerMs:0,citationsInMs:0,citationsRisePx:0,drawerMs:0,pressScale:1,pressMs:0,revealTickMs:0,dotsCycleMs:0,dotsMinOpacity:1,dotsLiftPx:0,reduced:true});function ac(e){return e.motion.reducedMotion?Dv:ic}i(ac,"chatMotion");function sc(e,t){return Math.max(0,t)*e.followUpStaggerMs}i(sc,"followUpDelayMs");function lc(e,t,r){if(e.reduced||t>=r)return r;let n=Math.max(1,Math.ceil((r-t)/e.revealDivisor));return Math.min(r,t+n)}i(lc,"nextRevealLength");function Q(){let e=N();return useMemo(()=>ac(e),[e])}i(Q,"useChatMotion");function Ht(e){return e!==null&&typeof e.animate=="function"}i(Ht,"canAnimate");function Se(e,t){if(!Ht(e)||t.durationMs<=0)return null;let r=[t.fromTranslateX!==void 0?`translateX(${t.fromTranslateX})`:"",t.fromTranslateY!==void 0&&t.fromTranslateY!==0?`translateY(${t.fromTranslateY}px)`:""].filter(a=>a.length>0).join(" "),n={...t.fromOpacity!==void 0?{opacity:t.fromOpacity}:{},...r.length>0?{transform:r}:{}},o={...t.fromOpacity!==void 0?{opacity:1}:{},...r.length>0?{transform:"none"}:{}};try{return e.animate([n,o],{duration:t.durationMs,delay:t.delayMs??0,easing:Fi(Oi.standard),fill:"backwards"})}catch{return null}}i(Se,"animateEnter");function Mi(e,t,r){if(!Ht(e)||t<=0)return Promise.resolve();try{let n=e.animate([{opacity:1,transform:"none"},{opacity:0,...r!==void 0?{transform:`translateX(${r})`}:{}}],{duration:t,easing:Fi(Oi.exit),fill:"forwards"});return new Promise(o=>{n.onfinish=()=>o(),n.oncancel=()=>o();})}catch{return Promise.resolve()}}i(Mi,"animateExit");function Di(e,t){let[r,n]=useState(e),o=r&&!e;return useEffect(()=>{if(e){n(true);return}if(!r)return;if(t<=0){n(false);return}let a=setTimeout(()=>n(false),t);return ()=>clearTimeout(a)},[e,t,r]),{present:r,exiting:o}}i(Di,"usePresence");function cc(e,t,r){let[n,o]=useState(t&&!r.reduced?0:e.length),a=useRef({text:e,active:t});return a.current={text:e,active:t},useEffect(()=>{if(!t||r.reduced||r.revealTickMs<=0){o(a.current.text.length);return}let s=setInterval(()=>{o(l=>lc(r,l,a.current.text.length));},r.revealTickMs);return ()=>clearInterval(s)},[t,r]),t&&!r.reduced?e.slice(0,Math.min(n,e.length)):e}i(cc,"useRevealedText");var Le=44,Bv="85%",Li={y:16,blur:48,alpha:.18},jv=.32,Vv=36,pc=8,Ni=1.5,$v=.08,Wv="50%";function mc({chat:e,history:t,mode:r,returnFocusTo:n}){let o=N(),a=r==="rail"?"brand":"surface",s=useMemo(()=>qv(o,a),[o,a]),l=Q(),u=qe(r==="dialog"&&t.open,t.close,n),c=useRef(null),d=t.open,p=l.drawerMs;if(useEffect(()=>{if(!d||r!=="dialog")return;let m=Se(c.current,{durationMs:p,fromOpacity:0,fromTranslateX:"-100%"});return ()=>m?.cancel()},[d,r,p]),!d)return null;let f=jsx(Kv,{chat:e,history:t,styles:s,theme:o,ink:a==="brand"?o.color.onPrimary:o.color.brandInk});return r==="rail"?jsx("aside",{ref:m=>{c.current=m;},"aria-label":W.heading,"data-ef-focus-ring-color":o.color.onPrimary,style:s.rail,children:f}):jsx("div",{style:s.scrim,onClick:t.close,children:jsx("div",{ref:m=>{u.dialogRef.current=m,c.current=m;},role:"dialog","aria-modal":"true","aria-label":W.heading,tabIndex:-1,onKeyDown:u.onKeyDown,onClick:m=>m.stopPropagation(),style:s.overlay,children:f})})}i(mc,"HistoryDrawer");function Kv({chat:e,history:t,styles:r,theme:n,ink:o}){let{filtered:a,loading:s,loadingMore:l,error:u,cursor:c,emptyKind:d,searching:p,query:f,setQuery:m}=t,y=!s&&u===null,[R,b]=useState(false);return jsxs(Fragment,{children:[jsxs("div",{style:r.toolbar,children:[jsxs("label",{style:{...r.searchPill,...R?pi(o):null},children:[jsx(z,{name:"search",size:16,color:n.color.text.muted}),jsx("input",{type:"search",value:f,onChange:T=>m(T.target.value),onFocus:()=>b(true),onBlur:()=>b(false),"data-ef-focus-ring":"self","aria-label":W.search,placeholder:W.search,autoComplete:"off",style:r.searchInput})]}),jsx("button",{type:"button",onClick:t.newConversation,"aria-label":W.newChat,style:r.roundControl,children:jsx(z,{name:"squarePen",size:16,color:n.color.brandInk})}),jsx("button",{type:"button",onClick:t.close,"aria-label":W.closeA11y,style:r.roundControl,children:jsx(z,{name:"x",size:16,color:n.color.brandInk})})]}),jsx("p",{style:r.heading,children:W.heading}),s?jsx("p",{role:"status",style:r.state,children:W.loading}):null,u!==null?jsxs("div",{style:r.stateBlock,children:[jsx("p",{role:"alert",style:r.state,children:W.loadFailed}),jsx("button",{type:"button",onClick:()=>{t.load();},"aria-label":W.retryA11y,style:r.retryControl,children:W.retry})]}):null,y&&a.length===0?jsxs("div",{style:r.stateBlock,children:[jsx("p",{style:r.state,children:d==="noMatch"?W.noMatch:W.empty}),jsx("p",{style:r.stateBody,children:d==="noMatch"?W.noMatchBody:W.emptyBody})]}):null,y&&a.length>0?jsx(Gv,{rows:a,activeId:e.conversationId,onSelect:T=>{t.resume(T);},styles:r,canLoadMore:c!==null&&!p&&!l,onLoadMore:t.loadMore}):null,l?jsx("p",{role:"status",style:r.state,children:W.loadingMore}):null]})}i(Kv,"PanelBody");function Gv({rows:e,activeId:t,onSelect:r,styles:n,canLoadMore:o,onLoadMore:a}){let s=useRef(null),l=typeof IntersectionObserver=="function",u=useRef(a);u.current=a;let c=useCallback(d=>{s.current=d;},[]);return useEffect(()=>{let d=s.current;if(!l||!o||d===null)return;let p=new IntersectionObserver(f=>{f.some(m=>m.isIntersecting)&&u.current();},{rootMargin:Wv});return p.observe(d),()=>p.disconnect()},[l,o,e.length]),jsxs("ul",{style:n.list,children:[e.map(d=>{let p=d.unreadCount!==null&&d.unreadCount>0,f=d.id===t;return jsx("li",{children:jsxs("button",{type:"button","aria-label":Vu(d),"aria-current":f?"true":void 0,onClick:()=>r(d.id),style:{...n.row,...f?n.rowActive:null},children:[jsx("span",{style:{...n.rowTitle,...p?n.rowTitleUnread:null},children:ln(d.title)}),p?jsx("span",{"aria-hidden":"true",style:n.unreadDot}):null]})},d.id)}),o?jsx("li",{ref:c,style:n.sentinel,children:l?null:jsx("button",{type:"button",onClick:a,style:n.textControl,children:W.more})}):null]})}i(Gv,"RowList");function qv(e,t){let r=e.color,n=e.space,o=e.radius,a=e.type,s=t==="brand",l=s?r.onPrimary:r.text.primary,u={boxSizing:"border-box",display:"flex",flexDirection:"column",gap:n.md,padding:`${n.lg}px ${n.lg}px ${n.lg}px`,backgroundColor:s?r.brand:r.surface,color:l,overflowY:"auto"},c={boxSizing:"border-box",minHeight:Le,minWidth:Le,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`0 ${n.md}px`,borderRadius:o.pill,border:`1px solid ${l}`,background:"transparent",color:l,cursor:"pointer",...P(e,"medium"),fontSize:a.tierSizes.control.body};return {rail:{...u,flex:`0 0 ${Er}px`,width:Er,minHeight:0,borderRadius:`${o.lg}px 0 0 ${o.lg}px`},scrim:{position:"absolute",top:0,right:0,bottom:0,left:0,overflow:"hidden",zIndex:1,backgroundColor:$e(r.shadow,jv)??"transparent"},overlay:{...u,position:"absolute",top:0,bottom:0,left:0,margin:0,width:Er,maxWidth:Bv,border:0,borderRadius:0,boxShadow:`0 ${Li.y}px ${Li.blur}px ${$e(r.brand,Li.alpha)??"transparent"}`,outline:"none"},toolbar:{display:"flex",flexDirection:"row",alignItems:"center",gap:n.sm},searchPill:{flex:"1 1 auto",minWidth:0,minHeight:Le,display:"flex",flexDirection:"row",alignItems:"center",gap:n.sm,padding:`0 ${n.md+2}px`,borderRadius:o.pill,boxSizing:"border-box",...s?{backgroundColor:r.surface,border:`1px solid ${r.onPrimary}`}:{backgroundColor:r.surfaceCream,border:`1px solid ${r.brandBorderStrong}`},color:r.text.primary},searchInput:{boxSizing:"border-box",flex:"1 1 auto",minWidth:0,minHeight:Le,margin:0,padding:0,border:0,outline:"none",background:"transparent",...P(e,"regular"),fontSize:a.size.bodyTight,lineHeight:`${a.size.bodyTight+3}px`,color:r.text.primary},roundControl:{boxSizing:"border-box",flexShrink:0,width:Le,height:Le,minWidth:Le,minHeight:Le,margin:0,padding:(Le-Vv)/2,border:0,display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",backgroundClip:"content-box",backgroundColor:s?r.surface:r.brandSoft,borderRadius:o.pill},heading:{margin:0,...P(e,"bold"),fontSize:a.tierSizes.heading.body,lineHeight:`${a.tierSizes.heading.body+3}px`,color:l},state:{margin:0,...P(e,"regular"),fontSize:a.size.body,lineHeight:`${a.size.body+4}px`,color:l},stateBody:{margin:0,...P(e,"regular"),fontSize:a.size.caption,lineHeight:`${a.size.caption+4}px`,color:l,opacity:.8},stateBlock:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:n.sm},textControl:c,retryControl:{...c,...Re(e.slots.primaryButton),...Ce(e.slots.primaryButton)},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column"},row:{boxSizing:"border-box",width:"100%",minHeight:Le,display:"flex",flexDirection:"row",alignItems:"center",gap:n.sm,margin:0,padding:`${n.md}px ${n.xs}px`,border:0,borderRadius:o.sm,background:"transparent",color:l,textAlign:"left",cursor:"pointer",font:"inherit"},rowActive:{backgroundColor:$e(l,$v)??"transparent"},rowTitle:{flex:"1 1 auto",minWidth:0,...P(e,"regular"),fontSize:a.size.body,lineHeight:`${a.size.body+4}px`,color:l,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},rowTitleUnread:P(e,"bold"),unreadDot:{boxSizing:"border-box",flexShrink:0,width:pc+Ni*2,height:pc+Ni*2,borderRadius:o.pill,backgroundColor:r.danger,border:`${Ni}px solid ${s?r.brand:r.surface}`},sentinel:{minHeight:1,display:"flex",justifyContent:"center",padding:`${n.xs}px 0`}}}i(qv,"makeStyles");var Ye=44,Ut=22,Qv=12,Zv=20,Jv=13,eE=16,tE=.75;function gc({surface:e,vetEntry:t,renderVetAction:r,onFindVet:n}){let o=N(),a=useMemo(()=>iE(o),[o]),s=Q(),l=Di(e.showBanner,s.bannerOutMs),u=Di(e.showCompactIcon,s.iconOutMs);return jsxs(Fragment,{children:[l.present&&e.tier!==null&&e.source!==null?jsx(rE,{surface:e,exiting:l.exiting,styles:a,action:e.showVetAction?jsx(nE,{tier:e.tier,styles:a,vetEntry:t,renderVetAction:r,onFindVet:n}):null},e.signature??"banner"):null,u.present?jsx(oE,{exiting:u.exiting,onExpand:e.expand,styles:a}):null]})}i(gc,"UrgencyBanner");function rE({surface:e,exiting:t,styles:r,action:n}){let o=useRef(null),a=Q();useEffect(()=>{let c=Se(o.current,{durationMs:a.bannerInMs,fromOpacity:0});return ()=>c?.cancel()},[a.bannerInMs]),useEffect(()=>{t&&Mi(o.current,a.bannerOutMs);},[t,a.bannerOutMs]);let s=e.tier,l=e.source;if(s===null||l===null)return null;let u=s.level==="emergency"||s.level==="schedule_soon";return jsxs("div",{ref:o,role:u?"alert":"status","aria-hidden":t?true:void 0,style:{...r.banner,borderColor:s.borderColor,backgroundColor:s.backgroundColor},children:[jsx("p",{style:{...r.label,color:s.textColor},children:s.label}),l.reason?jsx("p",{style:{...r.reason,color:s.reasonColor},children:l.reason}):null,n,jsx("button",{type:"button",onClick:e.dismiss,"aria-label":e.dismissLabel??h.close,style:r.dismissHit,children:jsx("span",{"aria-hidden":"true",style:r.dismissDisc,children:jsx(z,{name:"x",size:Qv,color:s.textColor,strokeWidth:2.25})})})]})}i(rE,"Banner");function nE({tier:e,styles:t,vetEntry:r,renderVetAction:n,onFindVet:o}){let a=N(),s=e.level,l=r.available?r.open:o!==void 0?()=>{se(o,s);}:null,u=Zd(a.slots.vetVisitButton),c=u?.textColor??e.textColor,d=l===null?null:jsxs("button",{type:"button",onClick:l,"aria-label":h.findVetA11y,style:{...t.pill,borderColor:e.borderColor,backgroundColor:e.pillColor,color:e.textColor,...Re(u),...Ce(u)},children:[jsx(z,{name:"mapPin",size:Jv,color:c}),jsx("span",{children:h.findVet})]});return n!==void 0?jsx("div",{style:t.actionRow,children:jsx(xt,{render:()=>n(s),fallback:d,resetKey:s})}):d===null?null:jsx("div",{style:t.actionRow,children:d})}i(nE,"VetAction");function oE({exiting:e,onExpand:t,styles:r}){let n=useRef(null),o=Q(),a=N();return useEffect(()=>{let s=Se(n.current,{durationMs:o.iconInMs,fromOpacity:0});return ()=>s?.cancel()},[o.iconInMs]),useEffect(()=>{e&&Mi(n.current,o.iconOutMs);},[e,o.iconOutMs]),jsx("div",{ref:n,"aria-hidden":e?true:void 0,style:r.iconRow,children:jsx("button",{type:"button",onClick:t,"aria-label":h.showLatestVetAlert,style:r.iconButton,children:jsx(z,{name:"info",size:Zv,color:a.color.text.muted})})})}i(oE,"CompactIcon");function iE(e){let t=e.space,r=e.radius,n=e.type,o=n.tierSizes.compact,a=n.tierSizes.control;return {banner:{position:"relative",boxSizing:"border-box",margin:`0 ${t.lg}px ${t.xs}px`,padding:`${t.sm}px ${t.md+2}px`,borderRadius:eE,borderStyle:"solid",borderWidth:tE,display:"flex",flexDirection:"column",gap:2},label:{margin:0,paddingRight:Ut,...P(e,"monoBold"),fontSize:o.caption,lineHeight:`${o.caption+3}px`},reason:{margin:0,paddingRight:Ut,...P(e,"regular"),fontSize:n.size.caption,lineHeight:`${n.size.caption+6}px`,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},actionRow:{display:"flex",flexDirection:"row",marginTop:t.xs},pill:{boxSizing:"border-box",minHeight:Ye,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:t.xs+2,margin:0,padding:`${t.xs+1}px ${t.sm+2}px`,borderRadius:r.pill,borderStyle:"solid",borderWidth:1,cursor:"pointer",...P(e,"monoBold"),fontSize:a.caption,lineHeight:`${a.caption+3}px`},dismissHit:{position:"absolute",top:6-(Ye-Ut)/2,right:6-(Ye-Ut)/2,boxSizing:"border-box",width:Ye,height:Ye,minWidth:Ye,minHeight:Ye,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},dismissDisc:{boxSizing:"border-box",width:Ut,height:Ut,borderRadius:r.pill,display:"inline-flex",alignItems:"center",justifyContent:"center"},iconRow:{display:"flex",flexDirection:"row",justifyContent:"flex-end",padding:`2px ${t.lg}px ${t.xs}px`},iconButton:{boxSizing:"border-box",minWidth:Ye,minHeight:Ye,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"}}}i(iE,"makeStyles");var kc=300,hc=120,wn=44,$i=120,lE="12%",uE=480,dE=18,cE="min(75%, 34rem)",pE="lg",fE=15,mE=22,yE=17,gE=28,bc="-0.005em";var vc=1,zi={y:2,blur:8,alpha:.04},hE=.6,bE="md",vE="xs",Ec="lg",EE="xl",CE=60,Bi=1,RE="xs",SE=14,ji={y:1,blur:2,alpha:.08},xE=52,Cc=16,Rc=26,Sc="-0.01em",Vi=36,Pc=24,_c=22,TE=.4,kE=.5;var xc=24,PE=3,wc=900,Ic=20,_E=14,wE="0.09em",IE=22;function Ne(e,t){return Math.round(e*t*10)/10}i(Ne,"scaledPx");function fe(){let e=N(),{desktop:t}=Pn(),r=useMemo(()=>AE(e,t),[e,t]);return {theme:e,styles:r}}i(fe,"useChatTheme");function Tc(e){return `max(${e}px, calc((100% - ${Ii}px) / 2))`}i(Tc,"columnInset");function AE(e,t){let r=e.color,n=e.space,o=e.radius,a=e.type,s=e.slots,l=Zo(a.family),u=n[pE],c=t?yE:fE,d=t?gE:mE,p=a.tierSizes.control,f=a.tierSizes.compact,m={boxSizing:"border-box",minHeight:wn,minWidth:wn,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,border:0,cursor:"pointer",...P(e,"medium"),fontSize:p.body,lineHeight:`${Math.round(p.body*a.lineHeight.normal)}px`};return {container:{...Mt,boxSizing:"border-box",position:"relative",display:"flex",flexDirection:"column",minHeight:hc,height:"100%",backgroundColor:r.chatGround,color:r.text.primary,fontFamily:l},split:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"row"},main:{flex:"1 1 auto",minWidth:0,minHeight:0,display:"flex",flexDirection:"column"},body:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column"},centered:{boxSizing:"border-box",flex:"1 1 auto",minHeight:hc,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",padding:n.xl},spinner:{boxSizing:"border-box",width:xc,height:xc,borderRadius:o.pill,border:`${PE}px solid ${r.brandSofter}`,borderTopColor:r.brandInk},emptyScroller:{boxSizing:"border-box",flex:"1 1 auto",minHeight:0,overflowY:"auto"},emptyContent:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"flex-start",minHeight:uE,paddingTop:lE,paddingLeft:n.lg,paddingRight:n.lg,paddingBottom:n.lg,gap:dE},errorText:{margin:`0 0 ${n.md}px`,...P(e,"regular"),fontSize:a.size.subtitle,lineHeight:`${Math.round(a.size.subtitle*a.lineHeight.snug)}px`,color:r.danger,textAlign:"center"},retryButton:{...m,padding:`${n.sm}px ${n.xl}px`,borderRadius:o.pill,backgroundColor:r.brand,color:r.onPrimary,...Re(s.primaryButton),...Ce(s.primaryButton)},setupNotice:{boxSizing:"border-box",display:"flex",alignItems:"center",justifyContent:"space-between",gap:n.sm,padding:`${n.sm}px ${n.lg}px`,backgroundColor:r.surfaceCream},setupNoticeText:{...P(e,"regular"),fontSize:a.size.caption,color:r.danger},setupNoticeAction:{...m,padding:0,background:"none",border:"none",color:r.brandInk,fontSize:a.size.caption,minHeight:wn},turnNotice:{boxSizing:"border-box",display:"flex",flexDirection:"column",alignItems:"flex-start",gap:n.xs,padding:n.md,borderRadius:o.lg,backgroundColor:r.surfaceCream,border:`1px solid ${r.brandBorder}`},turnNoticeError:{border:`1px solid ${r.danger}`},turnNoticeTitle:{...P(e,"bold"),margin:0,fontSize:a.size.body,color:r.text.primary},turnNoticeTitleError:{color:r.danger},reconnectingCaption:{...P(e,"medium"),margin:0,fontSize:a.size.caption,color:r.text.secondary,textTransform:"uppercase",letterSpacing:"0.5px"},turnNoticeBody:{...P(e,"regular"),margin:0,fontSize:a.size.caption,color:r.text.secondary},turnNoticeAction:{...m,padding:0,background:"none",border:"none",color:r.brandInk,fontSize:a.size.body,minHeight:wn},earlierButton:{...m,alignSelf:"center",padding:`0 ${n.md+n.xs/2}px`,backgroundColor:"transparent",color:r.linkInk,...P(e,"monoBold"),fontSize:f.tiny,lineHeight:`${Math.round(f.tiny*a.lineHeight.snug)}px`,letterSpacing:kE,textTransform:"uppercase"},list:{boxSizing:"border-box",flex:"1 1 auto",minHeight:0,overflowY:"auto",display:"flex",flexDirection:"column",gap:n[Ec],paddingTop:n.lg,paddingBottom:n.lg,paddingLeft:Tc(n.lg),paddingRight:Tc(n.lg)},messageList:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:n[Ec]},row:{display:"flex",flexDirection:"column"},rowUser:{alignItems:"flex-end"},rowAssistant:{alignItems:"flex-start"},bubble:{boxSizing:"border-box",maxWidth:cE,paddingTop:u,paddingBottom:u,paddingLeft:u,paddingRight:u,borderRadius:o[bE],position:"relative"},bubbleUser:{backgroundColor:r.bubbleUser,borderBottomRightRadius:o[vE],boxShadow:`0 ${zi.y}px ${zi.blur}px ${$e(r.brand,zi.alpha)??r.brandSoft}`,...Re(s.userBubble,vc)},bubbleAssistant:{...s.assistantBubble?.backgroundColor===void 0?{paddingTop:0,paddingBottom:0,paddingLeft:0,paddingRight:n[EE],maxWidth:`min(100%, ${tc})`}:{},...Re(s.assistantBubble,vc)},bubblePending:{opacity:hE},bubbleTextUser:{margin:0,...P(e,"medium"),color:r.onPrimary,fontSize:Ne(c,a.scale),lineHeight:`${Ne(d,a.scale)}px`,letterSpacing:bc,whiteSpace:"pre-wrap",overflowWrap:"anywhere",...Ce(s.userBubble)},bubbleTextAssistant:{margin:0,...P(e,"medium"),color:r.text.primary,fontSize:Ne(c,a.scale),lineHeight:`${Ne(d,a.scale)}px`,letterSpacing:bc,whiteSpace:"pre-wrap",overflowWrap:"anywhere",...Ce(s.assistantBubble)},bubbleBold:P(e,"bold"),bubbleItalic:{fontStyle:"italic"},bubbleCode:P(e,"mono"),followUps:{boxSizing:"border-box",marginTop:n.sm},followUpsLabel:{margin:`0 0 ${n.xs}px`,...P(e,"monoBold"),color:r.text.secondary,fontSize:f.tiny,lineHeight:`${_E}px`,letterSpacing:wE,textTransform:"uppercase"},followUpList:{listStyle:"none",margin:0,padding:0},followUpRow:{...m,width:"100%",justifyContent:"flex-start",textAlign:"left",padding:`${n.sm}px ${n.md}px ${n.sm}px 0`,background:"transparent",color:r.text.primary,...P(e,"regular"),fontSize:a.size.body,lineHeight:`${Ne(IE,a.scale)}px`,whiteSpace:"pre-wrap",overflowWrap:"anywhere"},followUpDivider:{borderTop:`1px solid ${r.brandBorder}`},composerBlock:{display:"flex",flexDirection:"column"},composerError:{margin:`${n.xs}px ${n.md}px 0`,...P(e,"regular"),fontSize:a.size.caption,lineHeight:`${Math.round(a.size.caption*a.lineHeight.normal)}px`,color:r.danger},composer:{boxSizing:"border-box",display:"flex",flexDirection:"row",alignItems:"center",gap:SE,minHeight:CE,width:`calc(100% - ${n.md*2}px)`,maxWidth:Ii,margin:`${n.xs}px auto ${n.sm}px`,padding:n[RE],backgroundColor:r.chatGround,border:`${Bi}px solid ${r.composerBorder}`,borderRadius:o.pill,boxShadow:`0 ${ji.y}px ${ji.blur}px ${$e(r.brand,ji.alpha)??r.brandSoft}`,...Re(s.composerInput,Bi)},composerFocused:{border:`${Bi}px solid ${s.composerInput?.borderColor??r.brandInk}`,outline:`${yr}px solid ${r.brandInk}`,outlineOffset:yr},inputWrap:{position:"relative",flex:"1 1 auto",minWidth:0,minHeight:Ne(xE,a.scale),display:"flex",alignItems:"center"},placeholder:{position:"absolute",top:"50%",left:0,right:0,transform:"translateY(-50%)",pointerEvents:"none",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",...P(e,"regular"),fontSize:Ne(Cc,a.scale),lineHeight:`${Ne(Rc,a.scale)}px`,letterSpacing:Sc,color:r.text.placeholder,...Ce(s.composerInput)},input:{boxSizing:"border-box",flex:"1 1 auto",width:"100%",maxHeight:$i,margin:0,padding:0,border:0,outline:"none",resize:"none",background:"transparent",...P(e,"regular"),fontSize:Ne(Cc,a.scale),lineHeight:`${Ne(Rc,a.scale)}px`,letterSpacing:Sc,color:r.text.primary,...Ce(s.composerInput)},iconControl:{...m,flexShrink:0,padding:0,borderRadius:o.pill,background:"transparent",color:r.brandInk},actionButton:{...m,flexShrink:0,padding:0,backgroundColor:"transparent"},sendDisc:{boxSizing:"border-box",width:Vi,height:Vi,display:"inline-flex",alignItems:"center",justifyContent:"center",borderRadius:Vi/2,...Re(s.sendButton)},actionButtonDisabled:{opacity:TE,cursor:"not-allowed"},poweredBy:{margin:0,padding:`0 0 ${n.xs}px`,...P(e,"regular"),color:r.text.muted,fontSize:f.micro,lineHeight:`${Math.round(f.micro*a.lineHeight.normal)}px`,textAlign:"center"}}}i(AE,"makeStyles");var OE=Object.freeze({kind:"live"}),FE=Object.freeze({kind:"folded"});function Ac(e){if(e.role!=="assistant"||e.checkin===void 0)return null;let t=e.checkin.caseId,r=co(e.proactiveOriginRef);return {caseId:t,dueDay:r!==null&&r.caseId===t?r.dueDay:""}}i(Ac,"askOf");function Oc(e){let t=new Map,r=new Map;for(let o of e){let a=Ac(o);if(a===null)continue;let s=r.get(a.caseId);(s===void 0||a.dueDay>=s.dueDay)&&r.set(a.caseId,{messageId:o.id,dueDay:a.dueDay});}if(r.size===0)return t;let n=null;for(let o of e){let a=Ac(o);if(a===null){n=null;continue}if(r.get(a.caseId)?.messageId===o.id){t.set(o.id,OE),n=null;continue}if(n!==null&&n.caseId===a.caseId){n.days.push(a.dueDay),t.set(o.id,FE);continue}let s=[a.dueDay];n={id:o.id,caseId:a.caseId,days:s},t.set(o.id,{kind:"past",runDueDays:s});}return t}i(Oc,"placeCheckins");function Fc(e){let t=new Set;for(let[r,n]of e)n.kind==="live"&&t.add(r);return t}i(Fc,"liveCheckinIds");var zt=44,Bt=56,Mc=12,In=22,Dc=18,DE=2,LE=900,Lc=220,NE=14,Nc=100,HE=10,UE=6,zE=.45,BE="rgba(7,193,104,0.55)",jE="rgba(185,28,28,0.55)",zc=Object.freeze([]);function Bc({attachments:e,onRetry:t,onRemove:r,onPreview:n}){let o=N(),a=useMemo(()=>Vc(o),[o]);return e.length===0?null:jsx("ul",{style:a.tray,children:e.map(s=>jsx("li",{style:a.cardSlot,children:jsx(VE,{row:s,styles:a,theme:o,onRetry:t,onRemove:r,onPreview:n})},s.id))})}i(Bc,"AttachmentTray");function VE({row:e,styles:t,theme:r,onRetry:n,onRemove:o,onPreview:a}){let s=Q(),l=useRef(null),[u,c]=useState(false),d=useRef(e.status==="uploading");useEffect(()=>{if(e.status==="uploaded"&&d.current){c(true);let f=setTimeout(()=>c(false),s.uploadFlashMs);return d.current=false,()=>clearTimeout(f)}d.current=e.status==="uploading";},[e.status,s.uploadFlashMs]);let p={uri:e.previewUri,filename:e.filename};return jsxs("div",{style:t.card,children:[jsx("button",{ref:l,type:"button","aria-label":K(h.previewAttachment,{filename:e.filename}),onClick:()=>a(p,l.current),style:t.previewButton,children:jsx("img",{src:e.previewUri,alt:"",style:t.thumb})}),e.status==="uploading"?jsx("div",{role:"status","aria-busy":"true","aria-label":K(h.previewAttachment,{filename:e.filename}),style:{...t.wash,backgroundColor:$e(r.color.brandInk,zE)??r.color.brandSofter},children:jsx($E,{styles:t})}):null,e.status==="uploaded"&&u?jsx("div",{"aria-hidden":"true",style:{...t.wash,backgroundColor:BE}}):null,e.status==="failed"?jsx("button",{type:"button","aria-label":K(h.retryUpload,{filename:e.filename}),onClick:()=>n(e.id),style:{...t.wash,...t.retry,backgroundColor:jE},children:jsx(z,{name:"upload",size:18,color:"#FFFFFF"})}):null,jsx("button",{type:"button","aria-label":K(h.removeAttachment,{filename:e.filename}),onClick:()=>o(e.id),style:t.removeHit,children:jsx("span",{"aria-hidden":"true",style:t.removeDisc,children:jsx(z,{name:"x",size:12,color:r.color.surface,strokeWidth:2.5})})})]})}i(VE,"TrayCard");function $E({styles:e}){let t=Q(),r=useRef(null);return useEffect(()=>{let n=r.current;if(t.reduced||!Ht(n))return;let o=n.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:LE,iterations:1/0,easing:"linear"});return ()=>o.cancel()},[t.reduced]),jsx("span",{ref:r,"aria-hidden":"true",style:e.spinner})}i($E,"Spinner");function jc({images:e,onPreview:t}){let r=N(),n=useMemo(()=>Vc(r),[r]);if(e.length===0)return null;let o=e.length===1;return jsx("ul",{style:o?n.singleList:n.gridList,children:e.map((a,s)=>jsx("li",{children:jsx(WE,{image:a,style:o?n.singleImage:n.gridImage,onPreview:t})},`${a.uri}-${s}`))})}i(jc,"MessageAttachments");function WE({image:e,style:t,onPreview:r}){let n=useRef(null);return jsx("button",{ref:n,type:"button","aria-label":K(h.attachedImage,{filename:e.filename}),onClick:()=>r(e,n.current),style:t,children:jsx("img",{src:e.uri,alt:"",style:{display:"block",width:"100%",height:"100%",objectFit:"cover"}})})}i(WE,"ImageButton");function Vc(e){let t=e.color,r=e.space,n=e.radius,o={boxSizing:"border-box",display:"block",margin:0,padding:0,border:0,overflow:"hidden",cursor:"pointer",backgroundColor:t.surfaceSubtle};return {tray:{listStyle:"none",margin:`0 ${r.md}px`,padding:`${r.xs}px 0`,display:"flex",flexDirection:"row",flexWrap:"wrap",gap:r.sm},cardSlot:{flex:"0 0 auto"},card:{position:"relative",boxSizing:"border-box",width:Bt,height:Bt},previewButton:{...o,width:Bt,height:Bt,borderRadius:Mc,border:`1px solid ${t.brandBorder}`},thumb:{display:"block",width:"100%",height:"100%",objectFit:"cover"},wash:{position:"absolute",top:0,right:0,bottom:0,left:0,borderRadius:Mc,display:"flex",alignItems:"center",justifyContent:"center",pointerEvents:"none"},retry:{pointerEvents:"auto",margin:0,padding:0,border:0,cursor:"pointer",minWidth:Bt,minHeight:Bt},spinner:{boxSizing:"border-box",display:"block",width:Dc,height:Dc,borderRadius:n.pill,border:`${DE}px solid rgba(255,255,255,0.45)`,borderTopColor:"#FFFFFF"},removeHit:{position:"absolute",top:4-(zt-In)/2,right:4-(zt-In)/2,boxSizing:"border-box",width:zt,height:zt,minWidth:zt,minHeight:zt,margin:0,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},removeDisc:{boxSizing:"border-box",width:In,height:In,borderRadius:n.pill,backgroundColor:"rgba(0,0,0,0.78)",border:`1.5px solid ${t.surface}`,display:"inline-flex",alignItems:"center",justifyContent:"center"},singleList:{listStyle:"none",margin:`0 0 ${r.sm}px`,padding:0},gridList:{listStyle:"none",margin:`0 0 ${r.sm}px`,padding:0,display:"flex",flexWrap:"wrap",gap:UE},singleImage:{...o,width:Lc,height:Lc,maxWidth:"100%",borderRadius:NE},gridImage:{...o,width:Nc,height:Nc,borderRadius:HE}}}i(Vc,"makeStyles");var jt=Object.freeze({eyebrow:"Checking in",logged:"Logged",findVet:"Find a vet now",day:"Day {day}",daySeparator:" \xB7 ",answers:Object.freeze({better:"Better",same:"Same",worse:"Worse"})}),$c=Object.freeze(Lr.map(e=>Object.freeze({answer:e,label:jt.answers[e]})));function Wc(e,t){let[r,n]=useState(null),[o,a]=useState(null),[s,l]=useState(null),u=useCallback(d=>{t!==null&&(n(d),a(null),t(e.caseId,d).then(p=>{n(null),p.ok?l(d):a(p.error);}));},[t,e.caseId]),c=s??e.answer;return {answer:c,answerable:!ys(e),escalated:c==="worse",pending:r,error:o,choose:u}}i(Wc,"useCheckinCard");var Kc=44,YE=.6;function Gc({message:e,checkin:t,onAnswer:r,onFindVet:n}){let o=N(),a=useMemo(()=>XE(o),[o]),s=Wc(t,r),l=s.answer!==null||s.pending!==null,u=r!==null&&s.answerable;return jsx("li",{style:a.row,children:jsxs("div",{role:"group","aria-label":jt.eyebrow,"aria-busy":s.pending!==null?true:void 0,style:a.card,children:[jsx("p",{style:a.eyebrow,children:jt.eyebrow}),jsx("p",{style:a.question,children:e.text}),u?jsx("div",{style:{...a.answers,...s.pending?a.answersPending:null},children:$c.map(({answer:c,label:d})=>{let p=(s.pending??s.answer)===c;return jsx("button",{type:"button",onClick:()=>s.choose(c),disabled:l,"aria-pressed":p,style:{...a.pill,...p?a.pillSelected:null},children:d},c)})}):null,s.answer!==null?jsx("p",{style:a.logged,children:jt.logged}):null,t.resolutionText?jsx("p",{style:a.question,children:t.resolutionText}):null,s.escalated&&n?jsx("button",{type:"button",onClick:n,style:a.findVet,children:jt.findVet}):null,s.error?jsx("p",{role:"alert",style:a.error,children:s.error.displayMessage}):null]})})}i(Gc,"CheckinCard");function XE(e){let t=e.color,r=e.space,n=e.radius,o=e.type,a=P(e,"regular"),s={margin:0,...a,fontSize:o.size.body,lineHeight:`${Math.round(o.size.body*o.lineHeight.normal)}px`},l=o.tierSizes.compact,u=o.tierSizes.control;return {row:{display:"flex",justifyContent:"flex-start",listStyle:"none"},card:{boxSizing:"border-box",maxWidth:"92%",padding:r.md,display:"flex",flexDirection:"column",gap:r.sm,borderRadius:n.lg,backgroundColor:t.surface,border:`1px solid ${t.brandBorder}`},eyebrow:{margin:0,...a,color:t.text.secondary,fontSize:l.caption,letterSpacing:o.letterSpacing.eyebrow,textTransform:"uppercase"},question:{...s,color:t.text.primary,whiteSpace:"pre-wrap"},answers:{display:"flex",gap:r.sm,marginTop:r.xs},answersPending:{opacity:YE},pill:{...s,fontSize:u.body,lineHeight:`${Math.round(u.body*o.lineHeight.normal)}px`,boxSizing:"border-box",flex:1,minHeight:Kc,display:"inline-flex",alignItems:"center",justifyContent:"center",padding:`0 ${r.md}px`,borderRadius:n.pill,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surfaceCream,color:t.text.primary,cursor:"pointer"},pillSelected:{backgroundColor:t.brand,borderColor:t.brand,color:t.onPrimary},logged:{margin:0,...a,color:t.text.secondary,fontSize:o.size.caption},error:{margin:0,...a,color:t.danger,fontSize:o.size.caption},findVet:{boxSizing:"border-box",alignSelf:"stretch",minHeight:Kc,borderRadius:n.pill,border:`1.5px solid ${t.brandBorder}`,backgroundColor:t.surface,color:t.brandInk,cursor:"pointer",...P(e,"bold"),fontSize:o.size.body}}}i(XE,"makeStyles");var ZE=Object.freeze({TIER_1:"#07C168",TIER_2:"#27A9FF",TIER_3:"#FBC558"}),qc="#C8BEB4";function JE(e){return e?ZE[e.toUpperCase()]??qc:qc}i(JE,"tierColor");function eC(e){if(!e)return null;let t=/^tier[_\s-]?(\d+)$/i.exec(e.trim());return t?`Tier ${t[1]}`:e}i(eC,"tierLabel");function He(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0?null:t}i(He,"text");function tC(e){let t=He(e);return t!==null&&/^https:\/\/\S+$/i.test(t)?t:null}i(tC,"httpsUrl");function rC(e,t){let r=He(e.source_name)??He(e.sourceName),n=He(e.section),o=He(e.authority_tier)??He(e.authorityTier),a=eC(o),s=r??He(e.title)??`Source ${t+1}`,l=He(e.monograph_chunk_id)??He(e.chunkId),u=[n,a].filter(c=>c!==null).join(" \xB7 ");return Object.freeze({title:s,sourceName:r,section:n,authorityTier:o,tierLabel:a,meta:u.length===0?null:u,url:tC(e.url),excerpt:He(e.excerpt),tierColor:JE(o),key:`${s}-${l??"none"}-${t}`})}i(rC,"toCitationCard");function Yc(e){return e===void 0||e.length===0?nC:Object.freeze(e.map((t,r)=>rC(t,r)))}i(Yc,"toCitationCards");var nC=Object.freeze([]);function Ki(e){return e===1?`1 ${h.sourceSingular}`:`${e} ${h.sourcePlural}`}i(Ki,"sourcesLabel");function Xc(e,t){return `${t?h.hideSources:h.showSources} ${Ki(e)}`}i(Xc,"sourcesToggleLabel");function Qc(e){return [e.url!==null?`${h.openSource}: ${e.title}`:e.title,e.meta,e.excerpt].filter(t=>t!==null&&t.length>0).join(". ")}i(Qc,"citationA11yLabel");var Jc=44,sC=244,ep=8,tp=13,lC=14,uC=2,dC=3,cC=.3;function op({citations:e}){let t=useMemo(()=>Yc(e),[e]),r=N(),n=useMemo(()=>mC(r),[r]),[o,a]=useState(false);return t.length===0?null:jsxs("div",{style:n.wrap,children:[jsxs("button",{type:"button","aria-expanded":o,"aria-label":Xc(t.length,o),onClick:()=>a(s=>!s),style:n.pill,children:[jsx(z,{name:"bookOpen",size:tp,color:r.color.brandInk}),jsx("span",{style:n.pillLabel,children:Ki(t.length)}),jsx(z,{name:"chevronDown",size:tp,color:r.color.brandInk,style:o?{transform:"rotate(180deg)"}:void 0})]}),o?jsx(pC,{cards:t,styles:n,theme:r}):null]})}i(op,"CitationCards");function pC({cards:e,styles:t,theme:r}){let n=useRef(null),o=Q(),a=Xd();return useEffect(()=>{let s=Se(n.current,{durationMs:o.citationsInMs,fromOpacity:0,fromTranslateY:o.citationsRisePx});return ()=>s?.cancel()},[o]),jsx("ul",{ref:n,style:t.deck,children:e.map(s=>{let l=a.kind==="static"?null:s.url;return jsx("li",{style:t.cardSlot,children:l!==null?jsx("a",{href:l,...fC(a,l),"aria-label":Qc(s),style:{...t.card,...t.cardLink},children:jsx(rp,{card:s,linked:true,styles:t,theme:r})}):jsx("div",{style:t.card,children:jsx(rp,{card:s,linked:false,styles:t,theme:r})})},s.key)})})}i(pC,"Deck");function fC(e,t){return e.kind==="static"?{}:{rel:"noopener noreferrer",onClick:i(r=>{r.defaultPrevented||r.button!==0||r.metaKey||r.ctrlKey||r.shiftKey||r.altKey||(r.preventDefault(),e.open(t));},"onClick")}}i(fC,"linkBehaviour");function rp({card:e,linked:t,styles:r,theme:n}){return jsxs(Fragment,{children:[jsxs("div",{style:r.cardHeader,children:[jsx("span",{"aria-hidden":"true",style:{...r.tierDot,backgroundColor:e.tierColor}}),jsx("span",{style:t?{...r.cardTitle,color:n.color.linkInk}:r.cardTitle,children:e.title}),t?jsx(z,{name:"arrowUpRight",size:lC,color:n.color.linkInk}):null]}),e.meta!==null?jsx("span",{style:r.cardMeta,children:e.meta}):null,e.excerpt!==null?jsx("span",{style:r.cardExcerpt,children:e.excerpt}):null]})}i(rp,"CardBody");function np(e){return {display:"-webkit-box",WebkitBoxOrient:"vertical",WebkitLineClamp:e,overflow:"hidden"}}i(np,"clamp");function mC(e){let t=e.color,r=e.space,n=e.radius,o=e.type;return {wrap:{display:"flex",flexDirection:"column",alignItems:"flex-start",gap:r.xs,marginTop:r.sm},pill:{boxSizing:"border-box",minHeight:Jc,minWidth:Jc,display:"inline-flex",flexDirection:"row",alignItems:"center",gap:r.xs+2,margin:0,padding:`${r.xs+2}px ${r.md}px`,border:0,borderRadius:n.pill,backgroundColor:t.brandSoft,color:t.brandInk,cursor:"pointer",font:"inherit"},pillLabel:{...P(e,"monoBold"),fontSize:o.tierSizes.compact.micro,lineHeight:`${o.tierSizes.compact.micro}px`,letterSpacing:cC,textTransform:"uppercase",color:t.brandInk},deck:{listStyle:"none",margin:0,padding:`${r.xs}px ${r.xl}px 0 0`,maxWidth:"100%",display:"flex",flexDirection:"row",gap:r.sm,overflowX:"auto"},cardSlot:{flex:"0 0 auto"},card:{boxSizing:"border-box",width:sC,display:"flex",flexDirection:"column",gap:r.xs+2,padding:r.md,borderRadius:n.md,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surface,color:t.text.primary},cardLink:{textDecoration:"none",cursor:"pointer"},cardHeader:{display:"flex",flexDirection:"row",alignItems:"flex-start",gap:r.sm},tierDot:{flexShrink:0,width:ep,height:ep,borderRadius:n.pill,marginTop:7},cardTitle:{flex:"1 1 auto",minWidth:0,...P(e,"bold"),fontSize:o.size.bodyTight,lineHeight:`${Math.round(o.size.bodyTight*1.7)}px`,letterSpacing:-0.24,color:t.text.primary,...np(uC)},cardMeta:{...P(e,"monoMedium"),fontSize:o.tierSizes.compact.nano,lineHeight:`${o.tierSizes.compact.nano+2}px`,letterSpacing:o.letterSpacing.monoWide,textTransform:"uppercase",color:t.text.metaCool,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},cardExcerpt:{...P(e,"regular"),fontSize:o.size.tiny,lineHeight:`${o.size.tiny+4}px`,color:t.text.muted,...np(dC)}}}i(mC,"makeStyles");function ip(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t.toLocaleTimeString([],{hour:"numeric",minute:"2-digit"})}i(ip,"formatMessageTime");var Gi=44,ap=20,hC=3,bC=.6;function sp(e){let{open:t,onSubmit:r,onClose:n,returnFocusTo:o}=e,a=N(),s=useMemo(()=>vC(a),[a]),l=qe(t,n,o),[u,c]=useState(null),[d,p]=useState(""),[f,m]=useState(false),[y,R]=useState(false);if(!t)return null;let b=i(()=>{if(f)return;m(true),R(false);let T=d.trim();r(u,T.length>0?T:null).then(x=>{m(false),x?n():R(true);});},"submit");return jsxs("dialog",{ref:l.dialogRef,"aria-label":h.feedbackTitle,"aria-busy":f?true:void 0,onCancel:l.onCancel,onKeyDown:l.onKeyDown,style:s.sheet,children:[jsx("h2",{style:s.title,children:h.feedbackTitle}),jsx("p",{style:s.subtitle,children:h.feedbackSubtitle}),jsx("div",{role:"group","aria-label":h.feedbackTitle,style:s.options,children:ti.map(T=>{let x=T.key===u;return jsxs("button",{type:"button","aria-pressed":x,disabled:f,onClick:()=>c(x?null:T.key),style:{...s.option,...x?s.optionSelected:null},children:[jsx("span",{style:s.optionLabel,children:T.label}),jsx("span",{"aria-hidden":"true",style:{...s.radio,...x?s.radioSelected:null},children:x?jsx(z,{name:"check",size:12,color:a.color.surface,strokeWidth:3}):null})]},T.key)})}),jsx("textarea",{rows:hC,value:d,disabled:f,"aria-label":h.feedbackNotesPlaceholder,placeholder:h.feedbackNotesPlaceholder,onChange:T=>{let x=T.target.value;[...x].length<=Zt&&p(x);},style:s.notes}),y?jsx("p",{role:"alert",style:s.failed,children:h.feedbackFailed}):null,jsxs("div",{style:s.actions,children:[jsx("button",{type:"button",onClick:b,"aria-disabled":f,style:{...s.submit,...f?s.pending:null},children:h.feedbackSubmit}),jsx("button",{type:"button",onClick:n,"aria-label":h.feedbackSkipA11y,disabled:f,style:s.skip,children:h.feedbackSkip})]})]})}i(sp,"FeedbackReasons");function vC(e){let t=e.color,r=e.space,n=e.radius,o=e.type,a=`${Math.round(o.size.body*o.lineHeight.normal)}px`,s=o.tierSizes.heading.heading,l=o.tierSizes.control.body,u={boxSizing:"border-box",minHeight:Gi,minWidth:Gi,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,cursor:"pointer",...P(e,"medium"),fontSize:o.size.body,lineHeight:a};return {sheet:{boxSizing:"border-box",position:"fixed",top:"auto",right:0,bottom:0,left:0,margin:0,width:"100%",maxWidth:"100%",maxHeight:"80vh",overflowY:"auto",padding:`${r.lg+4}px ${r.lg+4}px ${r.xxl}px`,border:0,borderRadius:`${n.lg}px ${n.lg}px 0 0`,backgroundColor:t.surface,color:t.text.primary,display:"flex",flexDirection:"column",gap:r.md},title:{margin:0,...P(e,"bold"),fontSize:s,lineHeight:`${Math.round(s*1.22)}px`,color:t.text.primary},subtitle:{margin:0,...P(e,"regular"),fontSize:o.size.body,lineHeight:a,color:t.text.muted},options:{display:"flex",flexDirection:"column",gap:r.sm},option:{...u,width:"100%",justifyContent:"space-between",gap:r.md,padding:`${r.sm}px ${r.md}px`,borderRadius:n.md,border:`1px solid ${t.brandBorder}`,backgroundColor:t.surfaceCream,color:t.text.primary,textAlign:"left"},optionSelected:{border:`1px solid ${t.brandInk}`,backgroundColor:t.brandSoft},optionLabel:{flex:"1 1 auto",minWidth:0},radio:{boxSizing:"border-box",flexShrink:0,width:ap,height:ap,borderRadius:n.pill,border:`1.5px solid ${t.brandBorderStrong}`,backgroundColor:t.surface,display:"inline-flex",alignItems:"center",justifyContent:"center"},radioSelected:{border:`1.5px solid ${t.brandInk}`,backgroundColor:t.brandInk},notes:{boxSizing:"border-box",width:"100%",minHeight:Gi,margin:0,padding:`${r.sm}px ${r.md}px`,borderRadius:n.md,border:`1px solid ${t.brandBorderStrong}`,backgroundColor:t.surfaceCream,color:t.text.primary,resize:"vertical",...P(e,"regular"),fontSize:o.size.body,lineHeight:a},failed:{margin:0,...P(e,"regular"),fontSize:o.size.caption,color:t.danger},actions:{display:"flex",flexDirection:"column",alignItems:"stretch",gap:r.sm},submit:{...u,fontSize:l,padding:`0 ${r.xl}px`,border:0,borderRadius:n.pill,backgroundColor:t.brand,color:t.onPrimary,...Re(e.slots.primaryButton),...Ce(e.slots.primaryButton)},pending:{opacity:bC,cursor:"progress"},skip:{...u,fontSize:l,padding:`0 ${r.xl}px`,border:0,borderRadius:n.pill,background:"transparent",color:t.text.secondary}}}i(vC,"makeStyles");var Cr=44,Xi=15,dp=16;function CC(){return typeof navigator<"u"&&typeof navigator.clipboard?.writeText=="function"}i(CC,"canCopyToClipboard");function pp(e){let{role:t,text:r,createdAt:n,responseId:o,sentiment:a,feedback:s}=e,l=N(),u=useMemo(()=>RC(l),[l]),c=Q(),d=useMemo(()=>ip(n),[n]),p=CC()&&r.length>0,[f,m]=useState(false),y=useRef(null);useEffect(()=>()=>{y.current!==null&&clearTimeout(y.current);},[]);let R=useCallback(()=>{navigator.clipboard.writeText(r).catch(()=>{}),m(true),y.current!==null&&clearTimeout(y.current),y.current=setTimeout(()=>{m(false),y.current=null;},c.copiedMs);},[r,c.copiedMs]),[b,T]=useState(false),[x,_]=useState(false),[w,g]=useState(false),S=useRef(null),I=useCallback(k=>{if(o===void 0)return;_(false),g(false);let v=a===k;s(o,k).then(C=>{C.ok||g(true);}),k==="down"&&!v&&T(true);},[o,a,s]),O=useCallback(async(k,v)=>{if(o===void 0)return false;if(k===null&&v===null)return _(true),true;let C=await s(o,"down",k??"other",v);return C.ok&&_(true),C.ok},[o,s]);return jsxs("div",{style:{...u.footer,...t==="user"?u.footerUser:u.footerAssistant},children:[jsxs("div",{style:u.row,children:[d!==null?jsx("span",{style:u.timestamp,children:d}):null,p?jsx("button",{type:"button",onClick:R,"aria-label":f?h.copied:t==="user"?h.copyUserMessage:h.copyAssistantMessage,style:u.iconButton,children:f?jsx(z,{name:"check",size:Xi,color:l.color.success}):jsx(z,{name:"copy",size:Xi,color:l.color.text.timestamp})}):null,t==="assistant"&&o!==void 0?Su.map(k=>{let v=a===k.sentiment,C=l.color.sentiment[k.sentiment];return jsx("button",{ref:k.sentiment==="down"?S:void 0,type:"button","aria-pressed":v,"aria-label":k.label,onClick:()=>I(k.sentiment),style:u.iconButton,children:jsx(z,{name:k.sentiment==="up"?"thumbsUp":"thumbsDown",size:Xi,color:C,fill:v?C:"transparent",style:k.sentiment==="neutral"?{transform:"rotate(-90deg)"}:void 0})},k.sentiment)}):null]}),x?jsx("p",{role:"status",style:u.thanks,children:h.feedbackThanks}):null,w?jsx("p",{role:"alert",style:u.failed,children:h.feedbackFailed}):null,b?jsx(sp,{open:true,onSubmit:O,onClose:()=>T(false),returnFocusTo:S}):null]})}i(pp,"MessageFooter");function RC(e){let t=e.color,r=e.space,n=e.type;return {footer:{display:"flex",flexDirection:"column",gap:r.xs,paddingTop:r.xs+2},footerUser:{alignItems:"flex-end"},footerAssistant:{alignItems:"flex-start"},row:{display:"flex",flexDirection:"row",alignItems:"center",gap:r.sm+2,minHeight:dp},timestamp:{...P(e,"monoMedium"),fontSize:n.tierSizes.compact.nano,lineHeight:`${n.tierSizes.compact.nano+2}px`,color:e.color.text.timestamp},iconButton:{boxSizing:"border-box",width:Cr,height:Cr,minWidth:Cr,minHeight:Cr,margin:`${ -28/2}px 0`,padding:0,border:0,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer"},thanks:{margin:0,...P(e,"regular"),fontSize:n.size.caption,color:t.text.secondary},failed:{margin:0,...P(e,"regular"),fontSize:n.size.caption,color:t.danger}}}i(RC,"makeStyles");var fp="#10462E",mp="#000000",SC="#83E0B4",xC=Object.freeze([Object.freeze({id:"breed-health-miss",intent:"send",label:"What {breed} health issue do owners miss most?",fallbackLabel:"What {species} health issue do owners miss most?",background:"#A0C4F6",borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"attention-at-age",intent:"send",label:"What changes should I expect at {ageYears} years old?",fallbackLabel:"What changes should I expect as my {species} ages?",background:SC,borderColor:"rgba(0,0,0,0.5)",borderWidth:1.25}),Object.freeze({id:"early-pain-signs",intent:"send",label:"What are early signs of pain?",background:"#FBC558",borderColor:fp,brandEdge:true,borderWidth:1}),Object.freeze({id:"vet-prep",intent:"vet_report",label:"Help me prep for {petName}\u2019s vet visit.",background:"#FFBDBD",borderColor:"#6D1D14",borderWidth:1.25})]),TC=/\s*-\s*(?:small|medium|large|giant|toy)\s*$/i;function kC(e){return e==null?e:e.replace(TC,"").trim()}i(kC,"formatBreedForPrompt");var PC=new Set(["","?","-","--",".","n/a","na","none","null","nil","unknown","unspecified","unsure","not sure","not specified","not applicable","no idea","dunno","idk","tbd","other","i dont know","i don't know","dont know","don't know","do not know","i do not know","not known","no clue"]);function _C(e){let t=String(e??"").replace(/\s+/gu," ").trim().toLowerCase().replace(/\u2019/g,"'");return PC.has(t)}i(_C,"isUninformativeBreed");function wC(e){return e==="cat"?"Domestic Short Hair Mix":"Mixed Breed"}i(wC,"unspecifiedBreedLabel");function IC(e,t){return _C(e)?wC(t):String(e).replace(/\s+/gu," ").trim()}i(IC,"resolveBreedLabel");function yp(e){let t=e?.name?.trim()||h.emptyTitlePetFallback;return K(h.emptyTitle,{petName:t})}i(yp,"emptyStateTitle");function gp(e,t=fp){let r=Si(e?.species),n=r==="cat"?"my cat":"my dog",o=e?.name?.trim()||null,a=o||n,s=IC(kC(e?.breed),r)||null,l=xi(e?.ageYears),u=l===null?null:String(l);return Object.freeze(xC.map(c=>{let d=c.label.includes("{breed}"),p=c.label.includes("{ageYears}"),m=c.fallbackLabel!==void 0&&(d&&!s||p&&!u)&&c.fallbackLabel?c.fallbackLabel:c.label,y=K(m,{petName:a,breed:s??n,species:r,ageYears:u??""}),R=!o&&m.startsWith("{petName}")?y.charAt(0).toUpperCase()+y.slice(1):y;return Object.freeze({id:c.id,intent:c.intent,label:R,background:c.background,borderColor:c.brandEdge===true?t:c.borderColor,borderWidth:c.borderWidth})}))}i(gp,"resolveQuickPrompts");var bp=44,MC=28,DC=34,LC=-0.8,NC=340;function vp({pet:e,onSend:t,onVetPrep:r}){let n=N(),o=useMemo(()=>UC(n),[n]),a=Q(),s=yp(e),l=ec(rc()),u=useId(),c=useMemo(()=>gp(e,n.color.brandInk).filter(d=>d.intent!=="vet_report"||r!==null),[e,r,n.color.brandInk]);return jsxs("div",{style:o.wrap,children:[jsx(l,{id:u,style:o.title,children:s}),jsx("ul",{"aria-labelledby":u,style:o.list,children:c.map((d,p)=>jsx("li",{children:jsx(HC,{chip:d,delayMs:sc(a,p),durationMs:a.followUpInMs,style:o.chip,onPress:()=>d.intent==="vet_report"?r?.():t(d.label)})},d.id))})]})}i(vp,"QuickPrompts");function HC({chip:e,delayMs:t,durationMs:r,style:n,onPress:o}){let a=useRef(null);return useEffect(()=>{let s=Se(a.current,{durationMs:r,delayMs:t,fromOpacity:0});return ()=>s?.cancel()},[r,t]),jsx("button",{ref:a,type:"button",onClick:o,style:{...n,backgroundColor:e.background,border:`${e.borderWidth}px solid ${e.borderColor}`},children:e.label})}i(HC,"Chip");function UC(e){let t=e.space,r=e.radius,n=e.type;return {wrap:{display:"flex",flexDirection:"column",alignItems:"center",gap:t.lg+2},title:{margin:0,maxWidth:NC,...P(e,"bold"),fontSize:Qo(e,"heading",MC),lineHeight:`${Qo(e,"heading",DC)}px`,letterSpacing:LC,color:e.color.text.primary,textAlign:"center"},list:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",alignItems:"center",gap:t.md},chip:{boxSizing:"border-box",minHeight:bp,minWidth:bp,display:"inline-flex",alignItems:"center",justifyContent:"center",margin:0,padding:`${t.sm+1}px ${t.md+2}px`,borderRadius:r.pill,cursor:"pointer",...P(e,"bold"),fontSize:n.tierSizes.compact.caption,lineHeight:`${n.tierSizes.compact.caption+2}px`,color:mp,textAlign:"center",whiteSpace:"normal"}}}i(UC,"makeStyles");var Qi=/\*\*([^*]+?)\*\*|\*([^*]+?)\*|`([^`]+?)`/g;function Ep(e){return e.includes("*")||e.includes("`")}i(Ep,"hasInlineMarkup");function Cp(e){let t=[],r=0;Qi.lastIndex=0;for(let n=Qi.exec(e);n!==null;n=Qi.exec(e)){n.index>r&&t.push({kind:"text",text:e.slice(r,n.index)});let o=n[1],a=n[2],s=n[3];o!==void 0?t.push({kind:"bold",text:o}):a!==void 0?t.push({kind:"italic",text:a}):s!==void 0&&t.push({kind:"code",text:s}),r=n.index+n[0].length;}return r<e.length&&t.push({kind:"text",text:e.slice(r)}),t}i(Cp,"tokenizeInlineMarkdown");function Rp(e,t){return Ep(e)?Cp(e).map((r,n)=>{switch(r.kind){case "bold":return jsx("strong",{style:t.bold,children:r.text},n);case "italic":return t.italic?jsx("em",{style:t.italic,children:r.text},n):r.text;case "code":return t.code?jsx("code",{style:t.code,children:r.text},n):r.text;default:return r.text}}):e}i(Rp,"renderInlineMarkdown");var Sp=6,$C=3.5,xp=520,WC=Math.round(xp*.18),Ji=.44,KC=.5,GC=[0,1,2];function Tp(){let e=N(),t=useMemo(()=>YC(e),[e]),r=!e.motion.reducedMotion;return jsx("div",{role:"img","aria-label":h.typing,style:t.card,children:GC.map(n=>r?jsx(qC,{index:n,style:t.dot},n):jsx("div",{style:{...t.dot,...t.dotStatic}},n))})}i(Tp,"TypingIndicator");function qC({index:e,style:t}){let r=useRef(null);return useEffect(()=>{let n=r.current;if(n===null||typeof n.animate!="function")return;let o=n.animate([{opacity:Ji,transform:"translateY(0)"},{opacity:1,transform:`translateY(-${$C}px)`},{opacity:Ji,transform:"translateY(0)"}],{duration:xp,iterations:1/0,delay:e*WC,easing:"ease-in-out"});return ()=>o.cancel()},[e]),jsx("div",{ref:r,style:{...t,opacity:Ji}})}i(qC,"AnimatedDot");function YC(e){let t=e.color,r=e.space,n=e.radius;return {card:{boxSizing:"border-box",alignSelf:"flex-start",display:"flex",flexDirection:"row",alignItems:"center",gap:r.xs,padding:`${r.sm}px ${r.md}px`,backgroundColor:t.surfaceCream,borderRadius:n.md,border:`1px solid ${t.brandBorder}`},dot:{width:Sp,height:Sp,borderRadius:n.pill,backgroundColor:t.brand},dotStatic:{opacity:KC}}}i(YC,"makeStyles");function kp(e,t,r){let n=e-r,o=t!=null?Math.min(n,t):n;return Math.max(0,o)}i(kp,"resolveTurnScrollTarget");function Pp(e){let t=e.length-1,r=e[t];if(r===void 0||r.role!=="assistant")return null;let n=e[t-1];return {assistantIndex:t,userIndex:n!==void 0&&n.role==="user"?t-1:null}}i(Pp,"latestTurn");function _p(e,t,r){let n=Math.max(0,r),o=e===null?n:Math.min(Math.max(0,e),n);return o>t+1?o:null}i(_p,"nextFollowOffset");function wp(e,t){return e.scrollTop+t.getBoundingClientRect().top-e.getBoundingClientRect().top}i(wp,"contentTop");function eR(e,t,r){let n=Pp(r);if(n===null||t===null||t.children.length!==r.length)return null;let o=t.children[n.assistantIndex];if(o===void 0)return null;let a=n.userIndex===null?void 0:t.children[n.userIndex];return kp(wp(e,o),a===void 0?null:wp(e,a),96)}i(eR,"turnAnchor");function Ip(e,t,r){let n=useRef(null),o=useRef(null),a=useRef(true),s=useRef(t),l=useRef(null),u=useCallback(()=>{let m=n.current;m!==null&&(l.current!==null&&Math.abs(m.scrollTop-l.current)<1||(l.current=null,a.current=m.scrollHeight-m.scrollTop-m.clientHeight<=24));},[]),{awaiting:c,prompts:d,notice:p,reconnecting:f}=r;return useLayoutEffect(()=>{t&&!s.current&&(a.current=true),s.current=t;let m=n.current;if(m===null||!a.current)return;let y=_p(eR(m,o.current,e),m.scrollTop,m.scrollHeight-m.clientHeight);y!==null&&(m.scrollTop=y,l.current=m.scrollTop);},[e,t,c,d,p,f]),{scrollerRef:n,listRef:o,onScroll:u}}i(Ip,"useTranscriptFollow");function oR({notice:e,onRetry:t,onStartNew:r}){let{styles:n}=fe(),o=e.tone==="error";return jsxs("div",{role:"alert",style:{...n.turnNotice,...o?n.turnNoticeError:null},children:[jsx("p",{style:{...n.turnNoticeTitle,...o?n.turnNoticeTitleError:null},children:e.title}),jsx("p",{style:n.turnNoticeBody,children:e.body}),jsx("button",{type:"button",onClick:e.action==="startNew"?r:t,style:n.turnNoticeAction,children:e.actionLabel})]})}i(oR,"TurnNoticeCard");function Op(e,t,r,n,o,a,s,l,u,c){switch(e){case "loading":return n?jsx(xt,{render:n,fallback:jsx(Ap,{})}):jsx(Ap,{});case "empty":return jsx(aR,{prompts:t.suggestedPrompts,onSelectPrompt:r,pet:o,onVetPrep:a});case "error":return jsx(lR,{error:t.error,onRetry:t.retryLast,onAddPet:u});case "populated":return jsx(uR,{chat:t,onSelectPrompt:r,onAnswerCheckin:t.petRef?t.answerCheckin:null,imagesFor:s,onPreview:l,onCheckinFindVet:c});default:return Je(e)}}i(Op,"renderView");function Ap(){let{styles:e}=fe(),[t,r]=useState(false);return useEffect(()=>{let n=setTimeout(()=>r(true),kc);return ()=>clearTimeout(n)},[]),jsx("div",{role:"status","aria-busy":"true","aria-label":h.loading,style:e.centered,children:t?jsx(iR,{}):null})}i(Ap,"LoadingState");function iR(){let{theme:e,styles:t}=fe(),r=useRef(null),n=!e.motion.reducedMotion;return useEffect(()=>{let o=r.current;if(!n||o===null||typeof o.animate!="function")return;let a=o.animate([{transform:"rotate(0deg)"},{transform:"rotate(360deg)"}],{duration:wc,iterations:1/0,easing:"linear"});return ()=>a.cancel()},[n]),jsx("div",{ref:r,"aria-hidden":"true",style:t.spinner})}i(iR,"Spinner");function aR({prompts:e,onSelectPrompt:t,pet:r,onVetPrep:n}){let{styles:o}=fe();return jsx("div",{role:"region","aria-label":h.empty,style:o.emptyScroller,children:jsxs("div",{style:o.emptyContent,children:[jsx(vp,{pet:r,onSend:t,onVetPrep:n}),jsx(Fp,{prompts:e,onSelectPrompt:t})]})})}i(aR,"EmptyState");function Fp({prompts:e,onSelectPrompt:t}){let{styles:r}=fe(),n=useId();return e.length===0?null:jsxs("div",{style:r.followUps,children:[jsx("p",{id:n,style:r.followUpsLabel,children:h.followUps}),jsx("ul",{"aria-labelledby":n,style:r.followUpList,children:e.map((o,a)=>jsx(sR,{prompt:o,index:a,onSelectPrompt:t},o))})]})}i(Fp,"FollowUps");function sR({prompt:e,index:t,onSelectPrompt:r}){let{styles:n}=fe(),o=Q(),a=useRef(null);return useEffect(()=>{let s=Se(a.current,{durationMs:o.followUpInMs,delayMs:t*o.followUpStaggerMs,fromOpacity:0});return ()=>s?.cancel()},[o,t]),jsx("li",{ref:a,style:n.followUpDivider,children:jsx("button",{type:"button",onClick:()=>r(e),style:n.followUpRow,children:e})})}i(sR,"FollowUpRow");function lR({error:e,onRetry:t,onAddPet:r}){let{styles:n}=fe(),o=r!==null&&Ou(e)?r:null;return jsxs("div",{role:"alert",style:n.centered,children:[jsx("p",{style:n.errorText,children:e.displayMessage}),o!==null?jsx("button",{type:"button",onClick:o,style:n.retryButton,children:h.addPet}):null,e.retryable?jsx("button",{type:"button",onClick:t,style:n.retryButton,children:h.retry}):null]})}i(lR,"ErrorState");function uR({chat:e,onSelectPrompt:t,onAnswerCheckin:r,imagesFor:n,onPreview:o,onCheckinFindVet:a}){let{styles:s}=fe(),{messages:l,suggestedPrompts:u,isStreaming:c}=e,d=cn(l,c),p=Xu(e),f=useMemo(()=>Fc(Oc(l)),[l]),{scrollerRef:m,listRef:y,onScroll:R}=Ip(l,c,{awaiting:d,prompts:u.length,notice:p!==null,reconnecting:e.reconnecting===true}),b=l[l.length-1],T=c&&b!==void 0&&b.role==="assistant"?b.id:null;return jsxs("div",{ref:m,onScroll:R,role:"region","aria-label":h.transcript,tabIndex:0,style:s.list,children:[e.historyCursor?jsx("button",{type:"button",disabled:e.isLoadingHistory,onClick:()=>{e.loadOlderMessages();},style:s.earlierButton,children:e.isLoadingHistory?W.loadingEarlier:W.earlier}):null,jsx("ol",{ref:y,style:s.messageList,children:l.map(x=>x.checkin&&f.has(x.id)?jsx(Gc,{message:x,checkin:x.checkin,onAnswer:r,onFindVet:a},x.id):jsx(dR,{message:x,streaming:x.id===T,chat:e,images:n(x),onPreview:o},x.id))}),e.reconnecting===true?jsx("p",{style:s.reconnectingCaption,children:h.reconnecting}):null,d?jsx(Tp,{}):null,p!==null?jsx(oR,{notice:p,onRetry:e.retryLast,onStartNew:e.newConversation}):null,c?null:jsx(Fp,{prompts:u,onSelectPrompt:t})]})}i(uR,"PopulatedState");function dR({message:e,streaming:t,chat:r,images:n,onPreview:o}){let{styles:a}=fe(),s=Q(),l=useRef(null),u=e.role==="user";useEffect(()=>{let f=Se(l.current,{durationMs:s.messageInMs,fromOpacity:0});return ()=>f?.cancel()},[]);let c=cc(e.text,t&&!u,s),d=u?h.senderUser:h.senderAssistant,p=e.pending!==true&&!t;return jsxs("li",{ref:l,style:{...a.row,...u?a.rowUser:a.rowAssistant},"aria-busy":e.pending===true?true:void 0,children:[jsxs("div",{style:{...a.bubble,...u?a.bubbleUser:a.bubbleAssistant,...e.pending?a.bubblePending:null},children:[jsx("span",{style:it,children:`${d}: `}),n.length>0?jsx(jc,{images:n,onPreview:o}):null,jsx("p",{style:u?a.bubbleTextUser:a.bubbleTextAssistant,children:u?c:Rp(c,{bold:a.bubbleBold,italic:a.bubbleItalic,code:a.bubbleCode})})]}),!u&&!t?jsx(op,{citations:e.citations}):null,p?jsx(pp,{role:e.role,text:e.text,createdAt:e.createdAt,...e.responseId!==void 0?{responseId:e.responseId}:{},sentiment:r.sentimentByMessage[e.id]??null,feedback:r.feedback}):null]})}i(dR,"MessageRow");function Lp(e,t,r){let[n,o]=useState({send:e,conversationId:t,text:r??"",seeded:r??null}),a=n.send===e&&(n.conversationId===null||n.conversationId===t);useEffect(()=>{o(l=>{let u=l.send===e&&(l.conversationId===null||l.conversationId===t),c=u?l.text:"",d=u?l.seeded:null,p=r!=null&&r!==d&&c.length===0;return {send:e,conversationId:t,text:p?r:c,seeded:p?r:d}});},[e,t,r]);let s=useCallback(l=>o(u=>({send:e,conversationId:t,text:l,seeded:u.seeded})),[e,t]);return [a?n.text:"",s]}i(Lp,"useChatDraft");function Np(e,t,r,n){let o=useRef({draft:r,setDraft:n});o.current={draft:r,setDraft:n};let a=useRef(null),[s,l]=useState(null);useEffect(()=>{if(e===void 0)return;let u=`${t??""}`;if(a.current===u)return;a.current=u;let c=true;return (async()=>{let d=await Nu(()=>e.read(t));if(!c)return;let p=d.ok&&typeof d.value=="string"?d.value:"";p.length>0&&o.current.draft.length===0&&o.current.setDraft(p),l(u);})(),()=>{c=false;}},[e,t]),useEffect(()=>{e===void 0||s!==`${t??""}`||se(()=>e.write(t,r));},[e,t,r,s]);}i(Np,"usePersistedDraft");var Nn=44,yR=18,gR=14,Hn=6,hR=1200,bR=.4;function vR(e){let t=Math.max(0,Math.floor(e/1e3)),r=Math.floor(t/60),n=t%60;return `${r}:${n.toString().padStart(2,"0")}`}i(vR,"formatDictationElapsed");function Up(e){switch(e){case "permissionDenied":return h.micBlocked;case "noSpeech":return h.noSpeech;case "unavailable":return h.dictationUnavailable}}i(Up,"dictationErrorMessage");function zp({active:e,listening:t,elapsedMs:r,disabled:n=false,onToggle:o}){let a=N(),s=useMemo(()=>CR(a),[a]);return jsxs("span",{style:s.wrap,children:[t?jsx("span",{"aria-hidden":"true",style:s.timer,children:vR(r)}):null,jsx("button",{type:"button",disabled:n,onClick:()=>o(),"aria-label":e?h.stopDictation:h.dictate,"aria-pressed":e,style:{...s.button,...n?s.buttonDisabled:null},children:e?jsxs(Fragment,{children:[jsx(ER,{style:s.pulse}),jsx(z,{name:"square",size:gR,color:a.color.brandInk,fill:a.color.brandInk,style:{position:"relative"}})]}):jsx(z,{name:"mic",size:yR,color:a.color.brandInk})}),jsx("span",{role:"status","aria-live":"polite",style:it,children:t?h.listening:""})]})}i(zp,"DictationButton");function ER({style:e}){let t=useRef(null),r=Q();return useEffect(()=>{let n=t.current;if(r.reduced||!Ht(n))return;let o=n.animate([{opacity:1},{opacity:.4},{opacity:1}],{duration:hR,iterations:1/0,easing:"ease-in-out"});return ()=>o.cancel()},[r.reduced]),jsx("span",{ref:t,"aria-hidden":"true",style:e})}i(ER,"Pulse");function CR(e){let t=e.color,r=e.radius,n=e.type;return {wrap:{display:"inline-flex",flexShrink:0,alignItems:"center",gap:e.space.xs},timer:{...P(e,"mono"),fontSize:n.tierSizes.compact.micro,lineHeight:`${n.tierSizes.compact.micro+2}px`,fontVariantNumeric:"tabular-nums",color:t.text.muted},button:{position:"relative",boxSizing:"border-box",width:Nn,height:Nn,minWidth:Nn,minHeight:Nn,margin:0,padding:0,border:0,borderRadius:r.pill,background:"transparent",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",color:t.brandInk},buttonDisabled:{opacity:bR,cursor:"not-allowed"},pulse:{position:"absolute",top:Hn,right:Hn,bottom:Hn,left:Hn,borderRadius:r.pill,backgroundColor:t.brandSofter}}}i(CR,"makeStyles");function Bp(e){if(!e)return null;let t=e.SpeechRecognition??e.webkitSpeechRecognition;return typeof t=="function"?t:null}i(Bp,"getRecognitionConstructor");function ra(e){return typeof e=="string"&&e.toLowerCase().startsWith("en")?e:"en-US"}i(ra,"resolveDictationLang");async function jp(e,t){let r=Bp(e);if(!r)return "none";if(typeof r.available!="function")return "browser";try{let n=await r.available({langs:[t],processLocally:!0});return n==="available"?"on_device":n==="downloadable"?"downloadable":"browser"}catch{return "browser"}}i(jp,"probeDictationCapability");function SR(e){let t=[];for(let r=0;r<e.length;r+=1){let n=e[r]?.[0]?.transcript?.trim();if(!n)continue;let o=t[t.length-1];o&&n.toLowerCase().startsWith(o.toLowerCase())?t[t.length-1]=n:t.push(n);}return t.join(" ")}i(SR,"joinRecognitionResults");function Vp(e,t,r){let n=t.trim();if(!n)return e;let o=e===""||/\s$/.test(e)?"":" ",a=`${e}${o}${n}`;return typeof r=="number"&&r>0?a.slice(0,r):a}i(Vp,"composeDictatedText");function xR(e){return e==="not-allowed"||e==="service-not-allowed"?"permissionDenied":e==="no-speech"?"noSpeech":"unavailable"}i(xR,"mapDictationError");var TR=new Set(["language-not-supported","service-not-allowed"]),kR={setTimeout:i((e,t)=>globalThis.setTimeout(e,t),"setTimeout"),clearTimeout:i(e=>globalThis.clearTimeout(e),"clearTimeout")};function $p(e){let{env:t,capability:r,lang:n,callbacks:o}=e,a=e.timers??kR,s=e.maxDurationMs??6e4,l=Bp(t),u=r==="on_device"?"on_device":"browser",c=u==="on_device"&&(e.phrases?.length??0)>0&&typeof t.SpeechRecognitionPhrase=="function",d=false,p=false,f=false,m=null,y=0,R=false,b=false,T=false,x=false,_=false,w="",g=null,S=null,I=i(()=>{if(b)return;b=true,y+=1,S!==null&&a.clearTimeout(S),S=null;let C=g;C===null&&!x&&w.trim()===""&&(C="noSpeech"),o.onEnd?.({mode:u,transcript:w,error:C});},"finish"),O=i(()=>{if(!l){g="unavailable",I();return}y+=1;let C=y,A=i(()=>C===y&&!b,"live"),F=new l;if(m=F,F.lang=n,F.continuous=true,F.interimResults=true,u==="on_device")try{F.processLocally=!0;}catch{u="browser";}if(u==="on_device"&&c)try{let B=t.SpeechRecognitionPhrase;F.phrases=(e.phrases??[]).map(V=>new B(V));}catch{c=false,p=true;}F.onstart=()=>{!A()||R||(R=true,o.onStart?.(u));},F.onresult=B=>{A()&&(_=true,w=SR(B.results),o.onTranscript?.(w));},F.onerror=B=>{if(!A())return;let V=B?.error??"";if(!(V==="aborted"&&T)){if(V==="phrases-not-supported"&&!p&&!_&&!T){c=false,p=true,f=true;return}if(u==="on_device"&&!d&&!_&&!T&&TR.has(V)){u="browser",c=false,d=true,f=true;return}V==="no-speech"&&w.trim()!==""||(g=xR(V));}},F.onend=()=>{if(A()){if(f&&!T){f=false,O();return}I();}};try{F.start();}catch{if(u==="on_device"&&!d){u="browser",c=false,d=true,O();return}g="unavailable",I();}},"launch");if(r==="downloadable"&&l&&typeof l.install=="function")try{Promise.resolve(l.install({langs:[n],processLocally:!0})).catch(()=>{});}catch{}let k=i(()=>{if(!(b||T)){T=true,f=false,S!==null&&a.clearTimeout(S),S=null;try{m?.stop();}catch{I();}}},"stopListening");S=a.setTimeout(()=>{S=null,k();},s);let v={get mode(){return u},stop(){b||T||(x=true,k());},cancel(){if(b)return;T=true,x=true,f=false;let C=m;I();try{C?.abort();}catch{}}};return O(),v}i($p,"startDictation");var PR=6e3;function na(e,t,r){if(e)try{e.track(t,{...r});}catch{}}i(na,"trackDictationEvent");function _R(){return typeof window>"u"?null:window}i(_R,"browserEnv");function Wp({enabled:e,input:t,setInput:r,phrases:n,maxLength:o,telemetry:a,env:s}){let[l,u]=useState("none"),[c,d]=useState("idle"),[p,f]=useState(null),[m,y]=useState(0),R=useRef(null),b=useRef(null),T=useRef(t);T.current=t;let x=useRef(r);x.current=r;let _=useRef(a);_.current=a;let[w,g]=useState(0),S=useCallback(()=>s??_R(),[s]);useEffect(()=>{if(!e){u("none");return}let A=S();if(!A)return;let F=true;return jp(A,ra(A.navigator?.language)).then(B=>{F&&u(B);}),()=>{F=false;}},[e,S,w]);let I=useCallback(()=>{let A=S();if(!A||l==="none")return;f(null),y(0),b.current=null,d("starting");let F=T.current,B=l,V=false,Z=$p({env:A,capability:l,lang:ra(A.navigator?.language),...n!==void 0?{phrases:n}:{},callbacks:{onStart:i(q=>{b.current=Date.now(),d("listening"),na(_.current,"chat_dictation_started",{mode:q});},"onStart"),onTranscript:i(q=>{x.current(Vp(F,q,o));},"onTranscript"),onEnd:i(({mode:q,transcript:Be,error:$})=>{V=true,R.current=null;let be=b.current;b.current=null,$?(f($),d("error"),na(_.current,"chat_dictation_failed",{mode:q,error:$})):(d("idle"),na(_.current,"chat_dictation_completed",{mode:q,duration_ms:be===null?0:Date.now()-be,char_count:Be.trim().length})),B==="downloadable"&&g(we=>we+1);},"onEnd")}});V||(R.current=Z);},[l,o,n,S]),O=useCallback(()=>{R.current?.stop();},[]),k=useCallback(()=>{R.current?.cancel();},[]),v=c==="starting"||c==="listening",C=useCallback(()=>{if(R.current){R.current.stop();return}I();},[I]);return useEffect(()=>{if(c!=="listening")return;let A=i(()=>{let B=b.current;B!==null&&y(Date.now()-B);},"tick");A();let F=setInterval(A,1e3);return ()=>clearInterval(F)},[c]),useEffect(()=>{if(!v||typeof document>"u")return;let A=i(()=>{document.visibilityState==="hidden"&&R.current?.stop();},"onVisibility");return document.addEventListener("visibilitychange",A),()=>document.removeEventListener("visibilitychange",A)},[v]),useEffect(()=>{if(!v||typeof document>"u")return;let A=i(F=>{F.key==="Escape"&&R.current?.stop();},"onKey");return document.addEventListener("keydown",A),()=>document.removeEventListener("keydown",A)},[v]),useEffect(()=>{if(c!=="error")return;let A=setTimeout(()=>{f(null),d("idle");},PR);return ()=>clearTimeout(A)},[c]),useEffect(()=>()=>{R.current?.cancel();},[]),{supported:e&&l!=="none",status:c,active:v,error:p,elapsedMs:m,toggle:C,stop:O,cancel:k}}i(Wp,"useDictation");var wR=["Apoquel","Cytopoint","Bravecto","NexGard","Simparica Trio","Credelio","Revolution","Heartgard","Interceptor","Sentinel","ProHeart","Rimadyl","carprofen","meloxicam","Metacam","Galliprant","gabapentin","trazodone","Librela","Solensia","Zenrelia","prednisone","prednisolone","amoxicillin","Clavamox","cephalexin","Convenia","metronidazole","doxycycline","Cerenia","maropitant","famotidine","omeprazole","Proin","Vetmedin","pimobendan","enalapril","furosemide","levothyroxine","methimazole","Vetsulin","fluoxetine","Sileo","tramadol","buprenorphine","Denamarin","Dasuquin","Cosequin","parvovirus","distemper","Bordetella","leptospirosis","heartworm","giardia","coccidia","pancreatitis","hypothyroidism","Cushing's disease","Addison's disease","IVDD","cruciate ligament","luxating patella","hip dysplasia","pyometra","kennel cough","otitis","FIV","FeLV","DHPP","FVRCP","Labrador Retriever","Golden Retriever","French Bulldog","German Shepherd","Dachshund","Cavalier King Charles Spaniel","Shih Tzu","Pomeranian","Chihuahua","Yorkshire Terrier","Bichon Frise","Havanese","Cockapoo","Goldendoodle","Labradoodle","Weimaraner","Vizsla","Shiba Inu","Springer Spaniel","Miniature Schnauzer","Corgi","Australian Shepherd","Border Collie","Siberian Husky","Beagle","Maine Coon","Ragdoll","Sphynx","Bengal cat","British Shorthair"];function Kp(e={}){let t=new Set,r=[];for(let n of [e.name,e.breed,...wR]){let o=(n??"").trim();if(!o)continue;let a=o.toLowerCase();if(!t.has(a)&&(t.add(a),r.push(o),r.length>=100))break}return r}i(Kp,"buildDictationPhrases");function qp({send:e,draftScope:t,stop:r,isStreaming:n,inputRef:o,conversationId:a,seed:s,draftStore:l,attachments:u,onPreview:c,dictation:d,pet:p,telemetry:f}){let{theme:m,styles:y}=fe(),[R,b]=Lp(t,a,s);Np(l,a===null?null:String(a),R,b);let[T,x]=useState(false),_=m.meta.placeholder??h.placeholder,w=useMemo(()=>Kp({name:p?.name??null,breed:p?.breed??null}),[p?.name,p?.breed]),g=Wp({enabled:d,input:R,setInput:b,phrases:w,maxLength:pt,telemetry:f}),S=g.cancel,I=g.active,O=useRef(null),k=useRef(new Set),v=useRef(new Set);useEffect(()=>()=>{for(let j of k.current)hr(j);for(let j of v.current)hr(j);},[]);let C=useCallback(j=>{if(u===null)return;let oe=Array.from(j.target.files??[]);if(j.target.value="",oe.length===0)return;u.dismissRejected();let dt=oe.map(Cn),xe=u.add(dt);dt.forEach((Pr,Bn)=>{xe[Bn]?.ok===true?k.current.add(Pr.uri):hr(Pr.uri);});},[u]),A=useCallback(j=>{if(u===null)return;let oe=u.attachments.find(dt=>dt.id===j);u.remove(j),oe!==void 0&&k.current.delete(oe.previewUri)&&hr(oe.previewUri);},[u]),F=u!==null&&u.uploading,B=u!==null&&u.failed,V=F||B,Z=useMemo(()=>[...R].length>pt,[R]),q=useCallback(()=>{if(R.trim().length===0||[...R].length>pt||V)return;I&&S();let j=u===null?zc:u.attachments.flatMap(oe=>oe.status==="uploaded"?[{uri:oe.previewUri,filename:oe.filename}]:[]);for(let oe of j)k.current.delete(oe.uri),v.current.add(oe.uri);e(R,j),b("");},[R,e,V,I,S,u,b]),Be=useCallback(()=>{r();},[r]),$=useCallback(j=>{j.key!=="Enter"||j.shiftKey||j.altKey||j.ctrlKey||j.metaKey||j.nativeEvent.isComposing||(j.preventDefault(),q());},[q]),be=useCallback(j=>{I&&S(),b(j.target.value);},[I,S,b]);useLayoutEffect(()=>{let j=o.current;j!==null&&(j.style.height="auto",j.style.height=`${Math.min(j.scrollHeight,$i)}px`);},[R,o]);let we=Z||V,lt=u!==null&&u.attachments.length>=u.maxPerMessage,ut=useCallback(j=>{j.target===j.currentTarget&&(j.preventDefault(),o.current?.focus());},[o]),Ze=m.slots.sendButton?.textColor??m.color.brandInk;return jsxs("div",{style:y.composerBlock,children:[B?jsx("p",{role:"alert",style:y.composerError,children:h.attachmentsFailedBlocked}):null,u!==null&&u.rejected!==null?jsx("p",{role:"alert",style:y.composerError,children:_u(u.rejected)}):null,g.supported&&g.error!==null?jsx("p",{role:"alert",style:y.composerError,children:Up(g.error)}):null,u!==null?jsx(Bc,{attachments:u.attachments,onRetry:u.retry,onRemove:A,onPreview:c}):null,jsxs("div",{style:{...y.composer,...T?y.composerFocused:null},onMouseDown:ut,children:[u!==null?jsxs(Fragment,{children:[jsx("input",{ref:O,type:"file",accept:Is,multiple:u.maxPerMessage>1,onChange:C,tabIndex:-1,"aria-hidden":"true",style:it}),jsx("button",{type:"button",onClick:()=>O.current?.click(),"aria-label":wu(u.attachments.length,u.maxPerMessage),"aria-disabled":lt,style:{...y.iconControl,...lt?y.actionButtonDisabled:null},children:jsx(z,{name:"upload",size:Ic,color:m.color.brandInk})})]}):null,jsxs("div",{style:y.inputWrap,children:[R.length===0?jsx("span",{"aria-hidden":"true",style:y.placeholder,children:_}):null,jsx("textarea",{ref:o,rows:1,value:R,onChange:be,onKeyDown:$,onFocus:()=>x(true),onBlur:()=>x(false),"data-ef-focus-ring":"self","aria-label":_,style:y.input})]}),g.supported?jsx(zp,{active:g.active,listening:g.status==="listening",elapsedMs:g.elapsedMs,onToggle:g.toggle}):null,n?jsx("button",{type:"button",onClick:Be,"aria-label":h.stop,style:y.actionButton,children:jsx("span",{"data-everfur-send-disc":"",style:y.sendDisc,children:jsx(z,{name:"square",size:_c,color:Ze,fill:Ze})})}):jsx("button",{type:"button",onClick:q,"aria-label":h.send,"aria-disabled":we,style:{...y.actionButton,...we?y.actionButtonDisabled:null},children:jsx("span",{"data-everfur-send-disc":"",style:y.sendDisc,children:jsx(z,{name:"send",size:Pc,color:Ze})})})]})]})}i(qp,"Composer");var DR=En(),ia=Object.freeze([]),LR=Object.freeze({display:"contents"});function Xp(e){let{style:t,className:r,renderPending:n}=e;return jsx(ei,{capability:"chat",style:t,className:r,...n?{renderPending:n}:{},children:jsx(Qd,{onOpenUrl:e.onOpenUrl,children:jsx(nc,{headingLevel:e.headingLevel,children:jsx(NR,{...e})})})})}i(Xp,"EverfurChat");function NR(e){let{petRef:t,conversationId:r,style:n,className:o,renderPending:a,onPetChange:s,onVetPrep:l,onFindVet:u,renderVetAction:c,pet:d,onAddPet:p,checkinTarget:f,initialAsk:m,composerSeed:y,lifecycle:R,draftStore:b,vetReturnTo:T,vetUsState:x,vetPrefer:_}=e,w=e.attachments!==false,g=e.attachments===false?void 0:e.attachments?.maxPerMessage,S=e.dictation!==false,{theme:I,styles:O}=fe(),k=useMemo(()=>Qu(t,r),[t,r]),v=mr(k),C=Yu(v),A=useRef(null),F=UR(v),B=X(),V=pn(),Z=useMemo(()=>Zu(V.pets,v.petRef),[V.pets,v.petRef]),q=useMemo(()=>p===void 0?null:()=>{se(p);},[p]),Be=useCallback(ve=>{B.handle.setActivePet(ve),se(s,ve);},[B.handle,s]),$=$u(v),be=Pn(),we=useRef(null),lt=(v.hasUnreadThreads??false)||(v.unreadCount??0)>0||$.rows.some(ve=>ve.unreadCount!==null&&ve.unreadCount>0);Bu(v.openCheckin,f),Du(v.askEverfur,v.isBootstrapping,m);let ut=useMemo(()=>si(y),[y]);Uu(R,{conversationId:v.conversationId===null?null:String(v.conversationId),isTurnInFlight:v.isStreaming,refresh:v.refreshActiveThread});let Ze=qu(useMemo(()=>Gu(v.messages),[v.messages])),j=useMemo(()=>od(v.petRef,T===void 0&&x===void 0&&_===void 0?void 0:{returnTo:T,usState:x,prefer:_}),[v.petRef,T,x,_]),oe=_d(j),dt=oe.open,xe=useMemo(()=>({available:oe.available,open:i(()=>{dt();},"open")}),[oe.available,dt]),Pr=useMemo(()=>xe.available?xe.open:u!==void 0?()=>{se(u,"emergency");}:null,[xe,u]),Bn=useMemo(()=>l!==void 0?()=>{se(l,v.petRef);}:xe.available?xe.open:null,[l,v.petRef,xe]),It=an({transport:DR,...g!==void 0?{maxPerMessage:g}:{}}),jn=HR(v.messages),[Qp,sa]=useState(null),la=useRef(null),ua=useCallback((ve,$n)=>{la.current=$n,sa(ve);},[]),Zp=useCallback(()=>sa(null),[]),Jp=useCallback(ve=>{v.send(ve),A.current?.focus();},[v.send]),ef=useCallback((ve,$n)=>{jn.record(ve,$n),It.s3Keys.length>0?v.send(ve,{imageS3Keys:It.s3Keys}):v.send(ve),It.clear();},[v.send,It,jn]),tf=B.runtime.registry?.services?.telemetry??null,Vn=useRef(null);return td(Vn,I.color.brandInk),oc(Vn),jsxs("div",{ref:Vn,className:o,style:{...O.container,...n},children:[jsx(Gd,{pets:V.pets,activePet:Z,unread:lt,onOpenHistory:$.open?$.close:$.show,historyTriggerRef:we,onSelectPet:Be,onAddPet:q,rail:be.rail,historyOpen:$.open,onNewChat:$.newConversation,vetEntry:xe.available?xe.open:null}),d!==void 0?jsx(zR,{petRef:t??null,pet:d,onRegistered:V.refresh}):null,jsxs("div",{style:O.split,children:[jsxs("div",{style:O.main,children:[jsx(gc,{surface:Ze,vetEntry:xe,renderVetAction:c,onFindVet:u}),jsx("div",{style:O.body,children:Op(C,v,Jp,a,Z,Bn,jn.imagesFor,ua,q,Pr)}),jsx(qp,{send:ef,draftScope:v.send,stop:v.stop,isStreaming:v.isStreaming,inputRef:A,conversationId:v.conversationId,seed:ut,draftStore:b,attachments:w&&It.available?It:null,onPreview:ua,dictation:S,pet:Z,telemetry:tf}),jsx(nd,{}),I.meta.hidePoweredBy?null:jsx("p",{style:O.poweredBy,children:h.poweredBy})]}),jsx(mc,{chat:v,history:$,mode:be.rail?"rail":"dialog",returnFocusTo:we})]}),jsx("div",{role:"status","aria-live":"polite","aria-atomic":"true",style:it,children:F}),jsx(Fd,{image:Qp,onClose:Zp,returnFocusTo:la}),jsx("div",{"data-ef-focus-ring":"self",style:LR,children:jsx(yd,{})})]})}i(NR,"ChatBody");function HR(e){let t=useRef({pending:[],byMessage:new Map}),r=useRef(e);r.current=e;let n=useCallback((a,s)=>{s.length!==0&&t.current.pending.push({text:a,images:s,before:new Set(r.current.map(l=>l.id))});},[]),o=useCallback(a=>{let s=t.current,l=s.byMessage.get(a.id);if(l!==void 0)return l;if(a.role!=="user")return ia;let u=s.pending.findIndex(d=>d.text===a.text&&!d.before.has(a.id));if(u<0)return ia;let[c]=s.pending.splice(u,1);return c===void 0?ia:(s.byMessage.set(a.id,c.images),c.images)},[]);return useMemo(()=>({record:n,imagesFor:o}),[n,o])}i(HR,"useSentImages");function UR(e){let t=cn(e.messages,e.isStreaming),[r,n]=useState({send:e.send,id:e.conversationId,text:""}),o=useRef(false),a=useRef({send:e.send,id:e.conversationId});return useEffect(()=>{let s=a.current;if((s.send!==e.send||s.id!==e.conversationId)&&(o.current=false),a.current={send:e.send,id:e.conversationId},o.current&&!e.isStreaming){let l=e.messages[e.messages.length-1];n({send:e.send,id:e.conversationId,text:l!==void 0&&l.role==="assistant"?l.text:""});}o.current=e.isStreaming;},[e.isStreaming,e.messages,e.send,e.conversationId]),t?h.typing:r.send===e.send&&r.id===e.conversationId?r.text:""}i(UR,"useReplyAnnouncement");function zR({petRef:e,pet:t,onRegistered:r}){let{styles:n}=fe(),o=Fu(e,t,r);return o.status!=="failed"||o.error===null?null:jsxs("div",{role:"alert",style:n.setupNotice,children:[jsx("span",{style:n.setupNoticeText,children:o.error.displayMessage}),jsx("button",{type:"button",onClick:o.retry,style:n.setupNoticeAction,children:h.retry})]})}i(zR,"PetSetupNotice");function WR(e){let{runtime:t,userRef:r,scopeEpoch:n}=X(),o=useMemo(()=>et(t.registry.services.authFor(r)),[t,r,n]),a=useMemo(()=>({repository:o,petRef:e}),[o,e]),[s,l]=useState({key:a,profile:null,loading:e!==null,error:null}),u=s.key===a?s:{profile:null,loading:e!==null,error:null},c=useRef(0),d=useCallback(async()=>{let p=++c.current;if(a.petRef===null){l({key:a,profile:null,loading:false,error:null});return}l(m=>({key:a,profile:m.key===a?m.profile:null,loading:true,error:null}));let f=await a.repository.getPetProfile(a.petRef);p===c.current&&l(f.ok?{key:a,profile:f.value,loading:false,error:null}:{key:a,profile:null,loading:false,error:f.error});},[a]);return useEffect(()=>(d(),()=>{c.current+=1;}),[d]),useMemo(()=>({profile:u.profile,loading:u.loading,error:u.error,refresh:d}),[u.profile,u.loading,u.error,d])}i(WR,"useEverfurPetProfile");function GR(e){return createElement(Jr,{clientTheme:e.clientTheme??null,seams:on,children:e.children})}i(GR,"EverfurThemeProvider");export{ei as CapabilityGate,Xp as EverfurChat,J as EverfurConfigError,_h as EverfurProvider,GR as EverfurThemeProvider,_r as EverfurThrownError,Vy as THEME_SLOT_KEYS,Ct as THEME_SLOT_NAMES,rr as canonicalPetSpecies,Kn as categoryFor,wm as conversationId,Go as createLocalStorageKv,En as createWebAttachmentTransport,rh as face,P as faceCss,Cn as fileToAttachmentHandle,of as isErr,nf as isOk,Gn as isRetryableCode,Pm as petRef,hg as previewTheme,af as unwrap,Ft as useCapability,an as useChatAttachments,ru as useEverfur,mr as useEverfurChat,WR as useEverfurPetProfile,pn as useEverfurPets,N as useEverfurTheme,At as userFacingError,_m as userRef};