@everfur/sdk 1.5.3 → 1.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/chat-cards/package.json +8 -0
- package/dist/{Chat.d-BCfyvzX8.d.ts → Chat.d-B4GybUU4.d.ts} +1 -1
- package/dist/{Chat.d-Od44h51D.d.cts → Chat.d-DPM2ncxi.d.cts} +1 -1
- package/dist/chat/index.cjs +174 -174
- package/dist/chat/index.d.cts +4 -4
- package/dist/chat/index.d.ts +4 -4
- package/dist/chat/index.js +340 -340
- package/dist/chat/lite/index.cjs +174 -174
- package/dist/chat/lite/index.d.cts +4 -4
- package/dist/chat/lite/index.d.ts +4 -4
- package/dist/chat/lite/index.js +339 -339
- package/dist/chat-cards/index.cjs +18 -0
- package/dist/chat-cards/index.d.cts +15 -0
- package/dist/chat-cards/index.d.ts +15 -0
- package/dist/chat-cards/index.js +18 -0
- package/dist/{chatHandoffToken.d-BjfmIxXk.d.cts → chatHandoffToken.d-Cap2z62P.d.cts} +1 -1
- package/dist/{chatHandoffToken.d-CFiI6IMc.d.ts → chatHandoffToken.d-zdp23Ukr.d.ts} +1 -1
- package/dist/{checkin.d-CokpahFL.d.ts → checkin.d-BoZXWjxX.d.ts} +8 -0
- package/dist/{checkin.d-BP3ZWBfX.d.cts → checkin.d-CuIUahcd.d.cts} +8 -0
- package/dist/{chunk-CFEHTNKX.js → chunk-6AIEUA4V.js} +1 -1
- package/dist/{chunk-OU5RMGKD.js → chunk-BN7OAFBS.js} +18 -18
- package/dist/{chunk-ZGL2GEEI.js → chunk-IXHLESYC.js} +1 -1
- package/dist/{chunk-XGF2HYNN.js → chunk-LMIBOI3I.js} +16 -16
- package/dist/client/index.cjs +1 -1
- package/dist/client/index.d.cts +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.js +1 -1
- package/dist/{context.d-DS1GXUEY.d.ts → context.d-D7zX6Q0J.d.ts} +1 -1
- package/dist/{context.d-Bj6-xYPA.d.cts → context.d-guaLkx5t.d.cts} +1 -1
- package/dist/core/index.cjs +2 -2
- package/dist/core/index.d.cts +4 -4
- package/dist/core/index.d.ts +4 -4
- package/dist/core/index.js +2 -2
- package/dist/index.cjs +354 -354
- package/dist/index.d.cts +7 -7
- package/dist/index.d.ts +7 -7
- package/dist/index.js +364 -364
- package/dist/notifications/index.d.cts +3 -3
- package/dist/notifications/index.d.ts +3 -3
- package/dist/records/index.cjs +1 -1
- package/dist/records/index.js +1 -1
- package/dist/{route.d-DtuKY5dM.d.ts → route.d-B3u14HJT.d.ts} +1 -1
- package/dist/{route.d-Nt-r-7IO.d.cts → route.d-QBCoO62z.d.cts} +1 -1
- package/dist/{runtimeTypes.d-CL4l7ta4.d.cts → runtimeTypes.d-BSxuUCOX.d.cts} +1 -1
- package/dist/{runtimeTypes.d-BzUig75K.d.ts → runtimeTypes.d-hjN6xvxm.d.ts} +1 -1
- package/dist/server/events/index.cjs +1 -1
- package/dist/server/events/index.js +1 -1
- package/dist/server/index.cjs +1 -1
- package/dist/server/index.js +1 -1
- package/dist/testing/rn/index.d.cts +2 -2
- package/dist/testing/rn/index.d.ts +2 -2
- package/dist/testing/web/index.d.cts +2 -2
- package/dist/testing/web/index.d.ts +2 -2
- package/dist/{useUnread.d-CedFK4k6.d.ts → useUnread.d-4SbFChbd.d.ts} +30 -3
- package/dist/{useUnread.d-DST1GMmL.d.cts → useUnread.d-B0YhhR_D.d.cts} +30 -3
- package/dist/web/health-plan/index.cjs +1 -1
- package/dist/web/health-plan/index.js +1 -1
- package/dist/web/index.cjs +3 -3
- package/dist/web/index.d.cts +7 -7
- package/dist/web/index.d.ts +7 -7
- package/dist/web/index.js +3 -3
- package/dist/web/notifications/index.d.cts +2 -2
- package/dist/web/notifications/index.d.ts +2 -2
- package/dist/web/records-sheet/index.cjs +1 -1
- package/dist/web/records-sheet/index.js +1 -1
- package/dist/web/shop/index.cjs +1 -1
- package/dist/web/shop/index.js +1 -1
- package/dist/web/televet/booking/index.cjs +1 -1
- package/dist/web/televet/booking/index.js +1 -1
- package/dist/web/televet/call/index.cjs +1 -1
- package/dist/web/televet/call/index.js +1 -1
- package/dist/web/ui/index.cjs +1 -1
- package/dist/web/ui/index.js +32 -32
- package/package.json +16 -1
package/dist/client/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
/*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
|
|
2
2
|
import{z as e}from"zod";var t=[{wireCode:"AccessDeniedException",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"AuthorizationException",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"ConflictException",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"DAILY_QUOTA_EXCEEDED",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"FILE_TOO_LARGE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"IDEMPOTENCY_KEY_IN_FLIGHT",envelope:"http_envelope",httpStatus:409,retryable:true},{wireCode:"IDEMPOTENCY_KEY_REUSED_DIFFERENT_REQUEST",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"INVALID_CONTENT_TYPE",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"InternalFailureException",envelope:"http_envelope",httpStatus:500,retryable:true},{wireCode:"MethodNotAllowedException",envelope:"http_envelope",httpStatus:405,retryable:false},{wireCode:"NotImplementedException",envelope:"http_envelope",httpStatus:501,retryable:false},{wireCode:"PaymentRequiredException",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ResourceNotFoundException",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"ServiceUnavailableException",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"TIER_UPGRADE_REQUIRED",envelope:"http_envelope",httpStatus:402,retryable:false},{wireCode:"ThrottlingException",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"ValidationException",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"accessDenied",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"access_denied",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"anchor_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"anchor_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"anonTokenInvalid",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"attachment_unreadable",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"authExpired",envelope:"http_envelope",httpStatus:401,retryable:true},{wireCode:"authRejected",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"before_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundle_not_uploaded",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"bundles_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"catalog_empty_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"catalog_shrink_refused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"consent_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_required",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"consent_scope_wrong_route",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"device_cipher_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"email_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"endpoint_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"environment_mismatch",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_cursor_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"event_payload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_not_available",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"event_type_unknown",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_required",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"idempotency_key_reused",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"inbox_cursor_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"insufficientCapability",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"insufficient_scope",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"internal_error",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"invalidRequest",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"invalid_client",envelope:"oauth_error",httpStatus:401,retryable:false},{wireCode:"invalid_client_metadata",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_grant",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_redirect_uri",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_request",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_scope",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"invalid_target",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"item_id_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"linked_account_read_only",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_connection_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"mcp_request_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"mcp_request_gone",envelope:"http_envelope",httpStatus:410,retryable:false},{wireCode:"mcp_request_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"not_found",envelope:"sse_frame",httpStatus:200,retryable:false},{wireCode:"not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"open_url_not_allowed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"partner_visit_link_conflict",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"partner_visit_owner_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"partner_visit_pet_already_mapped",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"payload_too_large",envelope:"http_envelope",httpStatus:413,retryable:false},{wireCode:"petRefInUse",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"pet_health_list_removals_unconfirmed",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_health_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"pet_not_registered",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"provider_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"rateLimited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"read_target_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"record_subject_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"record_upload_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"records_consent_required",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"restricted_key",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"sandbox_only",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_required",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"session_revoked",envelope:"http_envelope",httpStatus:401,retryable:false},{wireCode:"share_limit_reached",envelope:"http_envelope",httpStatus:429,retryable:false},{wireCode:"slow_down",envelope:"oauth_error",httpStatus:429,retryable:true},{wireCode:"species_unsupported",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"subscription_keys_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"tenant_filter_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"tenant_has_no_capabilities",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tenant_resource_not_found",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"tenant_surface_not_enabled",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"ticket_not_resolved",envelope:"http_envelope",httpStatus:409,retryable:false},{wireCode:"tickets_disabled",envelope:"http_envelope",httpStatus:404,retryable:false},{wireCode:"timeout",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"timezone_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"token_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"unavailable",envelope:"sse_frame",httpStatus:200,retryable:true},{wireCode:"unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"unrestrictedKeyRequired",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"unsupported_grant_type",envelope:"oauth_error",httpStatus:400,retryable:false},{wireCode:"unsupported_response_type",envelope:"oauth_error",httpStatus:302,retryable:false},{wireCode:"user_ref_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"verify_mint_rate_limited",envelope:"http_envelope",httpStatus:429,retryable:true},{wireCode:"verify_mint_refused",envelope:"http_envelope",httpStatus:403,retryable:false},{wireCode:"verify_mint_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"verify_user_ref_invalid",envelope:"http_envelope",httpStatus:422,retryable:false},{wireCode:"web_push_unavailable",envelope:"http_envelope",httpStatus:503,retryable:true},{wireCode:"webhook_endpoint_update_empty",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_endpoint_update_invalid",envelope:"http_envelope",httpStatus:400,retryable:false},{wireCode:"webhook_url_rejected",envelope:"http_envelope",httpStatus:400,retryable:false}],r=/* @__PURE__ */Object.freeze(t.map(e=>/* @__PURE__ */Object.freeze(e)));/* @__PURE__ */Object.freeze(r.map(e=>e.wireCode));var n=/* @__PURE__ */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",session_revoked:"authExpired",anonTokenInvalid:"authRejected",accessDenied:"accessDenied",invalidRequest:"sdkUpdateRequired",authRejected:"authRejected",rateLimited:"rateLimited",insufficientCapability:"accessDenied",unrestrictedKeyRequired:"accessDenied",user_ref_invalid:"validationFailed",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",linked_account_read_only:"conflict",catalog_empty_refused:"conflict",catalog_shrink_refused:"conflict",endpoint_not_allowed:"validationFailed",event_id_invalid:"validationFailed",inbox_cursor_invalid:"validationFailed",item_id_invalid:"validationFailed",open_url_not_allowed:"validationFailed",read_target_invalid:"validationFailed",subscription_keys_invalid:"validationFailed",web_push_unavailable:"serviceUnavailable",anchor_not_found:"resourceNotFound",anchor_ref_invalid:"validationFailed",before_invalid:"validationFailed",bundle_mismatch:"validationFailed",bundle_not_uploaded:"validationFailed",bundles_unavailable:"serviceUnavailable",environment_mismatch:"validationFailed",restricted_key:"accessDenied",ticket_not_resolved:"conflict",tickets_disabled:"resourceNotFound",timezone_invalid:"validationFailed"}),o=/* @__PURE__ */Object.freeze(r.map(e=>/* @__PURE__ */Object.freeze({wireCode:e.wireCode,envelope:e.envelope,retryable:e.retryable,normalized:n[e.wireCode]}))),a=new Map(o.map(e=>[e.envelope+e.wireCode.toUpperCase(),e])),l=/* @__PURE__ */Object.freeze(["http_envelope",...[...new Set(o.map(e=>e.envelope))].filter(e=>e!=="http_envelope").sort()]);function contractErrorFor(e,t){if(typeof e!="string")return;let r=e.trim().toUpperCase();if(r.length!==0)for(let e of[t??"http_envelope",...l]){let t=a.get(e+r);if(t)return t}}function contractDocUrl(e){return e.envelope==="sse_frame"?`/errors#sse-${e.wireCode}`:e.envelope==="oauth_error"?`/errors#oauth-${e.wireCode}`:`/errors#${e.wireCode}`}var i=null;function publishedDocUrl(e){return null}var s=/* @__PURE__ */Object.freeze(["authExpired","authRejected","sessionRequired","accessDenied","paymentRequired","quotaExceeded","rateLimited","validationFailed","sdkUpdateRequired","conflict","idempotencyConflict","idempotencyInFlight","conversationNotFound","petNotFound","resourceNotFound","streamTimeout","mediaUploadFailed","moderationBlocked","upstreamLlmTimeout","internalError","notImplemented","serviceUnavailable","streamIncomplete","identitySignatureRequired","runtimeDisposed","unknown"]),u=/* @__PURE__ */Object.freeze(["authentication","authorization","entitlement","rateLimit","invalidRequest","notFound","conflict","connection","server","media","policy","unknown"]),c=/* @__PURE__ */Object.freeze({authExpired:"authentication",authRejected:"authentication",sessionRequired:"authentication",identitySignatureRequired:"authentication",accessDenied:"authorization",paymentRequired:"entitlement",quotaExceeded:"rateLimit",rateLimited:"rateLimit",validationFailed:"invalidRequest",sdkUpdateRequired:"invalidRequest",runtimeDisposed:"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 categoryFor(e){return c[e]}function fromWire(e){let t=contractErrorFor(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"IDENTITYSIGNATUREREQUIRED":return"identitySignatureRequired";case"FREECAPREACHED":return"paymentRequired";case"RUNTIMEDISPOSED":return"runtimeDisposed";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"}}function fromHttpStatus(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"}var d=/* @__PURE__ */new Set(["streamTimeout","rateLimited","internalError","upstreamLlmTimeout","streamIncomplete"]);function isAutoRetryable(e){return d.has(e)}var f=/* @__PURE__ */new Set(["serviceUnavailable","conflict","idempotencyInFlight"]);function isRetryableCode(e){return isAutoRetryable(e)||f.has(e)}function shouldRetry(e,t=false){return t||isAutoRetryable(e)}var p=500,h=8e3,b=4;function backoffDelayMs(e,t=Math.random){let r=Math.max(0,e),n=Math.min(p*2**r,h);return Math.floor(t()*n)}function canRecreateOnNotFound(e){return e==="conversationNotFound"}var g="This feature isn't available on your account right now.",m="Something in that request was not right. Check the details and try again.",y=/* @__PURE__ */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:g,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:m,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.",identitySignatureRequired:g,runtimeDisposed:m,unknown:"Something went wrong. Please try again."}),v="This session has ended. Please sign in again.",_="linked_account_read_only";function isLinkedAccountReadOnly(e){return e!=null&&e.code==="conflict"&&e.reasonCode===_}function k(e,t,r){return e==="conflict"&&r===_?g:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?v:userFacingError(e)}function userFacingError(e){return y[e]}function w(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var C=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===_,o={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:k(e,t?.wireCode,n?_:null)};t?.httpStatus!==void 0&&(o.httpStatus=t.httpStatus),t?.requestId&&(o.requestId=t.requestId),typeof t?.reasonCode=="string"&&C.test(t.reasonCode)&&(o.reasonCode=t.reasonCode);let a=t?.retryAfterSeconds;if(typeof a=="number"&&Number.isFinite(a)&&a>=0&&(o.retryAfterSeconds=Math.round(a)),r);return t?.wireMessage&&w(o,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&w(o,"raw",t.raw),/* @__PURE__ */Object.freeze(o)}function ok(e,t){/* @__PURE__ */
|
|
3
3
|
return Object.freeze(t===void 0?{ok:true,value:e}:{ok:true,value:e,warning:t})}function err(e){/* @__PURE__ */
|
|
4
|
-
return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var x=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new x(e.error)}var F=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var S=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;var E=64,O=/^[A-Za-z0-9._+() -]+$/;function j(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>E?null:O.test(t)?t:null}var z="1.
|
|
4
|
+
return Object.freeze({ok:false,error:e})}function isOk(e){return e.ok}function isErr(e){return!e.ok}var x=class _EverfurThrownError extends Error{constructor(e){super(`${e.code}: ${e.displayMessage}`),this.name="EverfurThrownError",this.error=e,this.code=e.code,this.category=e.category,Object.setPrototypeOf(this,_EverfurThrownError.prototype)}};function unwrap(e){if(e.ok)return e.value;throw new x(e.error)}var F=class _EverfurConfigError extends Error{constructor(e,t){super(t),this.name="EverfurConfigError",this.kind=e,Object.setPrototypeOf(this,_EverfurConfigError.prototype)}};var S=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;var E=64,O=/^[A-Za-z0-9._+() -]+$/;function j(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>E?null:O.test(t)?t:null}var z="1.6.0";var A="react-native",I="2026-09-19",R="EVERFUR_API_BASE_URL";function B(e,t){/* @__PURE__ */
|
|
5
5
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:e,message:t})})}function checkPublishableKey(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}function tryResolveClientConfig(e,t){let r=checkPublishableKey(e?.publishableKey);if(r!==null)/* @__PURE__ */
|
|
6
6
|
return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),o=tryResolveApiBaseUrl(e.apiBaseUrl);if(!o.ok)return o;let a=e.contractVersion?.trim()||I,l=j(e.appVersion);/* @__PURE__ */
|
|
7
7
|
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:o.value,contractVersion:a,sdkVersion:z,platform:t?.platform??A,debug:e.debug===true,...l!==null?{appVersion:l}:{}})})}function resolveClientConfig(e,t){let r=tryResolveClientConfig(e,t);if(!r.ok)throw new F("invalid-argument",r.failure.message);return r.config}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:P(R);return r?U(r):B("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${R}. The SDK never ships a hardcoded host.`)}function resolveApiBaseUrl(e){let t=tryResolveApiBaseUrl(e);if(!t.ok)throw new F("invalid-argument",t.failure.message);return t.value}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function T(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function N(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function D(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:N(t)}function M(e,t){return`${e}://${t}`}function U(e){let t=e.trim(),r=S.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return B("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),o=T(r[2]);if(o.length===0)return B("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let a=D(t,o)?`: ${M(n,o)}`:"";if(n!=="https"){if(!(n==="http"&&$(o)))return n==="http"?B("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${a}`):B("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${a}`)}let l=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import { U as UserRef, P as PetRef } from './ids.d-B2GAAifq.js';
|
|
4
4
|
import { C as CapabilityName, a as CapabilityDecision } from './resolve.d-BTC3b6FW.js';
|
|
5
|
-
import { S as SecureStorePort, c as LogSink, a as EverfurEventHandler, g as EverfurRuntime } from './runtimeTypes.d-
|
|
5
|
+
import { S as SecureStorePort, c as LogSink, a as EverfurEventHandler, g as EverfurRuntime } from './runtimeTypes.d-hjN6xvxm.js';
|
|
6
6
|
import { T as TokenProvider } from './identity.d-D4VtpqRr.js';
|
|
7
7
|
import { T as TransportPort } from './config.d-B7Z-KTGq.js';
|
|
8
8
|
import { K as KvPort, I as ImageCachePort } from './cacheEpoch.d-DknKn3S0.js';
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
import { ReactNode } from 'react';
|
|
3
3
|
import { U as UserRef, P as PetRef } from './ids.d-B2GAAifq.cjs';
|
|
4
4
|
import { C as CapabilityName, a as CapabilityDecision } from './resolve.d-BTC3b6FW.cjs';
|
|
5
|
-
import { S as SecureStorePort, c as LogSink, a as EverfurEventHandler, g as EverfurRuntime } from './runtimeTypes.d-
|
|
5
|
+
import { S as SecureStorePort, c as LogSink, a as EverfurEventHandler, g as EverfurRuntime } from './runtimeTypes.d-BSxuUCOX.cjs';
|
|
6
6
|
import { T as TokenProvider } from './identity.d-DDpXOtas.cjs';
|
|
7
7
|
import { T as TransportPort } from './config.d-ClAI2RZ6.cjs';
|
|
8
8
|
import { K as KvPort, I as ImageCachePort } from './cacheEpoch.d-DknKn3S0.cjs';
|
package/dist/core/index.cjs
CHANGED
|
@@ -11,7 +11,7 @@ return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryab
|
|
|
11
11
|
return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}function analysisCompleteFrame(e,t=null){/* @__PURE__ */
|
|
12
12
|
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:/* @__PURE__ */Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}function unknownFrame(e,t,r=null){/* @__PURE__ */
|
|
13
13
|
return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var w="/widget/v1/anon-identity",C="x-everfur-anon-token",k="anonTokenInvalid";function z(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let i=null,s=null,a=null,l=null,o=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>i!==null&&(i.ttlMs===null||o(i.mintedAtMs)<i.ttlMs-2592e5),d=()=>i!==null&&(i.ttlMs===null||o(i.mintedAtMs)<i.ttlMs)?i.token:null,h=()=>s||(s=(async()=>{try{let s=null,l={method:"POST",path:w,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{s=e("date")}},o=await e.request(l),u=o.ok?o.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(a=n(),d()):(i={token:c,mintedAtMs:n(),ttlMs:z(u?.expires_at,s)},a=null,c)}catch{return a=n(),d()}finally{s=null}})(),s);return{token(e){return e?.forceRefresh?s||(u(l,3e4)?Promise.resolve(i?.token??null):(l=n(),i=null,h())):c()||u(a,3e5)?Promise.resolve(d()):h()}}}async function I(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}var S="This feature isn't available on your account right now.",O="Something in that request was not right. Check the details and try again.",j=/* @__PURE__ */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:S,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:O,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.",identitySignatureRequired:S,runtimeDisposed:O,unknown:"Something went wrong. Please try again."}),E="This session has ended. Please sign in again.",R="linked_account_read_only";function T(e,t,r){return e==="conflict"&&r===R?S:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?E:userFacingError(e)}function userFacingError(e){return j[e]}function A(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var x=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===R,i={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:T(e,t?.wireCode,n?R:null)};t?.httpStatus!==void 0&&(i.httpStatus=t.httpStatus),t?.requestId&&(i.requestId=t.requestId),typeof t?.reasonCode=="string"&&x.test(t.reasonCode)&&(i.reasonCode=t.reasonCode);let s=t?.retryAfterSeconds;if(typeof s=="number"&&Number.isFinite(s)&&s>=0&&(i.retryAfterSeconds=Math.round(s)),r);return t?.wireMessage&&A(i,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&A(i,"raw",t.raw),/* @__PURE__ */Object.freeze(i)}function F(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(userRef,e,r,n){let i=null,s=false,a=null,l=false,o=()=>a||(a=(async()=>{try{let n=await e(),a=typeof n=="string"?n:n?.token;if(typeof a!="string"||a.length===0)throw new t("invalid-argument","TokenProvider returned an empty token");return i=a,s=!1,r?.(typeof n=="string"?null:P(n.expiresAt)),a}finally{a=null}})(),a);return{userRef:userRef,async currentToken(e){if(l)throw new t("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(i=null),i!==null?i:o()},hasToken(){return!l&&i!==null},clear(){l=true,i=null},reportRejected(){l||s||(s=true,n?.())}}}function P(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}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].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("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[C]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...D(e.headers),...authHeaders(t)}}}function D(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===C||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await I(t),n=await t.transport.request(withAuthHeaders(e,M(t,r)));if(n.ok||U(n.error.raw)!==k||t.anonIdentity===void 0||t.userRef!==null)return n;let i=await t.anonIdentity.token({forceRefresh:true});return i===null||i===r?n:t.transport.request(withAuthHeaders(e,M(t,i)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(F(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let i;try{i=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(F(e,{wireCode:U(n.error.raw),requestId:n.error.requestId}))}let s=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:i,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!s.ok&&s.error.httpStatus===401?(t.identity.reportRejected?.(),err(N(s.error))):s}function M(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function N(e){let t=e.raw,r=U(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function U(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var $="DAILY_QUOTA_EXCEEDED",L=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function q(e,t){if(!L.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?$:e}var B="free_cap_reached";function H(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function K(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==B&&n.code!==B)return null;let i=H(n.limit),s=H(n.used);if(i===null||s===null)return null;let a=n.resets_at,l=n.emergency_guidance;/* @__PURE__ */
|
|
14
|
-
return Object.freeze({limit:i,used:s,resetsAt:typeof a=="string"&&a.length>0?a:null,...typeof l=="string"&&l.trim().length>0?{emergencyGuidance:l}:{}})}function V(){let e=[];return{decode(t,r){let n=r?.stream===true,i=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)i.push(t[e]);e=[];let s="",a=0;for(;a<i.length;){let t=i[a];if(t<128){s+=String.fromCharCode(t),a+=1;continue}let r,l=128,o=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(l=160),t===237&&(o=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(l=144),t===244&&(o=143);else{s+="�",a+=1;continue}let c=1,d=true;for(;c<=r&&!(a+c>=i.length);){let e=i[a+c],t=c===1?l:128,r=c===1?o:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){s+="�",a+=c;continue}if(c<=r){n?e=i.slice(a):s+="�";break}s+=String.fromCodePoint(u),a+=r+1}return s}}}function G(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):V()}var W=`\n\n`,Y=1048576,X=/* @__PURE__ */e.z.record(/* @__PURE__ */e.z.string(),/* @__PURE__ */e.z.unknown()),Q=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),i=G(),s="",a=0,l=false;for await(let t of e){for(s+=i.decode(t,{stream:true});;){let e=s.indexOf(W,a);if(e===-1)break;let t=s.slice(0,e);s=s.slice(e+W.length),a=0;let r=J(t,n());if(r!==null&&(r.kind==="delta"&&(l=true),yield r,r.terminal))return}if(a=s.length>0?s.length-1:0,s.length>Y){yield errorFrame({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=i.decode(),s.trim().length>0){let e=J(s,n());if(e!==null&&(e.kind==="delta"&&(l=true),yield e,e.terminal))return}yield errorFrame({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function J(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let i;try{i=JSON.parse(n.join(`\n`))}catch{return null}if(typeof i!="object"||i===null||Array.isArray(i))return null;let s=X.safeParse(i);return s.success?Z(s.data,r,t):null}function Z(e,t,r){let n=e.type,i=e.event;if(n==="error"||"error"in e)return errorFrame({code:ee(e.code)??"unknown",retryable:e.retryable===true,wireMessage:ee(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:K(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:ee(e.conversation_id)??"",messageId:ee(e.message_id),title:ee(e.title),followUpQuestions:ie(e.follow_up_questions),citations:ae(e.citations),citationStatus:ee(e.citation_status),urgencyLevel:re(e.urgency_level),urgencyReason:ee(e.urgency_reason),urgencyProvided:ne(e),resultId:ee(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(ee(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=ee(e.delta)??ee(e.token)??"";return deltaFrame(n,t,r)}return i==="analysis_started"?analysisStartedFrame(ee(e.request_id),t,r):i==="analysis_complete"?analysisCompleteFrame({resultId:ee(e.result_id),analysisType:ee(e.analysis_type),modelVersion:ee(e.model_version),confidence:te(e.confidence),detections:ae(e.detections),interpretation:ee(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function ee(e){return typeof e=="string"?e:null}function te(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function re(e){return typeof e=="string"&&Q.includes(e)?e:null}function ne(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||re(t)!==null}function ie(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ae(e){return Array.isArray(e)?e.filter(se):[]}var le=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function oe(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return he(e,t)}var ue=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,ce=/[\s\u0000-\u001f\u007f\\]/,de={"http:":"80","https:":"443"};function he(e,t){let r=e.trim();if(t!==void 0&&!le.test(r)){let e=he(t);if(e===null||!r.startsWith("/")||r.startsWith("//"))return null;r=e.origin+r}let n=ce.test(r)?null:ue.exec(r);if(n===null)return null;let[,i="",s="",a="",l="",o="",u="",c="",d=""]=n,h=`${i.toLowerCase()}:`,f=Number(o);if(f>65535)return null;let p=o===""||String(f)===de[h]?"":String(f),g=de[h]!==void 0,m=l.toLowerCase()+(p&&`:${p}`),y=u||(g?"/":""),v=s||a?`${s}${a&&`:${a}`}@`:"";return{href:`${h}//${v}${m}${y}${c}${d}`,protocol:h,username:s,password:a,hostname:l.toLowerCase(),port:p,origin:g?`${h}//${m}`:"null",pathname:y,search:c==="?"?"":c,hash:d==="#"?"":d}}function fe(e,t,r){return{...e,surface:t,requestId:r||null}}var pe=64,ge=/^[A-Za-z0-9._+() -]+$/;function me(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>pe?null:ge.test(t)?t:null}var ye="1.
|
|
14
|
+
return Object.freeze({limit:i,used:s,resetsAt:typeof a=="string"&&a.length>0?a:null,...typeof l=="string"&&l.trim().length>0?{emergencyGuidance:l}:{}})}function V(){let e=[];return{decode(t,r){let n=r?.stream===true,i=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)i.push(t[e]);e=[];let s="",a=0;for(;a<i.length;){let t=i[a];if(t<128){s+=String.fromCharCode(t),a+=1;continue}let r,l=128,o=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(l=160),t===237&&(o=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(l=144),t===244&&(o=143);else{s+="�",a+=1;continue}let c=1,d=true;for(;c<=r&&!(a+c>=i.length);){let e=i[a+c],t=c===1?l:128,r=c===1?o:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){s+="�",a+=c;continue}if(c<=r){n?e=i.slice(a):s+="�";break}s+=String.fromCodePoint(u),a+=r+1}return s}}}function G(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):V()}var W=`\n\n`,Y=1048576,X=/* @__PURE__ */e.z.record(/* @__PURE__ */e.z.string(),/* @__PURE__ */e.z.unknown()),Q=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),i=G(),s="",a=0,l=false;for await(let t of e){for(s+=i.decode(t,{stream:true});;){let e=s.indexOf(W,a);if(e===-1)break;let t=s.slice(0,e);s=s.slice(e+W.length),a=0;let r=J(t,n());if(r!==null&&(r.kind==="delta"&&(l=true),yield r,r.terminal))return}if(a=s.length>0?s.length-1:0,s.length>Y){yield errorFrame({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(s+=i.decode(),s.trim().length>0){let e=J(s,n());if(e!==null&&(e.kind==="delta"&&(l=true),yield e,e.terminal))return}yield errorFrame({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function J(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let i;try{i=JSON.parse(n.join(`\n`))}catch{return null}if(typeof i!="object"||i===null||Array.isArray(i))return null;let s=X.safeParse(i);return s.success?Z(s.data,r,t):null}function Z(e,t,r){let n=e.type,i=e.event;if(n==="error"||"error"in e)return errorFrame({code:ee(e.code)??"unknown",retryable:e.retryable===true,wireMessage:ee(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:K(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:ee(e.conversation_id)??"",messageId:ee(e.message_id),title:ee(e.title),followUpQuestions:ie(e.follow_up_questions),citations:ae(e.citations),citationStatus:ee(e.citation_status),urgencyLevel:re(e.urgency_level),urgencyReason:ee(e.urgency_reason),urgencyProvided:ne(e),resultId:ee(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(ee(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=ee(e.delta)??ee(e.token)??"";return deltaFrame(n,t,r)}return i==="analysis_started"?analysisStartedFrame(ee(e.request_id),t,r):i==="analysis_complete"?analysisCompleteFrame({resultId:ee(e.result_id),analysisType:ee(e.analysis_type),modelVersion:ee(e.model_version),confidence:te(e.confidence),detections:ae(e.detections),interpretation:ee(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function ee(e){return typeof e=="string"?e:null}function te(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function re(e){return typeof e=="string"&&Q.includes(e)?e:null}function ne(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||re(t)!==null}function ie(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function se(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function ae(e){return Array.isArray(e)?e.filter(se):[]}var le=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function oe(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return he(e,t)}var ue=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,ce=/[\s\u0000-\u001f\u007f\\]/,de={"http:":"80","https:":"443"};function he(e,t){let r=e.trim();if(t!==void 0&&!le.test(r)){let e=he(t);if(e===null||!r.startsWith("/")||r.startsWith("//"))return null;r=e.origin+r}let n=ce.test(r)?null:ue.exec(r);if(n===null)return null;let[,i="",s="",a="",l="",o="",u="",c="",d=""]=n,h=`${i.toLowerCase()}:`,f=Number(o);if(f>65535)return null;let p=o===""||String(f)===de[h]?"":String(f),g=de[h]!==void 0,m=l.toLowerCase()+(p&&`:${p}`),y=u||(g?"/":""),v=s||a?`${s}${a&&`:${a}`}@`:"";return{href:`${h}//${v}${m}${y}${c}${d}`,protocol:h,username:s,password:a,hostname:l.toLowerCase(),port:p,origin:g?`${h}//${m}`:"null",pathname:y,search:c==="?"?"":c,hash:d==="#"?"":d}}function fe(e,t,r){return{...e,surface:t,requestId:r||null}}var pe=64,ge=/^[A-Za-z0-9._+() -]+$/;function me(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>pe?null:ge.test(t)?t:null}var ye="1.6.0";var ve="react-native",be="2026-09-19",_e="EVERFUR_API_BASE_URL";function we(e,t){/* @__PURE__ */
|
|
15
15
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:e,message:t})})}function checkPublishableKey(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}function tryResolveClientConfig(e,t){let r=checkPublishableKey(e?.publishableKey);if(r!==null)/* @__PURE__ */
|
|
16
16
|
return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),i=tryResolveApiBaseUrl(e.apiBaseUrl);if(!i.ok)return i;let s=e.contractVersion?.trim()||be,a=me(e.appVersion);/* @__PURE__ */
|
|
17
17
|
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:i.value,contractVersion:s,sdkVersion:ye,platform:t?.platform??ve,debug:e.debug===true,...a!==null?{appVersion:a}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:je(_e);return r?Se(r):we("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${_e}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function Ce(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function ke(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function ze(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:ke(t)}function Ie(e,t){return`${e}://${t}`}function Se(e){let t=e.trim(),r=le.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return we("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),i=Ce(r[2]);if(i.length===0)return we("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let s=ze(t,i)?`: ${Ie(n,i)}`:"";if(n!=="https"){if(!(n==="http"&&Oe(i)))return n==="http"?we("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${s}`):we("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${s}`)}let a=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
|
|
@@ -24,7 +24,7 @@ return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function qt(e){
|
|
|
24
24
|
return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function Bt(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),/* @__PURE__ */Object.freeze(r)}function Ht(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,/* @__PURE__ */Object.freeze(r)}function Kt(e){/* @__PURE__ */
|
|
25
25
|
return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function Vt(e,t,r){return makeEverfurError(e,{retryable:t,...r?{wireMessage:r}:{}})}function Gt(e){let t=fromWire(e.code);return makeEverfurError(t,{retryable:e.retryable||shouldRetry(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}function Wt(e){return errorFrame({code:Yt(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}function Yt(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"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(e)}}function Xt(e){let t=Array.isArray(e)?e:Jt(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let e of t){if(!Jt(e))continue;let t=Zt(e.category)??Zt(e.title)??"",n=er(e.prompts??e.questions);t.length===0&&n.length===0||r.push(/* @__PURE__ */Object.freeze({category:t,prompts:/* @__PURE__ */Object.freeze(n)}))}/* @__PURE__ */
|
|
26
26
|
return Object.freeze(r)}function Qt(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zt(e){return typeof e=="string"?e:null}function er(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Jt(r)){let e=Zt(r.text)??Zt(r.prompt)??Zt(r.title);e!==null&&t.push(e)}return t}function tr(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function rr(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function nr(){return typeof Symbol=="function"?Symbol.asyncIterator:void 0}function ir(e){let t=e,r=nr(),n=(r!==void 0?t[r]:void 0)??t["@@asyncIterator"];if(typeof n=="function")return n.call(e);let i=typeof Symbol=="function"?t[Symbol.iterator]:void 0;if(typeof i=="function"){let t=i.call(e);return{next:()=>Promise.resolve(t.next()),return:e=>Promise.resolve(t.return?.(e)??{done:true,value:void 0})}}return null}var sr={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*ar(e,t,r,n){let i=ir(e);if(i===null){yield or();return}let s=ur(t.overallMs,n),a=ur(t.idleMs,n),l=cr(r);try{for(;;){if(r.aborted)return;let e=i.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,a.promise.then(()=>({tag:"idle"})),s.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield or();return}if(n.tag==="idle"||n.tag==="overall"){yield lr();return}let o=n.value;if(o.done||(a.reset(t.idleMs),yield o.value,o.value.terminal))return}}finally{a.cancel(),s.cancel(),Promise.resolve(i.return?.(void 0)).catch(()=>{})}}function lr(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function or(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function ur(e,t){let r=()=>{},n=new Promise(e=>{r=e}),i=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(i),i=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(i)}}}function cr(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var dr="checkin",hr=/^\d{4}-\d{2}-\d{2}$/,fr="watching";function pr(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r!==void 0){if(r.role==="user")return null;if(r.role==="assistant"){if(r.checkin!==void 0)return r.checkin.answer!==null||isCheckinSettled(r.checkin)?null:r;if(typeof r.proactiveOriginRef=="string"&&r.proactiveOriginRef.length>0)return r}}}return null}function gr(e){if(e===null||typeof e!="object")return null;let t=e,conversationId=t.conversation_id,r=t.message_id,n=t.question,i=t.occasion_ref;if(typeof conversationId!="string"||conversationId.length===0||typeof r!="string"||r.length===0||typeof n!="string"||n.trim().length===0)return null;let s=typeof i=="string"&&i.length>0?i:null,a=yr(s),l=a===null?null:/* @__PURE__ */Object.freeze({caseId:a.caseId,answer:null,resolutionText:null,status:null}),o=typeof t.created_at=="string"?t.created_at:"",u=/* @__PURE__ */Object.freeze({id:r,role:"assistant",text:n,createdAt:o,...s===null?{}:{proactiveOriginRef:s},...l===null?{}:{checkin:l}});/* @__PURE__ */
|
|
27
|
-
return Object.freeze({conversationId:conversationId,message:u,checkin:l,occasionRef:s})}function isCheckinSettled(e){return e.status!=null&&e.status!==fr}function mr(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}function yr(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,i]=t;return r!==dr||n===void 0||i===void 0||!Ot.test(n)||!hr.test(i)?null:{caseId:n,dueDay:i}}function vr(e){return yr(e)?.caseId??null}function br(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||zt(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function _r(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)}function wr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Cr(e){return e==null||typeof e=="string"&&e.length>0&&!zt(e)}function kr(){return err(makeEverfurError("internalError",{retryable:false}))}function zr(e){let t=wr(e);if(!t||!Array.isArray(t.conversations)||!Cr(t.next_cursor))return kr();let r=[];for(let e of t.conversations){let t=wr(e);if(!t||typeof t.conversation_id!="string"||!_r(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return kr();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return kr();let i=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...i.length>0?{preview:i}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Ir(e){let t=wr(e);if(!t||!Array.isArray(t.messages)||!Cr(t.next_cursor))return kr();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=wr(e);if(!t||typeof t.message_id!="string"||!_r(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return kr();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(Sr(t,t.message_id,t.content,t.created_at));continue}let i=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,s=t.role==="assistant"?vr(i):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:jr(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:Er(t.citations)}:{},...i!==null?{proactiveOriginRef:i}:{},...s!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:s,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Sr(e,t,r,n){let i=wr(e.sender),s=Or(i?.display_name)??Or(e.sender_display_name),a=Or(i?.specialty);/* @__PURE__ */
|
|
27
|
+
return Object.freeze({conversationId:conversationId,message:u,checkin:l,occasionRef:s})}function isCheckinSettled(e){return e.status!=null&&e.status!==fr}function mr(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}function yr(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,i]=t;return r!==dr||n===void 0||i===void 0||!Ot.test(n)||!hr.test(i)?null:{caseId:n,dueDay:i}}function vr(e){return yr(e)?.caseId??null}function br(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||zt(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function _r(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)}function wr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Cr(e){return e==null||typeof e=="string"&&e.length>0&&!zt(e)}function kr(){return err(makeEverfurError("internalError",{retryable:false}))}function zr(e){let t=wr(e);if(!t||!Array.isArray(t.conversations)||!Cr(t.next_cursor))return kr();let r=[];for(let e of t.conversations){let t=wr(e);if(!t||typeof t.conversation_id!="string"||!_r(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return kr();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return kr();let i=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...i.length>0?{preview:i}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Ir(e){let t=wr(e);if(!t||!Array.isArray(t.messages)||!Cr(t.next_cursor))return kr();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=wr(e);if(!t||typeof t.message_id!="string"||!_r(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return kr();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(Sr(t,t.message_id,t.content,t.created_at));continue}let i=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,s=t.role==="assistant"?vr(i):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:jr(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:Er(t.citations)}:{},...i!==null?{proactiveOriginRef:i}:{},...s!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:s,answer:null,resolutionText:null,status:null})}:{},...t.a2ui?{a2ui:[t.a2ui]}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Sr(e,t,r,n){let i=wr(e.sender),s=Or(i?.display_name)??Or(e.sender_display_name),a=Or(i?.specialty);/* @__PURE__ */
|
|
28
28
|
return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:s,specialty:a})})}function Or(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!zt(t)?t:null}function jr(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function Er(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
|
|
29
29
|
return Object.freeze(e.flatMap(e=>{let r=wr(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function Rr(e,t,r){let n=new Set(e.map(e=>e.id)),i=e.filter(e=>r.has(e.id)),s=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=i.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){i.splice(r,1);continue}s.push(e)}return s}var Tr=5,Ar=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),xr=4e3;var Fr=4e3;function Pr(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:Vt("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:Vt("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function Dr(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:Vt("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>Fr?{reason:"too_long",error:Vt("validationFailed",false,`message is ${r} characters; the server accepts at most ${Fr}`)}:null}function Mr(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Nr(e){yield e}async function*Ur(){}var $r=6e4,Lr=18e4,qr=24,Br=512,Hr=false;function createChatController(e){return new Wr(e)}function Kr(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function Vr(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function Gr(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var Wr=class extends Ut{constructor(e){super(Kt({status:"idle",messages:[],conversationId:e.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */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.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=Ft(this.funnel),this.telemetry=e.telemetry??n,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??m,this.timers=e.timers??sr,this.rng=e.rng??Math.random,this.newId=e.newId??tr(),this.makeIdempotencyKey=e.makeIdempotencyKey??rr(),this.budget={idleMs:e.budget?.idleMs??$r,overallMs:e.budget?.overallMs??Lr}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=Vt(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Nr(Wt(e))}let i=Dr(e)??Pr(n.imageS3Keys);if(i!==null)return this.telemetry.track("chat.send.rejected",{reason:i.reason}),this.patch({status:"error",isStreaming:false,error:i.error}),r?(r.onError(i.error),()=>{}):Nr(Wt(i.error));if(r)return this.driveWithHandlers(e,n,r);let s=this.beginTurn(e,n);return this.runTurn(s,n.signal)}askEverfur(e,t){if(this.disposed)return Nr(Wt(Vt("accessDenied",false)));let r=Dr(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Nr(Wt(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):Ur()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,$t(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?qt(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(Qt(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=br(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Vt("accessDenied",false));let i=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(Vt("accessDenied",false));if(!i.ok)return i;let s=zr(i.value);if(s.ok){for(let e of s.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=s.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,s.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return s}reportCheckinSkips(petRef){let e=[];petRef===null&&e.push("no_pet"),this.auth.userRef===null&&e.push("no_member");for(let t of e)this.reportCheckinSkip(t)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(petRef){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let e=this.epoch,t=petRef===null?"":`?pet_ref=${encodeURIComponent(String(petRef))}`,r=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${t}`},void 0,{maxAttempts:1});if(!this.alive(e)||this.disposed)return null;if(this.cardsInFlight=false,r.ok){this.cardsRoute="served";let e=r.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],n=[];for(let e of t){let t=gr(e);t===null?this.reportCheckinSkip("card_unreadable"):n.push(this.withAnsweredCase(t))}return this.pendingCards=n,this.syncPendingCheckin(),null}if(r.error.category!=="notFound"&&r.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),Vr(r.error)?r.error:null;if(r.error.category==="notFound"&&Gr(r.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let i=pr(n.value.messages);i===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:i,checkin:i.checkin??null,occasionRef:i.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}Kr(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(Vt("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let petRef=e?.petRef??this.petRef,r=await this.listConversations({...petRef===null?{}:{petRef:petRef},limit:1});if(!r.ok)return err(r.error);let n=r.value.conversations[0];if(n===void 0)return ok(null);let i=await this.resumeConversation(n.id);return i.ok?ok(n.id):err(i.error)}async markRead(e){if(this.disposed)return err(Vt("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(Vt("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(Vt("accessDenied",false));if(typeof e!="string"||e.trim().length===0||zt(e))return err(Vt("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Ar.includes(t))return err(Vt("validationFailed",false,`feedback_type must be one of ${Ar.join(", ")}`));let i=typeof r=="string"?r.trim():"";if([...i].length>xr)return err(Vt("validationFailed",false,`notes is over ${xr} characters`));let s={feedback_type:t};i.length>0&&(s.notes=i);let a=this.epoch,l=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:s},n?.signal);if(!this.alive(a)||this.disposed)return err(Vt("accessDenied",false));if(!l.ok)return err(l.error);let o=l.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof o=="string"?o:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(Vt("accessDenied",false));let petRef=r?.petRef??this.petRef;if(petRef===null)return err(Vt("validationFailed",false,"a check-in needs the pet the case belongs to"));let n=this.epoch,i=await this.cases.checkin(petRef,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(n)||this.disposed)return err(Vt("accessDenied",false));if(!i.ok)return i;let s=i.value.case.openedAt,a=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...s!==null?{openedAt:s}:{}}),l=t=>t.checkin?.caseId===e;this.snapshot.messages.some(l)&&this.patch({messages:this.snapshot.messages.map(e=>l(e)?/* @__PURE__ */Object.freeze({...e,checkin:a}):e)}),this.answeredCases.set(e,a);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:a}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!_r(e))return err(Vt("validationFailed",false));let r=br(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Vt("accessDenied",false));let i=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(Vt("accessDenied",false)):i.ok?Ir(i.value):i}async resumeConversation(e){if(this.disposed)return err(Vt("accessDenied",false));if(!_r(e))return err(Vt("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(Vt("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let petRef=this.petRef;if(petRef===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let t=await this.cases.list(petRef);if(!t.ok||e!==this.historyGeneration||this.disposed)return;let r=new Set(t.value.filter(e=>e.status===fr).map(e=>e.caseId)),n=new Map(t.value.map(e=>[e.caseId,e])),i=false,s=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let s=n.get(t.caseId),a=t.openedAt??s?.openedAt??null,l=r.has(t.caseId),o=s!==void 0&&(!l||mr({askCount:s.checkinAskCount,answerCount:s.checkinAnswerCount}))?s.lastResponse:null;/* @__PURE__ */
|
|
30
30
|
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:l?fr:s?.status??"resolved",answer:t.answer??o,resolutionText:t.resolutionText??s?.resolutionText??null,...a!==null?{openedAt:a}:{}})})});i&&this.patch({messages:s})}async refreshActiveThread(e){if(this.disposed)return err(Vt("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),i=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(Vt("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=i===null?null:await i;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let s=await this.resumeConversation(r.id);return s.ok?ok(void 0):err(s.error)}let s=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(Vt("accessDenied",false));if(!s.ok)return err(s.error);let a=Rr(this.snapshot.messages,s.value.messages,this.localRowIds);if(a.length>0&&this.patch({messages:[...this.snapshot.messages,...a]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&Vr(n.error))return err(n.error);let l=i===null?null:await i;return l!==null&&r===this.historyGeneration&&!this.disposed?err(l):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(Vt("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(Vt("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let i=new Set(this.snapshot.messages.map(e=>e.id)),s=n.value.messages.filter(e=>!i.has(e.id));return this.patch({messages:[...s,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield Wt(t.error))}async primeConversation(e){if(this.disposed)return err(Vt("accessDenied",false));let petRef=e?.petRef??null,t={petRef:petRef,settled:this.primeBounded(petRef)};this.unadoptedCreate=t;let r=await t.settled;return this.disposed?err(Vt("accessDenied",false)):(!r.ok&&this.unadoptedCreate===t&&(this.unadoptedCreate=null),r)}async primeBounded(petRef){let e=await this.headThreadWithUnread(petRef);return e.ok?e.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(e.value)).ok?ok(e.value):ok(this.snapshot.conversationId):e.error.code==="accessDenied"||e.error.httpStatus===403?ok(null):err(e.error)}async headThreadWithUnread(petRef){let e=await this.listConversationsWith({...petRef===null?{}:{petRef:petRef},limit:1},{maxAttempts:1});if(!e.ok)return err(e.error);let t=e.value.conversations[0];return t===void 0||t.unreadCount===null||t.unreadCount<=0?ok(null):ok(t.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(Vt("accessDenied",false));let petRef=e?.petRef??null,r={petRef:petRef,settled:this.createConversationBounded(petRef)};this.unadoptedCreate=r;let n=await r.settled;return!this.alive(t)||this.disposed?err(Vt("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async createConversationBounded(petRef,e){let t={method:"POST",path:"/widget/v1/conversations",body:petRef?{pet_ref:petRef}:{}},r=await this.authedUnary("chat.createConversation",t,e,{maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.conversation_id??r.value?.id;return typeof n!="string"||n.length===0?err(Vt("internalError",true)):ok(n)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(Vt("accessDenied",false));let petRef=e?.petRef??null;if(petRef!==null&&zt(petRef))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let r=petRef!==null?`?pet_ref=${encodeURIComponent(petRef)}`:"",n=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${r}`});return!this.alive(t)||this.disposed?err(Vt("accessDenied",false)):n.ok?ok(Xt(n.value)):err(n.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,i=Nt(n.signal,t.signal),s=this.beginTurn(e,t),a=this.runTurn(s,i),l=false,o=()=>{l||(l=true,n.abort(),this.handlerTeardowns.delete(o))};return this.handlerTeardowns.add(o),(async()=>{for await(let e of a){if(l)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!l&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(o)})(),o}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,$t(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,i=false,s=false,a=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,l=t?this.unadoptedCreate:null;if(l!==null&&(e.petRef===null||e.petRef===l.petRef)){let e=await l.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,Wt(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let o=e.conversationIdOverride??this.snapshot.conversationId;if(o===null){let t=Vt("internalError",!0);yield*this.emitTerminal(e,t,Wt(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=Nt(r.signal,u.signal),d=null,h=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,o))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,Wt(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;h=t.headers?.[C]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of ar(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=Vt("streamIncomplete",!0);yield*this.emitTerminal(e,t,Wt(t));return}let f=fromWire(d.code);if(f==="authExpired"&&this.auth.mode==="personalized"&&!s){s=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!a&&h!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===k||f==="authExpired")){a=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==h){this.patch({reconnecting:!0});continue}}if(f==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(f==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,Gt(d),d);return}if(canRecreateOnNotFound(f)&&!i){i=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(f,!0);if(Hr&&p&&n+1<this.errorPolicy.maxAttempts(f));yield*this.emitTerminal(e,Gt(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?qt(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,Lt(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=Br){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},qr)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?Bt(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?Ht(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?qt(e):e),Ht(Lt(r,"",this.stamp()),e)]}let i=Qt([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=i.length>0?/* @__PURE__ */Object.freeze(i):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(conversationId,e){if(e===null||this.disposed)return;let t=String(e);if(this.classifiedMessageIds.has(t))return;this.classifiedMessageIds.add(t);let r=this.epoch,n=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${conversationId}/classify`});if(!i.ok||!this.alive(r)||this.disposed||n!==this.historyGeneration||this.snapshot.conversationId!==conversationId)return;let s=Mr(i.value?.urgency),a=typeof i.value?.reason=="string"?i.value.reason:null,l=t=>t.responseId===e;this.snapshot.messages.some(l)&&this.patch({messages:this.snapshot.messages.map(e=>l(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:s,urgencyReason:a,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?qt(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?Vt("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,petRef=e.petRef??null,n=e.resumeConversationId??null,i=[],s=false,a=false,l=false,o=null,u=null,c=n?r.resumeConversation(n).then(e=>e.ok?ok(n):err(e.error)):r.primeConversation(petRef?{petRef:petRef}:void 0),d=r.getPrompts(petRef!==null?{petRef:petRef}:void 0),[h,f]=await Promise.all([c,d]),conversationId=null;if(h.ok)conversationId=h.value,h.value!==null&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;u=e,Xr(e)?(a=true,o=e):(Qr(e)&&(s=true),l=true)}let p=[];f.ok?p=f.value:g(f.error);function g(e){Xr(e)?(a=true,o===null&&(o=e)):Qr(e)&&(s=true)}let m=o!==null?o.displayMessage:null;/* @__PURE__ */
|
package/dist/core/index.d.cts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
|
|
2
2
|
export { K as KvPort } from '../cacheEpoch.d-DknKn3S0.cjs';
|
|
3
|
-
import { C as CreateEverfurRuntimeInput, g as EverfurRuntime } from '../runtimeTypes.d-
|
|
4
|
-
export { B as BeforeLogoutContext, h as BeforeLogoutHook, i as CapabilityKind, j as CapabilityRegistry, k as CapabilityServices, l as ChatControllerRegistry, m as ChatScope, f as EntitlementSnapshot, n as EntitlementStore, E as EverfurClientEvent, a as EverfurEventHandler, o as EverfurRuntimeConfig, L as LogLevel, b as LogRecord, c as LogSink, N as NULL_SECURE_STORE, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, R as RuntimeTheme, p as RuntimeUser, S as SecureStorePort } from '../runtimeTypes.d-
|
|
3
|
+
import { C as CreateEverfurRuntimeInput, g as EverfurRuntime } from '../runtimeTypes.d-BSxuUCOX.cjs';
|
|
4
|
+
export { B as BeforeLogoutContext, h as BeforeLogoutHook, i as CapabilityKind, j as CapabilityRegistry, k as CapabilityServices, l as ChatControllerRegistry, m as ChatScope, f as EntitlementSnapshot, n as EntitlementStore, E as EverfurClientEvent, a as EverfurEventHandler, o as EverfurRuntimeConfig, L as LogLevel, b as LogRecord, c as LogSink, N as NULL_SECURE_STORE, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, R as RuntimeTheme, p as RuntimeUser, S as SecureStorePort } from '../runtimeTypes.d-BSxuUCOX.cjs';
|
|
5
5
|
import { T as TelemetryPort } from '../TelemetryPort.d-BDNr00hu.cjs';
|
|
6
6
|
export { n as noopTelemetry } from '../TelemetryPort.d-BDNr00hu.cjs';
|
|
7
7
|
export { E as ErrorPolicyPort, a as EverfurErrorContext, d as defaultErrorPolicy } from '../ErrorPolicyPort.d-BIdmYQnk.cjs';
|
|
8
8
|
export { C as CameraPort, a as CaptureOptions, M as MediaSource, u as unavailableCamera } from '../CameraPort.d-Cv31Pz7g.cjs';
|
|
9
9
|
export { F as FileHandle, b as FilePort } from '../ports.d-BX4f4UsB.cjs';
|
|
10
10
|
export { O as OptionalModule, o as optionalModule } from '../optionalModule.d-DbJmsq5f.cjs';
|
|
11
|
-
import { p as ChatControllerDeps, o as ChatController, q as SuggestedPromptCategory } from '../checkin.d-
|
|
12
|
-
export { r as CHAT_FEEDBACK_TYPES, s as CHECKIN_ANSWERABLE_STATUS, C as ChatCheckin, a as ChatCheckinTarget, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, t as ChatHandlers, g as ChatHistoryOptions, j as ChatMessage, h as ChatMessagePage, k as ChatMessageRole, l as ChatMessageSender, u as ChatPendingCheckin, i as ChatRefreshOptions, v as ChatSnapshot, m as ChatStatus, n as Citation, F as FEEDBACK_NOTES_MAX_CHARS, M as MAX_IMAGE_KEYS_PER_MESSAGE, S as SendOptions, T as Timers, w as isCheckinSettled } from '../checkin.d-
|
|
11
|
+
import { p as ChatControllerDeps, o as ChatController, q as SuggestedPromptCategory } from '../checkin.d-CuIUahcd.cjs';
|
|
12
|
+
export { r as CHAT_FEEDBACK_TYPES, s as CHECKIN_ANSWERABLE_STATUS, C as ChatCheckin, a as ChatCheckinTarget, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, t as ChatHandlers, g as ChatHistoryOptions, j as ChatMessage, h as ChatMessagePage, k as ChatMessageRole, l as ChatMessageSender, u as ChatPendingCheckin, i as ChatRefreshOptions, v as ChatSnapshot, m as ChatStatus, n as Citation, F as FEEDBACK_NOTES_MAX_CHARS, M as MAX_IMAGE_KEYS_PER_MESSAGE, S as SendOptions, T as Timers, w as isCheckinSettled } from '../checkin.d-CuIUahcd.cjs';
|
|
13
13
|
import { E as EverfurError } from '../EverfurError.d-8NHtlgzA.cjs';
|
|
14
14
|
import { P as PetRef, C as ConversationId } from '../ids.d-B2GAAifq.cjs';
|
|
15
15
|
export { f as ATTACHMENT_ACCEPT, g as ATTACHMENT_BACKOFF_MS, h as ATTACHMENT_INITIATE_PATH, i as ATTACHMENT_MAX_ATTEMPTS, j as ATTACHMENT_MIME_TYPES, k as ATTACHMENT_QUEUE_CONCURRENCY, A as AttachmentError, a as AttachmentErrorCode, b as AttachmentOutcome, c as AttachmentQueue, l as AttachmentQueueDeps, m as AttachmentQueueSnapshot, d as AttachmentState, e as AttachmentStatus, n as AttachmentUploadPolicy, M as MAX_ATTACHMENTS_PER_MESSAGE, o as MAX_ATTACHMENT_BYTES, p as MAX_FILENAME_LENGTH, V as ValidatedAttachment, q as attachmentSize, r as createAttachmentQueue, s as formatBytes, t as initiateAttachmentUpload, u as isAttachmentMime, v as sanitizeFilename, w as uploadAttachmentBytes, x as validateAttachment } from '../attachments.d-CF4lLuGK.cjs';
|
package/dist/core/index.d.ts
CHANGED
|
@@ -1,15 +1,15 @@
|
|
|
1
1
|
/*! @everfur/sdk. Copyright (c) 2026 Strand Health Inc. dba Everfur. All rights reserved. Use is subject to the Everfur SDK License: https://docs.everfur.com/license */
|
|
2
2
|
export { K as KvPort } from '../cacheEpoch.d-DknKn3S0.js';
|
|
3
|
-
import { C as CreateEverfurRuntimeInput, g as EverfurRuntime } from '../runtimeTypes.d-
|
|
4
|
-
export { B as BeforeLogoutContext, h as BeforeLogoutHook, i as CapabilityKind, j as CapabilityRegistry, k as CapabilityServices, l as ChatControllerRegistry, m as ChatScope, f as EntitlementSnapshot, n as EntitlementStore, E as EverfurClientEvent, a as EverfurEventHandler, o as EverfurRuntimeConfig, L as LogLevel, b as LogRecord, c as LogSink, N as NULL_SECURE_STORE, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, R as RuntimeTheme, p as RuntimeUser, S as SecureStorePort } from '../runtimeTypes.d-
|
|
3
|
+
import { C as CreateEverfurRuntimeInput, g as EverfurRuntime } from '../runtimeTypes.d-hjN6xvxm.js';
|
|
4
|
+
export { B as BeforeLogoutContext, h as BeforeLogoutHook, i as CapabilityKind, j as CapabilityRegistry, k as CapabilityServices, l as ChatControllerRegistry, m as ChatScope, f as EntitlementSnapshot, n as EntitlementStore, E as EverfurClientEvent, a as EverfurEventHandler, o as EverfurRuntimeConfig, L as LogLevel, b as LogRecord, c as LogSink, N as NULL_SECURE_STORE, P as PrepareOptions, d as PrepareResult, e as PrepareStatus, R as RuntimeTheme, p as RuntimeUser, S as SecureStorePort } from '../runtimeTypes.d-hjN6xvxm.js';
|
|
5
5
|
import { T as TelemetryPort } from '../TelemetryPort.d-BDNr00hu.js';
|
|
6
6
|
export { n as noopTelemetry } from '../TelemetryPort.d-BDNr00hu.js';
|
|
7
7
|
export { E as ErrorPolicyPort, a as EverfurErrorContext, d as defaultErrorPolicy } from '../ErrorPolicyPort.d-BnI5qWg4.js';
|
|
8
8
|
export { C as CameraPort, a as CaptureOptions, M as MediaSource, u as unavailableCamera } from '../CameraPort.d-Cv31Pz7g.js';
|
|
9
9
|
export { F as FileHandle, b as FilePort } from '../ports.d-BX4f4UsB.js';
|
|
10
10
|
export { O as OptionalModule, o as optionalModule } from '../optionalModule.d-DbJmsq5f.js';
|
|
11
|
-
import { p as ChatControllerDeps, o as ChatController, q as SuggestedPromptCategory } from '../checkin.d-
|
|
12
|
-
export { r as CHAT_FEEDBACK_TYPES, s as CHECKIN_ANSWERABLE_STATUS, C as ChatCheckin, a as ChatCheckinTarget, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, t as ChatHandlers, g as ChatHistoryOptions, j as ChatMessage, h as ChatMessagePage, k as ChatMessageRole, l as ChatMessageSender, u as ChatPendingCheckin, i as ChatRefreshOptions, v as ChatSnapshot, m as ChatStatus, n as Citation, F as FEEDBACK_NOTES_MAX_CHARS, M as MAX_IMAGE_KEYS_PER_MESSAGE, S as SendOptions, T as Timers, w as isCheckinSettled } from '../checkin.d-
|
|
11
|
+
import { p as ChatControllerDeps, o as ChatController, q as SuggestedPromptCategory } from '../checkin.d-BoZXWjxX.js';
|
|
12
|
+
export { r as CHAT_FEEDBACK_TYPES, s as CHECKIN_ANSWERABLE_STATUS, C as ChatCheckin, a as ChatCheckinTarget, b as ChatConversation, c as ChatConversationListOptions, d as ChatConversationPage, e as ChatFeedbackReceipt, f as ChatFeedbackType, t as ChatHandlers, g as ChatHistoryOptions, j as ChatMessage, h as ChatMessagePage, k as ChatMessageRole, l as ChatMessageSender, u as ChatPendingCheckin, i as ChatRefreshOptions, v as ChatSnapshot, m as ChatStatus, n as Citation, F as FEEDBACK_NOTES_MAX_CHARS, M as MAX_IMAGE_KEYS_PER_MESSAGE, S as SendOptions, T as Timers, w as isCheckinSettled } from '../checkin.d-BoZXWjxX.js';
|
|
13
13
|
import { E as EverfurError } from '../EverfurError.d-8NHtlgzA.js';
|
|
14
14
|
import { P as PetRef, C as ConversationId } from '../ids.d-B2GAAifq.js';
|
|
15
15
|
export { f as ATTACHMENT_ACCEPT, g as ATTACHMENT_BACKOFF_MS, h as ATTACHMENT_INITIATE_PATH, i as ATTACHMENT_MAX_ATTEMPTS, j as ATTACHMENT_MIME_TYPES, k as ATTACHMENT_QUEUE_CONCURRENCY, A as AttachmentError, a as AttachmentErrorCode, b as AttachmentOutcome, c as AttachmentQueue, l as AttachmentQueueDeps, m as AttachmentQueueSnapshot, d as AttachmentState, e as AttachmentStatus, n as AttachmentUploadPolicy, M as MAX_ATTACHMENTS_PER_MESSAGE, o as MAX_ATTACHMENT_BYTES, p as MAX_FILENAME_LENGTH, V as ValidatedAttachment, q as attachmentSize, r as createAttachmentQueue, s as formatBytes, t as initiateAttachmentUpload, u as isAttachmentMime, v as sanitizeFilename, w as uploadAttachmentBytes, x as validateAttachment } from '../attachments.d-BlukNfIf.js';
|
package/dist/core/index.js
CHANGED
|
@@ -11,7 +11,7 @@ return Object.freeze({kind:"error",terminal:true,code:e.code,retryable:e.retryab
|
|
|
11
11
|
return Object.freeze({kind:"analysisStarted",requestId:e,lastEventId:t,serverRequestId:r,terminal:false})}function analysisCompleteFrame(e,t=null){/* @__PURE__ */
|
|
12
12
|
return Object.freeze({kind:"analysisComplete",terminal:false,resultId:e.resultId,analysisType:e.analysisType,modelVersion:e.modelVersion,confidence:e.confidence,detections:/* @__PURE__ */Object.freeze([...e.detections]),interpretation:e.interpretation,lastEventId:e.lastEventId,serverRequestId:t})}function unknownFrame(e,t,r=null){/* @__PURE__ */
|
|
13
13
|
return Object.freeze({kind:"unknown",raw:{...e},lastEventId:t,serverRequestId:r,terminal:false})}var w="/widget/v1/anon-identity",C="x-everfur-anon-token",k="anonTokenInvalid";function j(e,t){if(typeof e!="string"||t===null)return null;let r=Date.parse(e)-Date.parse(t);return Number.isFinite(r)&&r>0?r:null}function createAnonIdentityProvider(e,t,r,n=Date.now){let i=null,a=null,s=null,l=null,o=e=>Math.max(0,n()-e),u=(e,t)=>e!==null&&n()>=e&&n()-e<t,c=()=>i!==null&&(i.ttlMs===null||o(i.mintedAtMs)<i.ttlMs-2592e5),d=()=>i!==null&&(i.ttlMs===null||o(i.mintedAtMs)<i.ttlMs)?i.token:null,h=()=>a||(a=(async()=>{try{let a=null,l={method:"POST",path:w,headers:{"x-everfur-partner-key":t,"x-everfur-session-id":r},onResponseHeaders:e=>{a=e("date")}},o=await e.request(l),u=o.ok?o.value:null,c=typeof u?.anon_token=="string"&&u.anon_token.length>0?u.anon_token:null;return c===null?(s=n(),d()):(i={token:c,mintedAtMs:n(),ttlMs:j(u?.expires_at,a)},s=null,c)}catch{return s=n(),d()}finally{a=null}})(),a);return{token(e){return e?.forceRefresh?a||(u(l,3e4)?Promise.resolve(i?.token??null):(l=n(),i=null,h())):c()||u(s,3e5)?Promise.resolve(d()):h()}}}async function I(e){if(e.userRef!==null||e.anonIdentity===void 0)return null;try{return await e.anonIdentity.token()}catch{return null}}var O="This feature isn't available on your account right now.",S="Something in that request was not right. Check the details and try again.",E=/* @__PURE__ */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:O,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:S,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.",identitySignatureRequired:O,runtimeDisposed:S,unknown:"Something went wrong. Please try again."}),R="This session has ended. Please sign in again.",z="linked_account_read_only";function T(e,t,r){return e==="conflict"&&r===z?O:(e==="authRejected"||e==="authExpired")&&typeof t=="string"&&t.trim().toLowerCase()==="session_revoked"?R:userFacingError(e)}function userFacingError(e){return E[e]}function F(e,t,r){Object.defineProperty(e,t,{value:r,enumerable:false,writable:false,configurable:false})}var A=/^[a-z][a-z0-9_]{0,63}$/;function makeEverfurError(e,t){let r=contractErrorFor(t?.wireCode,t?.wireEnvelope),n=e==="conflict"&&t?.reasonCode===z,i={code:e,category:categoryFor(e),retryable:t?.retryable??(n?false:isRetryableCode(e)),displayMessage:T(e,t?.wireCode,n?z:null)};t?.httpStatus!==void 0&&(i.httpStatus=t.httpStatus),t?.requestId&&(i.requestId=t.requestId),typeof t?.reasonCode=="string"&&A.test(t.reasonCode)&&(i.reasonCode=t.reasonCode);let a=t?.retryAfterSeconds;if(typeof a=="number"&&Number.isFinite(a)&&a>=0&&(i.retryAfterSeconds=Math.round(a)),r);return t?.wireMessage&&F(i,"wireMessage",t.wireMessage),t?.raw!==void 0&&t.raw!==null&&F(i,"raw",t.raw),/* @__PURE__ */Object.freeze(i)}function x(e,t){let r=e instanceof Error?e.message:typeof e=="string"?e:null;return makeEverfurError("authRejected",{retryable:false,...t?.wireCode?{wireCode:t.wireCode}:{},...t?.requestId?{requestId:t.requestId}:{},...r?{wireMessage:r}:{},...e!=null?{raw:e}:{}})}function createIdentityProvider(userRef,e,r,n){let i=null,a=false,s=null,l=false,o=()=>s||(s=(async()=>{try{let n=await e(),s=typeof n=="string"?n:n?.token;if(typeof s!="string"||s.length===0)throw new t("invalid-argument","TokenProvider returned an empty token");return i=s,a=!1,r?.(typeof n=="string"?null:P(n.expiresAt)),s}finally{s=null}})(),s);return{userRef:userRef,async currentToken(e){if(l)throw new t("not-initialized","This identity was cleared (sign-out); mint a new one.");return e?.forceRefresh&&(i=null),i!==null?i:o()},hasToken(){return!l&&i!==null},clear(){l=true,i=null},reportRejected(){l||a||(a=true,n?.())}}}function P(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}function newSessionId(){let e=new Uint8Array(16),t=globalThis.crypto;if(typeof t?.getRandomValues=="function")t.getRandomValues(e);else for(let t=0;t<e.length;t+=1)e[t]=Math.floor(Math.random()*256);e[6]=e[6]&15|64,e[8]=e[8]&63|128;let r=[];for(let t=0;t<e.length;t+=1)r.push(e[t].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("")}function authHeaders(e){let t={};return e.mode==="personalized"?t.authorization=`Bearer ${e.token}`:(t["x-everfur-partner-key"]=e.publishableKey,e.anonToken&&(t[C]=e.anonToken)),e.userRef&&(t["x-everfur-user-ref"]=e.userRef),e.sessionId&&(t["x-everfur-session-id"]=e.sessionId),t}function withAuthHeaders(e,t){return{...e,headers:{...D(e.headers),...authHeaders(t)}}}function D(e){if(!e)return{};let t={};for(let[r,n]of Object.entries(e)){let e=r.toLowerCase();e==="authorization"||e==="x-everfur-partner-key"||e===C||(t[r]=n)}return t}async function authedSend(e,t){if(t.mode==="anonymous"){let r=await I(t),n=await t.transport.request(withAuthHeaders(e,M(t,r)));if(n.ok||N(n.error.raw)!==k||t.anonIdentity===void 0||t.userRef!==null)return n;let i=await t.anonIdentity.token({forceRefresh:true});return i===null||i===r?n:t.transport.request(withAuthHeaders(e,M(t,i)))}let r;try{r=await t.identity.currentToken()}catch(e){return t.identity.reportRejected?.(),err(x(e))}let n=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:r,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));if(n.ok||n.error.httpStatus!==401)return n;let i;try{i=await t.identity.currentToken({forceRefresh:!0})}catch(e){return t.identity.reportRejected?.(),err(x(e,{wireCode:N(n.error.raw),requestId:n.error.requestId}))}let a=await t.transport.request(withAuthHeaders(e,{mode:"personalized",token:i,userRef:t.userRef,...t.sessionId?{sessionId:t.sessionId}:{}}));return!a.ok&&a.error.httpStatus===401?(t.identity.reportRejected?.(),err(U(a.error))):a}function M(e,t){return{mode:"anonymous",publishableKey:e.publishableKey,userRef:e.userRef,...e.sessionId?{sessionId:e.sessionId}:{},...t!==null?{anonToken:t}:{}}}function U(e){let t=e.raw,r=N(t);return makeEverfurError("authRejected",{retryable:false,...e.httpStatus!==void 0?{httpStatus:e.httpStatus}:{},...e.requestId?{requestId:e.requestId}:{},...r?{wireCode:r}:{},...e.reasonCode?{reasonCode:e.reasonCode}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},...t!=null?{raw:t}:{}})}function N(e){if(typeof e!="object"||e===null)return null;let t=e,r=(typeof t.error=="object"&&t.error!==null?t.error.code:void 0)??t.code;return typeof r=="string"&&r.length>0?r:null}var $="DAILY_QUOTA_EXCEEDED",q=/* @__PURE__ */new Set(["THROTTLINGEXCEPTION","RATELIMITED","TOOMANYREQUESTS"]);function L(e,t){if(!q.has(e.toUpperCase().replace(/[^A-Z0-9]/g,"")))return e;let r=t,n=r?.daily_limit??r?.error?.daily_limit;return typeof n=="number"&&Number.isFinite(n)?$:e}var B="free_cap_reached";function H(e){return typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}function K(e){if(typeof e!="object"||e===null)return null;let t=e,r=t.detail,n=typeof r=="object"&&r!==null?r:t;if(n.error!==B&&n.code!==B)return null;let i=H(n.limit),a=H(n.used);if(i===null||a===null)return null;let s=n.resets_at,l=n.emergency_guidance;/* @__PURE__ */
|
|
14
|
-
return Object.freeze({limit:i,used:a,resetsAt:typeof s=="string"&&s.length>0?s:null,...typeof l=="string"&&l.trim().length>0?{emergencyGuidance:l}:{}})}function V(){let e=[];return{decode(t,r){let n=r?.stream===true,i=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)i.push(t[e]);e=[];let a="",s=0;for(;s<i.length;){let t=i[s];if(t<128){a+=String.fromCharCode(t),s+=1;continue}let r,l=128,o=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(l=160),t===237&&(o=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(l=144),t===244&&(o=143);else{a+="�",s+=1;continue}let c=1,d=true;for(;c<=r&&!(s+c>=i.length);){let e=i[s+c],t=c===1?l:128,r=c===1?o:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){a+="�",s+=c;continue}if(c<=r){n?e=i.slice(s):a+="�";break}a+=String.fromCodePoint(u),s+=r+1}return a}}}function G(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):V()}var W=`\n\n`,Y=1048576,Q=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),X=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),i=G(),a="",s=0,l=false;for await(let t of e){for(a+=i.decode(t,{stream:true});;){let e=a.indexOf(W,s);if(e===-1)break;let t=a.slice(0,e);a=a.slice(e+W.length),s=0;let r=J(t,n());if(r!==null&&(r.kind==="delta"&&(l=true),yield r,r.terminal))return}if(s=a.length>0?a.length-1:0,a.length>Y){yield errorFrame({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(a+=i.decode(),a.trim().length>0){let e=J(a,n());if(e!==null&&(e.kind==="delta"&&(l=true),yield e,e.terminal))return}yield errorFrame({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function J(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let i;try{i=JSON.parse(n.join(`\n`))}catch{return null}if(typeof i!="object"||i===null||Array.isArray(i))return null;let a=Q.safeParse(i);return a.success?Z(a.data,r,t):null}function Z(e,t,r){let n=e.type,i=e.event;if(n==="error"||"error"in e)return errorFrame({code:ee(e.code)??"unknown",retryable:e.retryable===true,wireMessage:ee(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:K(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:ee(e.conversation_id)??"",messageId:ee(e.message_id),title:ee(e.title),followUpQuestions:ie(e.follow_up_questions),citations:se(e.citations),citationStatus:ee(e.citation_status),urgencyLevel:re(e.urgency_level),urgencyReason:ee(e.urgency_reason),urgencyProvided:ne(e),resultId:ee(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(ee(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=ee(e.delta)??ee(e.token)??"";return deltaFrame(n,t,r)}return i==="analysis_started"?analysisStartedFrame(ee(e.request_id),t,r):i==="analysis_complete"?analysisCompleteFrame({resultId:ee(e.result_id),analysisType:ee(e.analysis_type),modelVersion:ee(e.model_version),confidence:te(e.confidence),detections:se(e.detections),interpretation:ee(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function ee(e){return typeof e=="string"?e:null}function te(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function re(e){return typeof e=="string"&&X.includes(e)?e:null}function ne(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||re(t)!==null}function ie(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function se(e){return Array.isArray(e)?e.filter(ae):[]}var le=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function oe(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return he(e,t)}var ue=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,ce=/[\s\u0000-\u001f\u007f\\]/,de={"http:":"80","https:":"443"};function he(e,t){let r=e.trim();if(t!==void 0&&!le.test(r)){let e=he(t);if(e===null||!r.startsWith("/")||r.startsWith("//"))return null;r=e.origin+r}let n=ce.test(r)?null:ue.exec(r);if(n===null)return null;let[,i="",a="",s="",l="",o="",u="",c="",d=""]=n,h=`${i.toLowerCase()}:`,f=Number(o);if(f>65535)return null;let p=o===""||String(f)===de[h]?"":String(f),g=de[h]!==void 0,m=l.toLowerCase()+(p&&`:${p}`),y=u||(g?"/":""),v=a||s?`${a}${s&&`:${s}`}@`:"";return{href:`${h}//${v}${m}${y}${c}${d}`,protocol:h,username:a,password:s,hostname:l.toLowerCase(),port:p,origin:g?`${h}//${m}`:"null",pathname:y,search:c==="?"?"":c,hash:d==="#"?"":d}}function fe(e,t,r){return{...e,surface:t,requestId:r||null}}var pe=64,ge=/^[A-Za-z0-9._+() -]+$/;function me(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>pe?null:ge.test(t)?t:null}var ye="1.
|
|
14
|
+
return Object.freeze({limit:i,used:a,resetsAt:typeof s=="string"&&s.length>0?s:null,...typeof l=="string"&&l.trim().length>0?{emergencyGuidance:l}:{}})}function V(){let e=[];return{decode(t,r){let n=r?.stream===true,i=e.length>0?e.slice():[];if(t!==void 0)for(let e=0;e<t.length;e+=1)i.push(t[e]);e=[];let a="",s=0;for(;s<i.length;){let t=i[s];if(t<128){a+=String.fromCharCode(t),s+=1;continue}let r,l=128,o=191,u;if(t>=194&&t<=223)r=1,u=t&31;else if(t>=224&&t<=239)r=2,u=t&15,t===224&&(l=160),t===237&&(o=159);else if(t>=240&&t<=244)r=3,u=t&7,t===240&&(l=144),t===244&&(o=143);else{a+="�",s+=1;continue}let c=1,d=true;for(;c<=r&&!(s+c>=i.length);){let e=i[s+c],t=c===1?l:128,r=c===1?o:191;if(e<t||e>r){d=false;break}u=u<<6|e&63,c+=1}if(!d){a+="�",s+=c;continue}if(c<=r){n?e=i.slice(s):a+="�";break}a+=String.fromCodePoint(u),s+=r+1}return a}}}function G(){let e=globalThis.TextDecoder;return typeof e=="function"?new e("utf-8"):V()}var W=`\n\n`,Y=1048576,Q=/* @__PURE__ */e.record(/* @__PURE__ */e.string(),/* @__PURE__ */e.unknown()),X=["emergency","schedule_soon","home_care"];async function*parseSse(e,t=null){let r=null,n=()=>(r!==null||(r=typeof t=="function"?t():t),r),i=G(),a="",s=0,l=false;for await(let t of e){for(a+=i.decode(t,{stream:true});;){let e=a.indexOf(W,s);if(e===-1)break;let t=a.slice(0,e);a=a.slice(e+W.length),s=0;let r=J(t,n());if(r!==null&&(r.kind==="delta"&&(l=true),yield r,r.terminal))return}if(s=a.length>0?a.length-1:0,a.length>Y){yield errorFrame({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()});return}}if(a+=i.decode(),a.trim().length>0){let e=J(a,n());if(e!==null&&(e.kind==="delta"&&(l=true),yield e,e.terminal))return}yield errorFrame({code:l?"CHAT_STREAM_INCOMPLETE":"internal_error",retryable:true,wireMessage:null,synthesized:true,lastEventId:null,serverRequestId:n()})}function J(e,t){let r=null,n=[];for(let t of e.split(`\n`)){let e=t.replace(/\s+$/,"");e.length===0||e.startsWith(":")||(e.startsWith("id:")?r=e.slice(3).trim():e.startsWith("data:")&&n.push(e.slice(5).replace(/^ /,"")))}if(n.length===0)return null;let i;try{i=JSON.parse(n.join(`\n`))}catch{return null}if(typeof i!="object"||i===null||Array.isArray(i))return null;let a=Q.safeParse(i);return a.success?Z(a.data,r,t):null}function Z(e,t,r){let n=e.type,i=e.event;if(n==="error"||"error"in e)return errorFrame({code:ee(e.code)??"unknown",retryable:e.retryable===true,wireMessage:ee(e.error),synthesized:false,lastEventId:t,serverRequestId:r,freeCap:K(e)});if(n==="done"||e.done===true)return doneFrame({conversationId:ee(e.conversation_id)??"",messageId:ee(e.message_id),title:ee(e.title),followUpQuestions:ie(e.follow_up_questions),citations:se(e.citations),citationStatus:ee(e.citation_status),urgencyLevel:re(e.urgency_level),urgencyReason:ee(e.urgency_reason),urgencyProvided:ne(e),resultId:ee(e.result_id),lastEventId:t},r);if(n==="accepted"||e.status==="reasoning")return acceptedFrame(ee(e.stream_id),t,r);if(n==="heartbeat"||e.heartbeat===true)return heartbeatFrame(t,r);if(n==="text.delta"||"delta"in e||"token"in e){let n=ee(e.delta)??ee(e.token)??"";return deltaFrame(n,t,r)}return i==="analysis_started"?analysisStartedFrame(ee(e.request_id),t,r):i==="analysis_complete"?analysisCompleteFrame({resultId:ee(e.result_id),analysisType:ee(e.analysis_type),modelVersion:ee(e.model_version),confidence:te(e.confidence),detections:se(e.detections),interpretation:ee(e.interpretation),lastEventId:t},r):unknownFrame(e,t,r)}function ee(e){return typeof e=="string"?e:null}function te(e){return typeof e=="number"&&Number.isFinite(e)?e:null}function re(e){return typeof e=="string"&&X.includes(e)?e:null}function ne(e){if(!Object.prototype.hasOwnProperty.call(e,"urgency_level"))return false;let t=e.urgency_level;return t===null||re(t)!==null}function ie(e){return Array.isArray(e)?e.map(e=>typeof e=="string"?e:String(e)):[]}function ae(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function se(e){return Array.isArray(e)?e.filter(ae):[]}var le=/^([A-Za-z][A-Za-z0-9+.-]*):\/\/([^/?#]*)/;function oe(e,t){let r=globalThis.URL;if(typeof r=="function"){let n;try{n=t===void 0?new r(e):new r(e,t)}catch{return null}try{if(n.protocol)return n}catch{}}return he(e,t)}var ue=/^([a-z][a-z0-9+.-]*):\/\/(?:([^:@/?#]*)(?::([^@/?#]*))?@)?(\[[0-9a-f:.]+\]|[\w.~-]+)(?::(\d*))?(\/[^?#]*)?(\?[^#]*)?(#.*)?$/i,ce=/[\s\u0000-\u001f\u007f\\]/,de={"http:":"80","https:":"443"};function he(e,t){let r=e.trim();if(t!==void 0&&!le.test(r)){let e=he(t);if(e===null||!r.startsWith("/")||r.startsWith("//"))return null;r=e.origin+r}let n=ce.test(r)?null:ue.exec(r);if(n===null)return null;let[,i="",a="",s="",l="",o="",u="",c="",d=""]=n,h=`${i.toLowerCase()}:`,f=Number(o);if(f>65535)return null;let p=o===""||String(f)===de[h]?"":String(f),g=de[h]!==void 0,m=l.toLowerCase()+(p&&`:${p}`),y=u||(g?"/":""),v=a||s?`${a}${s&&`:${s}`}@`:"";return{href:`${h}//${v}${m}${y}${c}${d}`,protocol:h,username:a,password:s,hostname:l.toLowerCase(),port:p,origin:g?`${h}//${m}`:"null",pathname:y,search:c==="?"?"":c,hash:d==="#"?"":d}}function fe(e,t,r){return{...e,surface:t,requestId:r||null}}var pe=64,ge=/^[A-Za-z0-9._+() -]+$/;function me(e){if(typeof e!="string")return null;let t=e.trim();return t.length===0||t.length>pe?null:ge.test(t)?t:null}var ye="1.6.0";var ve="react-native",be="2026-09-19",_e="EVERFUR_API_BASE_URL";function we(e,t){/* @__PURE__ */
|
|
15
15
|
return Object.freeze({ok:false,failure:/* @__PURE__ */Object.freeze({reason:e,message:t})})}function checkPublishableKey(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}function tryResolveClientConfig(e,t){let r=checkPublishableKey(e?.publishableKey);if(r!==null)/* @__PURE__ */
|
|
16
16
|
return Object.freeze({ok:false,failure:r});let n=e.publishableKey.trim(),i=tryResolveApiBaseUrl(e.apiBaseUrl);if(!i.ok)return i;let a=e.contractVersion?.trim()||be,s=me(e.appVersion);/* @__PURE__ */
|
|
17
17
|
return Object.freeze({ok:true,config:/* @__PURE__ */Object.freeze({publishableKey:n,apiBaseUrl:i.value,contractVersion:a,sdkVersion:ye,platform:t?.platform??ve,debug:e.debug===true,...s!==null?{appVersion:s}:{}})})}function tryResolveApiBaseUrl(e){let t=e?.trim(),r=t&&t.length>0?t:Ee(_e);return r?Oe(r):we("missing-api-base-url",`apiBaseUrl is required: pass config.apiBaseUrl or set ${_e}. The SDK never ships a hardcoded host.`)}function buildBaseHeaders(e){let t={"X-Everfur-SDK-Version":e.sdkVersion,"X-Everfur-SDK-Platform":e.platform,"X-Everfur-Contract":e.contractVersion};return e.appVersion!=null&&e.platform==="react-native"&&(t["X-Everfur-App-Version"]=e.appVersion),t}function Ce(e){return e.slice(e.lastIndexOf("@")+1).replace(/:\d+$/,"").toLowerCase()}function ke(e){return e.length===0||e.includes("@")?false:e.startsWith("[")&&e.endsWith("]")?true:!e.includes(":")}function je(e,t){let r=e.indexOf("://");return r<0||e.slice(r+3).includes("@")?false:ke(t)}function Ie(e,t){return`${e}://${t}`}function Oe(e){let t=e.trim(),r=le.exec(t);if(r===null||r[2]===void 0||r[2].length===0)return we("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let n=(r[1]??"").toLowerCase(),i=Ce(r[2]);if(i.length===0)return we("malformed-api-base-url","apiBaseUrl is not a valid absolute URL");let a=je(t,i)?`: ${Ie(n,i)}`:"";if(n!=="https"){if(!(n==="http"&&Se(i)))return n==="http"?we("insecure-api-base-url",`apiBaseUrl must use https (cleartext http is only allowed for localhost)${a}`):we("unsupported-api-base-url-scheme",`apiBaseUrl must be http(s)${a}`)}let s=t.endsWith("/")?t.slice(0,-1):t;/* @__PURE__ */
|
|
@@ -24,7 +24,7 @@ return Object.freeze({id:e,role:"assistant",text:t,createdAt:r})}function Lt(e){
|
|
|
24
24
|
return Object.freeze({id:e.id,role:e.role,text:e.text,createdAt:e.createdAt})}function Bt(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),/* @__PURE__ */Object.freeze(r)}function Ht(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,/* @__PURE__ */Object.freeze(r)}function Kt(e){/* @__PURE__ */
|
|
25
25
|
return Object.freeze({status:e.status,messages:/* @__PURE__ */Object.freeze([...e.messages]),conversationId:e.conversationId,error:e.error,isStreaming:e.isStreaming,isBootstrapping:e.isBootstrapping,suggestedPrompts:/* @__PURE__ */Object.freeze([...e.suggestedPrompts]),unreadCount:e.unreadCount})}function Vt(e,t,r){return makeEverfurError(e,{retryable:t,...r?{wireMessage:r}:{}})}function Gt(e){let t=fromWire(e.code);return makeEverfurError(t,{retryable:e.retryable||shouldRetry(t),wireCode:e.code,wireEnvelope:"sse_frame",...e.serverRequestId?{requestId:e.serverRequestId}:{},...e.wireMessage?{wireMessage:e.wireMessage}:{},raw:e})}function Wt(e){return errorFrame({code:Yt(e.code),retryable:e.retryable,wireMessage:e.wireMessage??null,synthesized:true,lastEventId:null,serverRequestId:e.requestId??null})}function Yt(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"identitySignatureRequired":return"identitySignatureRequired";case"runtimeDisposed":return"runtimeDisposed";case"unknown":return"UNKNOWN";default:return assertNever(e)}}function Qt(e){let t=Array.isArray(e)?e:Jt(e)&&Array.isArray(e.categories)?e.categories:[],r=[];for(let e of t){if(!Jt(e))continue;let t=Zt(e.category)??Zt(e.title)??"",n=er(e.prompts??e.questions);t.length===0&&n.length===0||r.push(/* @__PURE__ */Object.freeze({category:t,prompts:/* @__PURE__ */Object.freeze(n)}))}/* @__PURE__ */
|
|
26
26
|
return Object.freeze(r)}function Xt(e){let t=/* @__PURE__ */new Set,r=[];for(let n of e)for(let e of n.prompts){let n=e.trim();n.length===0||t.has(n)||(t.add(n),r.push(n))}return r}function Jt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Zt(e){return typeof e=="string"?e:null}function er(e){if(!Array.isArray(e))return[];let t=[];for(let r of e)if(typeof r=="string")t.push(r);else if(Jt(r)){let e=Zt(r.text)??Zt(r.prompt)??Zt(r.title);e!==null&&t.push(e)}return t}function tr(){let e=0;return()=>`m-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,8)}`}function rr(){let e=0;return()=>`chat-send-${Date.now().toString(36)}-${(e++).toString(36)}-${Math.random().toString(36).slice(2,10)}`}function nr(){return typeof Symbol=="function"?Symbol.asyncIterator:void 0}function ir(e){let t=e,r=nr(),n=(r!==void 0?t[r]:void 0)??t["@@asyncIterator"];if(typeof n=="function")return n.call(e);let i=typeof Symbol=="function"?t[Symbol.iterator]:void 0;if(typeof i=="function"){let t=i.call(e);return{next:()=>Promise.resolve(t.next()),return:e=>Promise.resolve(t.return?.(e)??{done:true,value:void 0})}}return null}var ar={setTimeout:(e,t)=>setTimeout(e,t),clearTimeout:e=>clearTimeout(e),now:()=>Date.now()};async function*sr(e,t,r,n){let i=ir(e);if(i===null){yield or();return}let a=ur(t.overallMs,n),s=ur(t.idleMs,n),l=cr(r);try{for(;;){if(r.aborted)return;let e=i.next().then(e=>({tag:"next",value:e}),()=>({tag:"streamError"})),n=await Promise.race([e,s.promise.then(()=>({tag:"idle"})),a.promise.then(()=>({tag:"overall"})),l.then(()=>({tag:"abort"}))]);if(n.tag==="abort")return;if(n.tag==="streamError"){if(r.aborted)return;yield or();return}if(n.tag==="idle"||n.tag==="overall"){yield lr();return}let o=n.value;if(o.done||(s.reset(t.idleMs),yield o.value,o.value.terminal))return}}finally{s.cancel(),a.cancel(),Promise.resolve(i.return?.(void 0)).catch(()=>{})}}function lr(){return errorFrame({code:"STREAM_TIMEOUT",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function or(){return errorFrame({code:"STREAM_INCOMPLETE",retryable:true,wireMessage:null,synthesized:true,lastEventId:null})}function ur(e,t){let r=()=>{},n=new Promise(e=>{r=e}),i=t.setTimeout(()=>r(),e);return{promise:n,reset(e){t.clearTimeout(i),i=t.setTimeout(()=>r(),e)},cancel(){t.clearTimeout(i)}}}function cr(e){return new Promise(t=>{if(e.aborted){t();return}e.addEventListener("abort",()=>t(),{once:true})})}var dr="checkin",hr=/^\d{4}-\d{2}-\d{2}$/,fr="watching";function pr(e){for(let t=e.length-1;t>=0;t-=1){let r=e[t];if(r!==void 0){if(r.role==="user")return null;if(r.role==="assistant"){if(r.checkin!==void 0)return r.checkin.answer!==null||isCheckinSettled(r.checkin)?null:r;if(typeof r.proactiveOriginRef=="string"&&r.proactiveOriginRef.length>0)return r}}}return null}function gr(e){if(e===null||typeof e!="object")return null;let t=e,conversationId=t.conversation_id,r=t.message_id,n=t.question,i=t.occasion_ref;if(typeof conversationId!="string"||conversationId.length===0||typeof r!="string"||r.length===0||typeof n!="string"||n.trim().length===0)return null;let a=typeof i=="string"&&i.length>0?i:null,s=yr(a),l=s===null?null:/* @__PURE__ */Object.freeze({caseId:s.caseId,answer:null,resolutionText:null,status:null}),o=typeof t.created_at=="string"?t.created_at:"",u=/* @__PURE__ */Object.freeze({id:r,role:"assistant",text:n,createdAt:o,...a===null?{}:{proactiveOriginRef:a},...l===null?{}:{checkin:l}});/* @__PURE__ */
|
|
27
|
-
return Object.freeze({conversationId:conversationId,message:u,checkin:l,occasionRef:a})}function isCheckinSettled(e){return e.status!=null&&e.status!==fr}function mr(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}function yr(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,i]=t;return r!==dr||n===void 0||i===void 0||!St.test(n)||!hr.test(i)?null:{caseId:n,dueDay:i}}function vr(e){return yr(e)?.caseId??null}function br(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||jt(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function _r(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)}function wr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Cr(e){return e==null||typeof e=="string"&&e.length>0&&!jt(e)}function kr(){return err(makeEverfurError("internalError",{retryable:false}))}function jr(e){let t=wr(e);if(!t||!Array.isArray(t.conversations)||!Cr(t.next_cursor))return kr();let r=[];for(let e of t.conversations){let t=wr(e);if(!t||typeof t.conversation_id!="string"||!_r(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return kr();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return kr();let i=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...i.length>0?{preview:i}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Ir(e){let t=wr(e);if(!t||!Array.isArray(t.messages)||!Cr(t.next_cursor))return kr();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=wr(e);if(!t||typeof t.message_id!="string"||!_r(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return kr();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(Or(t,t.message_id,t.content,t.created_at));continue}let i=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,a=t.role==="assistant"?vr(i):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:Er(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:Rr(t.citations)}:{},...i!==null?{proactiveOriginRef:i}:{},...a!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:a,answer:null,resolutionText:null,status:null})}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Or(e,t,r,n){let i=wr(e.sender),a=Sr(i?.display_name)??Sr(e.sender_display_name),s=Sr(i?.specialty);/* @__PURE__ */
|
|
27
|
+
return Object.freeze({conversationId:conversationId,message:u,checkin:l,occasionRef:a})}function isCheckinSettled(e){return e.status!=null&&e.status!==fr}function mr(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}function yr(e){if(typeof e!="string")return null;let t=e.split(":");if(t.length!==3)return null;let[r,n,i]=t;return r!==dr||n===void 0||i===void 0||!St.test(n)||!hr.test(i)?null:{caseId:n,dueDay:i}}function vr(e){return yr(e)?.caseId??null}function br(e,t){if(e?.limit!==void 0&&(!Number.isInteger(e.limit)||e.limit<1||e.limit>t))return err(makeEverfurError("validationFailed"));let r=[];for(let[t,n]of[["cursor",e?.cursor],["pet_ref",e?.petRef]])if(n!==void 0){if(typeof n!="string"||n.length===0||jt(n))return err(makeEverfurError("validationFailed"));r.push(`${t}=${encodeURIComponent(n)}`)}return e?.limit!==void 0&&r.push(`limit=${e.limit}`),ok(r.length?`?${r.join("&")}`:"")}function _r(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)}function wr(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)?e:null}function Cr(e){return e==null||typeof e=="string"&&e.length>0&&!jt(e)}function kr(){return err(makeEverfurError("internalError",{retryable:false}))}function jr(e){let t=wr(e);if(!t||!Array.isArray(t.conversations)||!Cr(t.next_cursor))return kr();let r=[];for(let e of t.conversations){let t=wr(e);if(!t||typeof t.conversation_id!="string"||!_r(t.conversation_id)||!(t.title==null||typeof t.title=="string")||typeof t.created_at!="string"||typeof t.updated_at!="string")return kr();let n=t.unread_message_count;if(!(n==null||Number.isInteger(n)&&n>=0))return kr();let i=typeof t.preview=="string"?t.preview.replace(/\s+/g," ").trim().slice(0,140):"";r.push(/* @__PURE__ */Object.freeze({id:t.conversation_id,title:t.title??null,createdAt:t.created_at,updatedAt:t.updated_at,unreadCount:n??null,...i.length>0?{preview:i}:{}}))}return ok(/* @__PURE__ */Object.freeze({conversations:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Ir(e){let t=wr(e);if(!t||!Array.isArray(t.messages)||!Cr(t.next_cursor))return kr();let r=[],n=/* @__PURE__ */new Set;for(let e of t.messages){let t=wr(e);if(!t||typeof t.message_id!="string"||!_r(t.message_id)||typeof t.role!="string"||typeof t.content!="string"||typeof t.created_at!="string")return kr();if(t.role!=="user"&&t.role!=="assistant"&&t.role!=="vet"||n.has(t.message_id))continue;if(n.add(t.message_id),t.role==="vet"){r.push(Or(t,t.message_id,t.content,t.created_at));continue}let i=typeof t.proactive_origin_ref=="string"?t.proactive_origin_ref:null,a=t.role==="assistant"?vr(i):null;r.push(/* @__PURE__ */Object.freeze({id:t.message_id,role:t.role,text:t.content,createdAt:t.created_at,...t.role==="assistant"?{responseId:t.message_id}:{},...t.urgency_level!==void 0?{urgencyLevel:Er(t.urgency_level)}:{},...Array.isArray(t.citations)?{citations:Rr(t.citations)}:{},...i!==null?{proactiveOriginRef:i}:{},...a!==null?{checkin:/* @__PURE__ */Object.freeze({caseId:a,answer:null,resolutionText:null,status:null})}:{},...t.a2ui?{a2ui:[t.a2ui]}:{}}))}return ok(/* @__PURE__ */Object.freeze({messages:/* @__PURE__ */Object.freeze(r),nextCursor:t.next_cursor??null}))}function Or(e,t,r,n){let i=wr(e.sender),a=Sr(i?.display_name)??Sr(e.sender_display_name),s=Sr(i?.specialty);/* @__PURE__ */
|
|
28
28
|
return Object.freeze({id:t,role:"vet",text:r,createdAt:n,sender:/* @__PURE__ */Object.freeze({displayName:a,specialty:s})})}function Sr(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0&&!jt(t)?t:null}function Er(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}function Rr(e){let t=["source_name","source_abbrev","section","authority_tier","doi","url","title","year","study_type","journal","excerpt","monograph_chunk_id"];/* @__PURE__ */
|
|
29
29
|
return Object.freeze(e.flatMap(e=>{let r=wr(e);if(!r||typeof r.source_name!="string"||typeof r.authority_tier!="string")return[];let n={};for(let e of t){let t=r[e];(typeof t=="string"||t===null)&&(n[e]=t)}return[/* @__PURE__ */Object.freeze(n)]}))}function zr(e,t,r){let n=new Set(e.map(e=>e.id)),i=e.filter(e=>r.has(e.id)),a=[];for(let e of t){if(n.has(e.id))continue;let t=e.text.trim(),r=i.findIndex(r=>r.role===e.role&&r.text.trim()===t);if(r>=0){i.splice(r,1);continue}a.push(e)}return a}var Tr=5,Fr=/* @__PURE__ */Object.freeze(["helpful","neutral","not_helpful","wrong","outdated","dangerous","unclear"]),Ar=4e3;var xr=4e3;function Pr(e){return e===void 0?null:!Array.isArray(e)||e.length>5?{reason:"too_many_images",error:Vt("validationFailed",false,`image_s3_keys accepts at most ${5} keys`)}:e.some(e=>typeof e!="string"||e.trim().length===0)?{reason:"bad_image_key",error:Vt("validationFailed",false,"image_s3_keys must be non-empty strings")}:null}function Dr(e){let t=typeof e=="string"?e:"";if(t.trim().length===0)return{reason:"empty",error:Vt("validationFailed",false,"message is empty or whitespace-only")};let r=[...t].length;return r>xr?{reason:"too_long",error:Vt("validationFailed",false,`message is ${r} characters; the server accepts at most ${xr}`)}:null}function Mr(e){return e==="emergency"||e==="schedule_soon"||e==="home_care"?e:null}async function*Ur(e){yield e}async function*Nr(){}var $r=6e4,qr=18e4,Lr=24,Br=512,Hr=false;function createChatController(e){return new Wr(e)}function Kr(e,t){return e===t?true:e===null||t===null?false:e.message.id===t.message.id&&e.conversationId===t.conversationId&&e.message.text===t.message.text&&(e.checkin?.answer??null)===(t.checkin?.answer??null)&&(e.checkin?.status??null)===(t.checkin?.status??null)&&(e.checkin?.resolutionText??null)===(t.checkin?.resolutionText??null)}function Vr(e){if(e.category==="rateLimit"||e.category==="server")return true;let t=e.httpStatus;return typeof t=="number"&&(t===429||t>=500)}function Gr(e){if(e.reasonCode!==void 0||e.wireMessage!==void 0)return true;let t=e.raw;return t==null||typeof t!="object"||typeof t.detail!="string"?false:t.detail.length>0&&t.detail.trim().toLowerCase()!=="not found"}var Wr=class extends Nt{constructor(e){super(Kt({status:"idle",messages:[],conversationId:e.initialConversationId??null,error:null,isStreaming:false,isBootstrapping:false,suggestedPrompts:[],unreadCount:null}));this.handlerTeardowns=/* @__PURE__ */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.localRowIds=/* @__PURE__ */new Set;this.unreadByConversation=/* @__PURE__ */new Map;this.classifiedMessageIds=/* @__PURE__ */new Set;this.pendingCheckinByThread=/* @__PURE__ */new Map;this.listHead=null;this.probedHead=null;this.lastHeadReadAt=null;this.reportedCheckinSkips=/* @__PURE__ */new Set;this.cardsRoute="unknown";this.pendingCards=[];this.cardsInFlight=false;this.lastCardProbe=null;this.answeredCases=/* @__PURE__ */new Map;this.pendingDelta="";this.flushHandle=null;this.auth=e.auth,this.funnel=e.funnel??createRequestFunnel({auth:e.auth,...e.errorPolicy?{errorPolicy:e.errorPolicy}:{}}),this.petRef=e.petRef??null,this.cases=xt(this.funnel),this.telemetry=e.telemetry??n,this.onConversationStarted=e.onConversationStarted,this.unread=e.unread,this.errorPolicy=e.errorPolicy??m,this.timers=e.timers??ar,this.rng=e.rng??Math.random,this.newId=e.newId??tr(),this.makeIdempotencyKey=e.makeIdempotencyKey??rr(),this.budget={idleMs:e.budget?.idleMs??$r,overallMs:e.budget?.overallMs??qr}}patch(e){if(e.messages!==void 0){let t=/* @__PURE__ */Object.freeze([...e.messages]);super.patch({...e,messages:t});return}super.patch(e)}send(e,t,r){let n=t??{};if(this.disposed||this.snapshot.isBootstrapping){let e=Vt(this.disposed?"accessDenied":"internalError",!this.disposed);return r?(r.onError(e),()=>{}):Ur(Wt(e))}let i=Dr(e)??Pr(n.imageS3Keys);if(i!==null)return this.telemetry.track("chat.send.rejected",{reason:i.reason}),this.patch({status:"error",isStreaming:false,error:i.error}),r?(r.onError(i.error),()=>{}):Ur(Wt(i.error));if(r)return this.driveWithHandlers(e,n,r);let a=this.beginTurn(e,n);return this.runTurn(a,n.signal)}askEverfur(e,t){if(this.disposed)return Ur(Wt(Vt("accessDenied",false)));let r=Dr(e);return r!==null?(this.telemetry.track("chat.send.rejected",{reason:r.reason}),Ur(Wt(r.error))):(this.resetThread(),this.send(e,t??{}))}retryLast(){let e=this.lastTurn;if(e===null){let e=this.snapshot.conversationId;return e!==null&&this.snapshot.status==="error"?this.retryHistory(e):Nr()}e.assistantMessageId=null,e.sawDelta=false,e.conversationIdOverride=null,this.discardPendingDelta();let t=this.snapshot.messages.some(t=>t.id===e.userMessageId)?this.snapshot.messages:[...this.snapshot.messages,$t(e.userMessageId,e.text,this.stamp())];return this.patch({error:null,stopped:false,messages:t}),this.runTurn(e,void 0)}stop(){this.inFlight?.abort(),this.inFlight=null,this.discardPendingDelta(),this.telemetry.track("chat.cancel",{});let e=this.snapshot.messages.some(e=>e.role==="user"&&e.pending===true),t=e?this.snapshot.messages.map(e=>e.pending===true?Lt(e):e):this.snapshot.messages;(this.snapshot.status==="streaming"||e)&&this.patch({status:"idle",isStreaming:false,reconnecting:false,...e?{messages:t,stopped:true}:{}})}rescope(){this.resetThread(),this.scopePrompts=[],this.unreadByConversation.clear(),this.classifiedMessageIds.clear(),this.pendingCheckinByThread.clear(),this.listHead=null,this.probedHead=null,this.lastHeadReadAt=null,this.reportedCheckinSkips.clear(),this.cardsRoute="unknown",this.pendingCards=[],this.cardsInFlight=false,this.lastCardProbe=null,this.answeredCases.clear(),this.reflectUnreadDot()}resetThread(e=[]){super.rescope(),this.historyGeneration+=1,this.unadoptedCreate=null,this.lastTurn=null,this.lastResponseIdValue=null,this.bootstrapPrompts=e,this.replyPrompts=null,this.localRowIds.clear(),this.discardPendingDelta(),this.patch({status:"idle",isStreaming:false,messages:[],conversationId:null,error:null,suggestedPrompts:e,historyCursor:null,isLoadingHistory:false,isBootstrapping:false,unreadCount:null,stopped:false,reconnecting:false,pendingCheckin:null})}newConversation(){this.disposed||(this.resetThread(this.scopePrompts),this.syncPendingCheckin(),this.touchPetList())}dispose(){this.rescope(),this.disposed=true,this.unadoptedCreate=null,this.discardPendingDelta();for(let e of this.handlerTeardowns)e();this.handlerTeardowns.clear(),super.dispose()}adoptConversation(e){this.disposed||(this.unadoptedCreate=null,this.snapshot.conversationId!==e&&this.patch({conversationId:e}))}adoptPrompts(e){if(this.disposed)return;let t=/* @__PURE__ */Object.freeze(Xt(e));this.bootstrapPrompts=t,this.scopePrompts=t,this.replyPrompts===null&&(t.length===0&&this.snapshot.suggestedPrompts.length===0||this.patch({suggestedPrompts:t}))}async listConversations(e){return this.listConversationsWith(e)}async listConversationsWith(e,t){let r=br(e,100);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Vt("accessDenied",false));let i=await this.authedUnary("chat.listConversations",{method:"GET",path:`/widget/v1/conversations${r.value}`},e?.signal,t);if(!this.alive(n)||this.disposed)return err(Vt("accessDenied",false));if(!i.ok)return i;let a=jr(i.value);if(a.ok){for(let e of a.value.conversations)e.unreadCount!==null&&this.unreadByConversation.set(e.id,e.unreadCount);let t=this.snapshot.conversationId,r=t===null?void 0:this.unreadByConversation.get(t);if(r!==void 0&&r!==this.snapshot.unreadCount&&this.patch({unreadCount:r}),this.reflectUnreadDot(),e?.cursor===void 0){let t=a.value.conversations[0];this.unread?.reportPage!==void 0?this.unread.reportPage(e?.petRef??null,a.value.conversations):this.unread?.reportHead(e?.petRef??null,t??null),this.lastHeadReadAt=Date.now(),this.listHead=t===void 0?null:{id:t.id,unreadCount:t.unreadCount},this.reportCheckinSkips(e?.petRef??null),this.lastCardProbe=this.probePendingCheckin(e?.petRef??this.petRef)}}return a}reportCheckinSkips(petRef){let e=[];petRef===null&&e.push("no_pet"),this.auth.userRef===null&&e.push("no_member");for(let t of e)this.reportCheckinSkip(t)}reportCheckinSkip(e){this.reportedCheckinSkips.has(e)||(this.reportedCheckinSkips.add(e),this.telemetry.track("chat.checkin.skipped",{reason:e}))}async touchPetList(){if(this.disposed||this.auth.userRef===null)return;let e=Date.now();this.lastHeadReadAt!==null&&e-this.lastHeadReadAt<15e3||(this.lastHeadReadAt=e,await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}))}async probePendingCheckin(petRef){if(this.auth.userRef===null)return null;if(this.cardsRoute!=="unavailable"){if(this.cardsInFlight)return null;this.cardsInFlight=true;let e=this.epoch,t=petRef===null?"":`?pet_ref=${encodeURIComponent(String(petRef))}`,r=await this.authedUnary("chat.pendingCheckins",{method:"GET",path:`/widget/v1/pending-checkins${t}`},void 0,{maxAttempts:1});if(!this.alive(e)||this.disposed)return null;if(this.cardsInFlight=false,r.ok){this.cardsRoute="served";let e=r.value??{};e.writer_enabled===false&&this.reportCheckinSkip("writer_off");let t=Array.isArray(e.items)?e.items:[],n=[];for(let e of t){let t=gr(e);t===null?this.reportCheckinSkip("card_unreadable"):n.push(this.withAnsweredCase(t))}return this.pendingCards=n,this.syncPendingCheckin(),null}if(r.error.category!=="notFound"&&r.error.category!=="authorization")return this.reportCheckinSkip("cards_failed"),Vr(r.error)?r.error:null;if(r.error.category==="notFound"&&Gr(r.error))return this.cardsRoute="served",this.pendingCards=[],this.reportCheckinSkip("no_pet"),this.syncPendingCheckin(),null;this.cardsRoute="unavailable",this.pendingCards=[],this.reportCheckinSkip("cards_unavailable")}return await this.probeHeadThread(),null}async probeHeadThread(){let e=this.listHead;if(e===null||e.unreadCount===null||e.unreadCount<=0||e.id===this.snapshot.conversationId){this.syncPendingCheckin();return}let t=`${e.id}:${e.unreadCount}`;if(this.probedHead===t){this.syncPendingCheckin();return}this.probedHead=t;let r=this.epoch,n=await this.getMessages(e.id);if(!this.alive(r)||this.disposed)return;if(!n.ok){this.probedHead=null;return}let i=pr(n.value.messages);i===null?this.pendingCheckinByThread.delete(e.id):this.pendingCheckinByThread.set(e.id,/* @__PURE__ */Object.freeze({conversationId:e.id,message:i,checkin:i.checkin??null,occasionRef:i.proactiveOriginRef??null})),this.syncPendingCheckin()}withAnsweredCase(e){if(e.checkin===null)return e;let t=this.answeredCases.get(e.checkin.caseId);return t===void 0?e:/* @__PURE__ */Object.freeze({...e,checkin:t,message:/* @__PURE__ */Object.freeze({...e.message,checkin:t})})}syncPendingCheckin(){let e=this.snapshot.conversationId,t=null,r=this.snapshot.pendingCheckin??null;if(this.cardsRoute==="served")t=this.pendingCards.find(t=>t.conversationId!==e&&(t.checkin?.answer==null||t.message.id===r?.message.id))??null;else{let r=this.listHead;r!==null&&r.id!==e&&(this.unreadByConversation.get(r.id)??r.unreadCount??0)>0&&(t=this.pendingCheckinByThread.get(r.id)??null)}Kr(r,t)||this.patch({pendingCheckin:t})}reflectUnreadDot(){let e=false;for(let t of this.unreadByConversation.values())if(t>0){e=true;break}e!==(this.snapshot.hasUnreadThreads??false)&&this.patch({hasUnreadThreads:e})}async openCheckin(e){if(this.disposed)return err(Vt("accessDenied",false));let t=e?.conversationId??null;if(t!==null){let e=await this.resumeConversation(t);return e.ok?ok(t):err(e.error)}let petRef=e?.petRef??this.petRef,r=await this.listConversations({...petRef===null?{}:{petRef:petRef},limit:1});if(!r.ok)return err(r.error);let n=r.value.conversations[0];if(n===void 0)return ok(null);let i=await this.resumeConversation(n.id);return i.ok?ok(n.id):err(i.error)}async markRead(e){if(this.disposed)return err(Vt("accessDenied",false));let t=this.snapshot.conversationId;if(t===null)return ok(void 0);let r=this.epoch,n=await this.authedUnary("chat.markRead",{method:"POST",path:`/widget/v1/conversations/${t}/read`},e?.signal);return!this.alive(r)||this.disposed?err(Vt("accessDenied",false)):n.ok?(this.unreadByConversation.set(t,0),this.snapshot.conversationId===t&&this.snapshot.unreadCount!==0&&this.patch({unreadCount:0}),this.reflectUnreadDot(),this.unread?.reportRead(t),ok(void 0)):err(n.error)}async submitFeedback(e,t,r,n){if(this.disposed)return err(Vt("accessDenied",false));if(typeof e!="string"||e.trim().length===0||jt(e))return err(Vt("validationFailed",false,"feedback needs the server message id of an assistant reply"));if(!Fr.includes(t))return err(Vt("validationFailed",false,`feedback_type must be one of ${Fr.join(", ")}`));let i=typeof r=="string"?r.trim():"";if([...i].length>Ar)return err(Vt("validationFailed",false,`notes is over ${Ar} characters`));let a={feedback_type:t};i.length>0&&(a.notes=i);let s=this.epoch,l=await this.authedUnary("chat.submitFeedback",{method:"POST",path:`/widget/v1/messages/${encodeURIComponent(e)}/feedback`,body:a},n?.signal);if(!this.alive(s)||this.disposed)return err(Vt("accessDenied",false));if(!l.ok)return err(l.error);let o=l.value?.feedback_id;return ok(/* @__PURE__ */Object.freeze({feedbackId:typeof o=="string"?o:""}))}async answerCheckin(e,t,r){if(this.disposed)return err(Vt("accessDenied",false));let petRef=r?.petRef??this.petRef;if(petRef===null)return err(Vt("validationFailed",false,"a check-in needs the pet the case belongs to"));let n=this.epoch,i=await this.cases.checkin(petRef,e,t,r?.signal?{signal:r.signal}:{});if(!this.alive(n)||this.disposed)return err(Vt("accessDenied",false));if(!i.ok)return i;let a=i.value.case.openedAt,s=/* @__PURE__ */Object.freeze({caseId:e,answer:t,resolutionText:i.value.case.resolutionText,status:i.value.case.status??null,...a!==null?{openedAt:a}:{}}),l=t=>t.checkin?.caseId===e;this.snapshot.messages.some(l)&&this.patch({messages:this.snapshot.messages.map(e=>l(e)?/* @__PURE__ */Object.freeze({...e,checkin:s}):e)}),this.answeredCases.set(e,s);for(let[t,r]of this.pendingCheckinByThread)r.checkin?.caseId===e&&this.pendingCheckinByThread.set(t,/* @__PURE__ */Object.freeze({...r,checkin:s}));return this.pendingCards=this.pendingCards.map(e=>this.withAnsweredCase(e)),this.syncPendingCheckin(),i}async getMessages(e,t){if(!_r(e))return err(Vt("validationFailed",false));let r=br(t,200);if(!r.ok)return r;let n=this.epoch;if(this.disposed)return err(Vt("accessDenied",false));let i=await this.authedUnary("chat.getMessages",{method:"GET",path:`/widget/v1/conversations/${e}/messages${r.value}`},t?.signal);return!this.alive(n)||this.disposed?err(Vt("accessDenied",false)):i.ok?Ir(i.value):i}async resumeConversation(e){if(this.disposed)return err(Vt("accessDenied",false));if(!_r(e))return err(Vt("validationFailed",false));this.resetThread();let t=this.historyGeneration;this.patch({conversationId:e,isBootstrapping:true,isLoadingHistory:true});let r=await this.getMessages(e);if(t!==this.historyGeneration||this.disposed)return err(Vt("accessDenied",false));if(!r.ok)return this.patch({status:"error",error:r.error,isBootstrapping:false,isLoadingHistory:false}),r;let n=this.unreadByConversation.get(e)??null;return this.patch({messages:r.value.messages,historyCursor:r.value.nextCursor,isBootstrapping:false,isLoadingHistory:false,unreadCount:n}),this.stampCheckinStatuses(t),n!==null&&n>0&&this.markRead(),this.syncPendingCheckin(),this.touchPetList(),ok(void 0)}async stampCheckinStatuses(e){let petRef=this.petRef;if(petRef===null||!this.snapshot.messages.some(e=>e.checkin!==void 0&&e.checkin.status===null))return;let t=await this.cases.list(petRef);if(!t.ok||e!==this.historyGeneration||this.disposed)return;let r=new Set(t.value.filter(e=>e.status===fr).map(e=>e.caseId)),n=new Map(t.value.map(e=>[e.caseId,e])),i=false,a=this.snapshot.messages.map(e=>{let t=e.checkin;if(t===void 0||t.status!==null)return e;i=true;let a=n.get(t.caseId),s=t.openedAt??a?.openedAt??null,l=r.has(t.caseId),o=a!==void 0&&(!l||mr({askCount:a.checkinAskCount,answerCount:a.checkinAnswerCount}))?a.lastResponse:null;/* @__PURE__ */
|
|
30
30
|
return Object.freeze({...e,checkin:/* @__PURE__ */Object.freeze({...t,status:l?fr:a?.status??"resolved",answer:t.answer??o,resolutionText:t.resolutionText??a?.resolutionText??null,...s!==null?{openedAt:s}:{}})})});i&&this.patch({messages:a})}async refreshActiveThread(e){if(this.disposed)return err(Vt("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);let t=this.snapshot.conversationId,r=this.historyGeneration,n=await this.listConversationsWith({...this.petRef===null?{}:{petRef:this.petRef},limit:1},{maxAttempts:1}),i=n.ok&&e?.reportLoadFailures===true?this.lastCardProbe:null;if(r!==this.historyGeneration||this.disposed)return err(Vt("accessDenied",false));if(this.snapshot.isStreaming)return ok(void 0);if(t===null){if(!n.ok)return err(n.error);let t=i===null?null:await i;if(t!==null)return err(t);if(e?.openUnreadHead!==true)return ok(void 0);let r=n.value.conversations[0];if(r===void 0||r.unreadCount===null||r.unreadCount<=0)return ok(void 0);if(this.snapshot.conversationId!==null)return ok(void 0);let a=await this.resumeConversation(r.id);return a.ok?ok(void 0):err(a.error)}let a=await this.getMessages(t);if(r!==this.historyGeneration||this.disposed)return err(Vt("accessDenied",false));if(!a.ok)return err(a.error);let s=zr(this.snapshot.messages,a.value.messages,this.localRowIds);if(s.length>0&&this.patch({messages:[...this.snapshot.messages,...s]}),e?.markRead===true&&this.snapshot.conversationId===t&&(this.unreadByConversation.get(t)??0)>0&&this.markRead(),e?.reportLoadFailures===true&&!n.ok&&Vr(n.error))return err(n.error);let l=i===null?null:await i;return l!==null&&r===this.historyGeneration&&!this.disposed?err(l):ok(void 0)}async loadOlderMessages(){if(this.disposed)return err(Vt("accessDenied",false));let e=this.snapshot.conversationId,t=this.snapshot.historyCursor;if(!e||!t||this.snapshot.isLoadingHistory)return ok(void 0);let r=this.historyGeneration;this.patch({isLoadingHistory:true});let n=await this.getMessages(e,{cursor:t});if(r!==this.historyGeneration||this.disposed)return err(Vt("accessDenied",false));if(this.patch({isLoadingHistory:false}),!n.ok)return n;let i=new Set(this.snapshot.messages.map(e=>e.id)),a=n.value.messages.filter(e=>!i.has(e.id));return this.patch({messages:[...a,...this.snapshot.messages],historyCursor:n.value.nextCursor===t?null:n.value.nextCursor}),ok(void 0)}async*retryHistory(e){let t=await this.resumeConversation(e);t.ok||(yield Wt(t.error))}async primeConversation(e){if(this.disposed)return err(Vt("accessDenied",false));let petRef=e?.petRef??null,t={petRef:petRef,settled:this.primeBounded(petRef)};this.unadoptedCreate=t;let r=await t.settled;return this.disposed?err(Vt("accessDenied",false)):(!r.ok&&this.unadoptedCreate===t&&(this.unadoptedCreate=null),r)}async primeBounded(petRef){let e=await this.headThreadWithUnread(petRef);return e.ok?e.value!==null&&!this.snapshot.isStreaming&&this.snapshot.conversationId===null&&(await this.resumeConversation(e.value)).ok?ok(e.value):ok(this.snapshot.conversationId):e.error.code==="accessDenied"||e.error.httpStatus===403?ok(null):err(e.error)}async headThreadWithUnread(petRef){let e=await this.listConversationsWith({...petRef===null?{}:{petRef:petRef},limit:1},{maxAttempts:1});if(!e.ok)return err(e.error);let t=e.value.conversations[0];return t===void 0||t.unreadCount===null||t.unreadCount<=0?ok(null):ok(t.id)}async createConversation(e){let t=this.epoch;if(this.disposed)return err(Vt("accessDenied",false));let petRef=e?.petRef??null,r={petRef:petRef,settled:this.createConversationBounded(petRef)};this.unadoptedCreate=r;let n=await r.settled;return!this.alive(t)||this.disposed?err(Vt("accessDenied",false)):(!n.ok&&this.unadoptedCreate===r&&(this.unadoptedCreate=null),n)}async createConversationBounded(petRef,e){let t={method:"POST",path:"/widget/v1/conversations",body:petRef?{pet_ref:petRef}:{}},r=await this.authedUnary("chat.createConversation",t,e,{maxAttempts:1});if(!r.ok)return err(r.error);let n=r.value?.conversation_id??r.value?.id;return typeof n!="string"||n.length===0?err(Vt("internalError",true)):ok(n)}async getPrompts(e){let t=this.epoch;if(this.disposed)return err(Vt("accessDenied",false));let petRef=e?.petRef??null;if(petRef!==null&&jt(petRef))return err(makeEverfurError("validationFailed",{retryable:false,wireMessage:"pet_ref contains an unpaired surrogate and cannot be encoded"}));let r=petRef!==null?`?pet_ref=${encodeURIComponent(petRef)}`:"",n=await this.authedUnary("chat.getPrompts",{method:"GET",path:`/widget/v1/suggested-prompts${r}`});return!this.alive(t)||this.disposed?err(Vt("accessDenied",false)):n.ok?ok(Qt(n.value)):err(n.error)}async authedUnary(e,t,r,n){return this.funnel.send(e,r?{...t,signal:r}:t,n)}driveWithHandlers(e,t,r){let n=new AbortController,i=Ut(n.signal,t.signal),a=this.beginTurn(e,t),s=this.runTurn(a,i),l=false,o=()=>{l||(l=true,n.abort(),this.handlerTeardowns.delete(o))};return this.handlerTeardowns.add(o),(async()=>{for await(let e of s){if(l)break;r.onFrame(e),e.kind==="done"&&r.onDone(this.lastResponseIdValue)}!l&&this.snapshot.status==="error"&&this.snapshot.error!==null&&r.onError(this.snapshot.error),this.handlerTeardowns.delete(o)})(),o}beginTurn(e,t){let r={epoch:this.epoch,text:e,petRef:t.petRef??this.petRef,imageS3Keys:/* @__PURE__ */Object.freeze([...t.imageS3Keys??[]]),idempotencyKey:t.idempotencyKey??this.makeIdempotencyKey(),userMessageId:this.newId(),assistantMessageId:null,sawDelta:false,conversationIdOverride:t.conversationId??null};return this.localRowIds.add(r.userMessageId),this.patch({error:null,stopped:false,reconnecting:false,messages:[...this.snapshot.messages,$t(r.userMessageId,e,this.stamp())]}),r}async*runTurn(e,t){let r=this.beginOperation(t);e.epoch=r.epoch,this.patch({status:"streaming",isStreaming:true,error:null}),this.lastTurn=e;let n=0,i=false,a=false,s=false;try{for(;;){if(r.signal.aborted||!this.alive(r.epoch))return;let t=e.conversationIdOverride===null&&this.snapshot.conversationId===null,l=t?this.unadoptedCreate:null;if(l!==null&&(e.petRef===null||e.petRef===l.petRef)){let e=await l.settled;if(r.signal.aborted||!this.alive(r.epoch))return;e.ok&&e.value!==null&&this.snapshot.conversationId===null&&(this.adoptConversation(e.value),this.reportConversationStarted(e.value))}if(t&&this.snapshot.conversationId===null){let t=await this.createConversationBounded(e.petRef,r.signal);if(r.signal.aborted||!this.alive(r.epoch))return;if(!t.ok){yield*this.emitTerminal(e,t.error,Wt(t.error));return}this.adoptConversation(t.value),this.reportConversationStarted(t.value)}let o=e.conversationIdOverride??this.snapshot.conversationId;if(o===null){let t=Vt("internalError",!0);yield*this.emitTerminal(e,t,Wt(t));return}this.clearAssistantInProgress(e);let u=new AbortController,c=Ut(r.signal,u.signal),d=null,h=null;try{let t;try{t=await this.funnel.authorize(this.buildSendRequest(e,o))}catch{this.reportSessionRejected();let t=this.authRejected();yield*this.emitTerminal(e,t,Wt(t));return}if(r.signal.aborted||!this.alive(r.epoch))return;h=t.headers?.[C]??null;let n=this.funnel.stream("chat.send",t,c);for await(let t of sr(n,this.budget,c,this.timers)){if(!this.alive(r.epoch))return;if(t.kind==="error"&&t.terminal){d=t;break}if(this.applyFrame(t,e),yield t,t.terminal){r.settle();return}}}finally{u.abort()}if(r.signal.aborted||!this.alive(r.epoch))return;if(d===null){if(this.snapshot.status==="complete")return;let t=Vt("streamIncomplete",!0);yield*this.emitTerminal(e,t,Wt(t));return}let f=fromWire(d.code);if(f==="authExpired"&&this.auth.mode==="personalized"&&!a){a=!0,this.telemetry.track("chat.auth.refresh",{});let t=await this.tryForceRefresh();if(r.signal.aborted||!this.alive(r.epoch))return;if(!t){this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}this.patch({reconnecting:!0});continue}if(!s&&h!==null&&this.auth.mode==="anonymous"&&this.auth.anonIdentity!==void 0&&(d.code===k||f==="authExpired")){s=!0;let e=await this.auth.anonIdentity.token({forceRefresh:!0});if(r.signal.aborted||!this.alive(r.epoch))return;if(e!==null&&e!==h){this.patch({reconnecting:!0});continue}}if(f==="authExpired"){this.telemetry.track("chat.auth.rejected",{}),this.reportSessionRejected();let t=this.authRejected(d);yield*this.emitTerminal(e,t,d);return}if(f==="accessDenied"){this.telemetry.track("chat.access_denied",{}),yield*this.emitTerminal(e,Gt(d),d);return}if(canRecreateOnNotFound(f)&&!i){i=!0,this.telemetry.track("chat.conv.recreate",{}),this.adoptConversation(null),e.conversationIdOverride=null,this.patch({reconnecting:!0});continue}let p=d.retryable&&shouldRetry(f,!0);if(Hr&&p&&n+1<this.errorPolicy.maxAttempts(f));yield*this.emitTerminal(e,Gt(d),d);return}}finally{r.settle()}}*emitTerminal(e,t,r){this.applyError(e,t),yield r}applyFrame(e,t){switch(e.kind){case"accepted":this.snapshot.isStreaming||this.patch({status:"streaming",isStreaming:true});return;case"heartbeat":return;case"delta":this.applyDelta(e.delta,t);return;case"done":this.applyDone(e,t);return;case"analysisStarted":case"analysisComplete":return;case"unknown":this.telemetry.track("chat.frame.unknown",{});return;case"error":return;default:return assertNever(e)}}stamp(){return new Date(this.timers.now()).toISOString()}applyDelta(e,t){if(t.assistantMessageId===null){let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true;let n=this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Lt(e):e);this.patch({status:"streaming",isStreaming:true,messages:[...n,qt(r,e,this.stamp())]});return}if(this.pendingDelta+=e,this.pendingDelta.length>=Br){this.flushPendingDelta(t);return}this.scheduleDeltaFlush(t)}scheduleDeltaFlush(e){if(this.flushHandle!==null)return;let t=this.epoch;this.flushHandle=this.timers.setTimeout(()=>{if(this.flushHandle=null,!this.alive(t)){this.pendingDelta="";return}this.flushPendingDelta(e)},Lr)}flushPendingDelta(e){if(this.clearFlushTimer(),this.pendingDelta.length===0)return;let t=this.pendingDelta;this.pendingDelta="";let r=e.assistantMessageId;if(r===null)return;let n=this.snapshot.messages.map(e=>e.id===r?Bt(e,t):e);this.patch({messages:n})}discardPendingDelta(){this.clearFlushTimer(),this.pendingDelta=""}clearFlushTimer(){this.flushHandle!==null&&(this.timers.clearTimeout(this.flushHandle),this.flushHandle=null)}applyDone(e,t){this.flushPendingDelta(t),this.lastResponseIdValue=e.messageId?e.messageId:null;let r=e.conversationId?e.conversationId:this.snapshot.conversationId,n;if(t.assistantMessageId!==null)n=this.snapshot.messages.map(r=>r.id===t.assistantMessageId?Ht(r,e):r);else{let r=this.newId();this.localRowIds.add(r),t.assistantMessageId=r,t.sawDelta=true,n=[...this.snapshot.messages.map(e=>e.id===t.userMessageId&&e.pending===true?Lt(e):e),Ht(qt(r,"",this.stamp()),e)]}let i=Xt([{category:"",prompts:e.followUpQuestions}]);this.replyPrompts=i.length>0?/* @__PURE__ */Object.freeze(i):null,this.patch({status:"complete",isStreaming:false,error:null,conversationId:r,messages:n,suggestedPrompts:this.replyPrompts??this.bootstrapPrompts,reconnecting:false}),!e.urgencyProvided&&r!==null&&this.classifyTurn(r,this.lastResponseIdValue)}async classifyTurn(conversationId,e){if(e===null||this.disposed)return;let t=String(e);if(this.classifiedMessageIds.has(t))return;this.classifiedMessageIds.add(t);let r=this.epoch,n=this.historyGeneration,i=await this.authedUnary("chat.classifyUrgency",{method:"POST",path:`/widget/v1/conversations/${conversationId}/classify`});if(!i.ok||!this.alive(r)||this.disposed||n!==this.historyGeneration||this.snapshot.conversationId!==conversationId)return;let a=Mr(i.value?.urgency),s=typeof i.value?.reason=="string"?i.value.reason:null,l=t=>t.responseId===e;this.snapshot.messages.some(l)&&this.patch({messages:this.snapshot.messages.map(e=>l(e)?/* @__PURE__ */Object.freeze({...e,urgencyLevel:a,urgencyReason:s,urgencyProvided:true}):e)})}applyError(e,t){this.flushPendingDelta(e);let r=this.snapshot.messages.map(t=>t.id===e.userMessageId&&t.pending===true?Lt(t):t);this.patch({status:"error",isStreaming:false,error:t,messages:r,reconnecting:false});try{this.errorPolicy.onExpectedFailure?.(t)}catch{}}clearAssistantInProgress(e){if(this.discardPendingDelta(),e.assistantMessageId===null)return;let t=e.assistantMessageId;e.assistantMessageId=null,e.sawDelta=false;let r=this.snapshot.messages.filter(e=>e.id!==t);r.length!==this.snapshot.messages.length&&this.patch({messages:r})}buildSendRequest(e,t){let r={message:e.text};return e.imageS3Keys.length>0&&(r.image_s3_keys=e.imageS3Keys),{method:"POST",path:`/widget/v1/conversations/${t}/messages`,body:r,headers:{"Idempotency-Key":e.idempotencyKey}}}async tryForceRefresh(){if(this.auth.mode!=="personalized")return false;try{return await this.auth.identity.currentToken({forceRefresh:!0}),!0}catch{return false}}reportSessionRejected(){this.auth.mode==="personalized"&&this.auth.identity.reportRejected?.()}reportConversationStarted(e){try{this.onConversationStarted?.(e)}catch{}}authRejected(e){return e===void 0?Vt("authRejected",false):makeEverfurError("authRejected",{retryable:false,...e.code?{wireCode:e.code}:{},...e.serverRequestId?{requestId:e.serverRequestId}:{}})}};async function bootstrapChat(e,t){let{controller:r}=t,petRef=e.petRef??null,n=e.resumeConversationId??null,i=[],a=false,s=false,l=false,o=null,u=null,c=n?r.resumeConversation(n).then(e=>e.ok?ok(n):err(e.error)):r.primeConversation(petRef?{petRef:petRef}:void 0),d=r.getPrompts(petRef!==null?{petRef:petRef}:void 0),[h,f]=await Promise.all([c,d]),conversationId=null;if(h.ok)conversationId=h.value,h.value!==null&&i.push(h.value),h.value!==null&&r.getSnapshot().conversationId===null&&r.adoptConversation(h.value);else{let e=h.error;u=e,Qr(e)?(s=true,o=e):(Xr(e)&&(a=true),l=true)}let p=[];f.ok?p=f.value:g(f.error);function g(e){Qr(e)?(s=true,o===null&&(o=e)):Xr(e)&&(a=true)}let m=o!==null?o.displayMessage:null;/* @__PURE__ */
|