@aiquants/chat 0.0.0-stage → 0.1.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.
@@ -0,0 +1,7 @@
1
+ "use strict";var Oe=Object.defineProperty;var gn=Object.getOwnPropertyDescriptor;var fn=Object.getOwnPropertyNames;var yn=Object.prototype.hasOwnProperty;var En=(e,t)=>{for(var n in t)Oe(e,n,{get:t[n],enumerable:!0})},bn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let o of fn(t))!yn.call(e,o)&&o!==n&&Oe(e,o,{get:()=>t[o],enumerable:!(r=gn(t,o))||r.enumerable});return e};var Cn=e=>bn(Oe({},"__esModule",{value:!0}),e);var ja={};En(ja,{chatScenarioRefusal:()=>Ha,createChatScenarioFetch:()=>Ia});module.exports=Cn(ja);var l=e=>{switch(typeof e){case"string":return JSON.stringify(e);case"number":case"boolean":case"undefined":return String(e);case"bigint":return`${String(e)}n`;default:return e===null?"null":typeof e}};var An={string:"a string",boolean:"a boolean",function:"a function",object:"an object",array:"an array",number:"a number"},Rn=(e,t)=>e==="array"?Array.isArray(t):e==="object"?typeof t=="object"&&t!==null:typeof t===e,x=(e,t,n,r)=>{if(!Rn(e,t))throw new TypeError(`${n}: ${r} must be ${An[e]}, got ${l(t)}`)};var Je=(e,t,n,r,o)=>{if(typeof e!="number")throw new TypeError(`${t}: ${n} must be ${r}, got ${l(e)}`);if(!o(e))throw new RangeError(`${t}: ${n} must be ${r}, got ${l(e)}`);return e};var Tn=/^https?:\/\/[^/@]+(?:\/(?!\/)|$)/i,Sn=/[?#\\\s\p{Cc}]/u,wn=/\/(?:\.|%2e){1,2}(?=\/|$)/i,xn=e=>{try{new URL(e)}catch(t){if(t instanceof TypeError)return!1;throw t}return!0},ve=(e,t,n)=>{x("string",e,t,n);let r=e;if(!(r===""||r.startsWith("/")&&!r.startsWith("//")||Tn.test(r)&&xn(r))||Sn.test(r)||wn.test(r)||r.endsWith("/"))throw new RangeError(`${t}: ${n} must be empty, an absolute path or an absolute http(s) URL without credentials whose path does not begin with "//", without a query, a fragment, backslashes, spaces, control characters or "." and ".." segments, and must not end with "/"`)};var Qe=new WeakMap,et=e=>{let t=Qe.get(e);if(t!==void 0)return t;let n=new WeakSet;return Qe.set(e,n),n},On=e=>e.path.length===0?e.message:`${e.path.join(".")}: ${e.message}`,tt=(e,t,n,r,o)=>{let s=e.issues.slice(0,1).map(On).join("");return new RangeError(`${n}: ${r} must be ${o}, got ${l(t)} (${s})`,{cause:e})},nt=(e,t,n,r,o)=>{let s=typeof t=="object"&&t!==null||typeof t=="function"?t:null;if(s!==null&&et(e).has(s))return;let d=e.safeParse(t);if(!d.success)throw tt(d.error,t,n,r,o);s!==null&&et(e).add(s)},B=(e,t,n,r,o)=>{let s=e.safeParse(t);if(!s.success)throw tt(s.error,t,n,r,o);return s.data};var he=e=>{if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===null||typeof t=="object"&&Object.getPrototypeOf(t)===null},h=e=>{if(Array.isArray(e)||he(e)){for(let t of Object.values(e))h(t);Object.freeze(e)}return e},F=e=>h(e);var a=require("zod");var _e={protocol_version:1,events:{"run.started":{terminal:!1,start:!0,fields:{run_uid:"required",conversation_uid:"required",assistant_message_uid:"required",protocol:"required",model:"required",started_at:"required"}},"step.started":{terminal:!1,start:!1,fields:{step:"required",kind:"required"}},"step.retry":{terminal:!1,start:!1,fields:{step:"required",retry_no:"required",reason:"required",wait_ms:"required"}},"text.delta":{terminal:!1,start:!1,fields:{step:"required",text:"required"}},"reasoning.delta":{terminal:!1,start:!1,fields:{step:"required",text:"required"}},usage:{terminal:!1,start:!1,fields:{step:"required",input_tokens:"required",output_tokens:"required",cached_input_tokens:"required",reasoning_tokens:"required",cost_micros:"required"}},"step.finished":{terminal:!1,start:!1,fields:{step:"required",finish_reason:"required",reasoning_ms:"optional"}},"step.reset":{terminal:!1,start:!1,fields:{step:"required"}},"run.completed":{terminal:!0,start:!1,fields:{finish_reason:"required",usage_total:"required",cost_total_micros:"required"}},"run.failed":{terminal:!0,start:!1,fields:{error_code:"required",detail:"required",retryable:"required",calls:"required"}},"run.cancelled":{terminal:!0,start:!1,fields:{cancelled_by:"required",calls:"required"}},"resync-required":{terminal:!0,start:!1,fields:{}}},event_refusals:["unknown_event","reserved_data","too_deep","not_json","shape"],data_max_depth:8,failure_codes:{CHAT_PROVIDER_FAILED:{detail:[{reason:{presence:"required",values:["rate_limited","quota_exhausted","auth_failed","timeout","error"]},retry:{presence:"required",values:["exhausted","withheld","no_time","none"]},retry_after_seconds:{presence:"optional",type:"count"}}]},CHAT_PROVIDER_REFUSED:{detail:[{}]},CHAT_MODEL_UNAVAILABLE:{detail:[{reason:{presence:"required",values:["access_denied","classification","stopped","breaker_open","ledger_mismatch","config_invalid","credential_refused","reasoning_level_unavailable"]}}]},CHAT_ASSISTANT_UNAVAILABLE:{detail:[{}]},CHAT_CONTEXT_OVERFLOW:{detail:[{}]},CHAT_CONTEXT_CHANGED:{detail:[{}]},CHAT_KNOWLEDGE_UNAVAILABLE:{detail:[{}]},CHAT_KNOWLEDGE_BODY_HIDDEN:{detail:[{}]},CHAT_KNOWLEDGE_SCOPE_TOO_LARGE:{detail:[{}]},CHAT_RUN_LIMIT_REACHED:{detail:[{kind:{presence:"required",values:["steps","tool_calls","events","active_time"]}}]},CHAT_CONFIRM_LIMIT_REACHED:{detail:[{}]},CHAT_CONFIDENTIALITY_BLOCKED:{detail:[{}]},CHAT_BUDGET_EXCEEDED:{detail:[{scope:{presence:"required",values:["run"]}},{scope:{presence:"required",values:["user","tenant"]},resets_at:{presence:"required",type:"instant"}}]},CHAT_RUN_INTERRUPTED:{detail:[{}]},CHAT_STOPPED_BY_ADMIN:{detail:[{}]},CHAT_ACCESS_REVOKED:{detail:[{}]},CHAT_TOOL_ARGS_INVALID:{detail:[{}]},CHAT_TOOL_UNAVAILABLE:{detail:[{}]},CHAT_TOOL_TIMEOUT:{detail:[{}]},CHAT_SOURCE_BUSY:{detail:[{}]},CHAT_TOOL_CONTRACT_ERROR:{detail:[{}]},CHAT_TOOL_INTERRUPTED:{detail:[{}]},CHAT_TOOL_RESULT_SHAPE_CHANGED:{detail:[{}]},CHAT_EGRESS_DENIED:{detail:[{}]}},business_codes:{PERMISSION_DENIED:{http_status:403,number:4031,detail:[{}]},NOT_FOUND:{http_status:404,number:4040,detail:[{resource:{presence:"required",values:["conversation","message","run","approval","source","tool","assistant","citation","attachment"]}}]},REQUEST_INVALID:{http_status:422,number:4222,detail:[{errors:{presence:"required",type:"errors"}}]},UPSTREAM_UNAVAILABLE:{http_status:503,number:5039,detail:[{upstream:{presence:"required",values:["model","stream_store","attachment_store"]}}]},CONFIGURATION_ERROR:{http_status:503,number:5030,detail:[{},{errors:{presence:"required",type:"errors"}},{reading:{presence:"required",values:["transcription","ocr"]}}]},CHAT_POLICY_CONSENT_REQUIRED:{http_status:403,number:40310,detail:[{}]},CHAT_POLICY_NOT_PUBLISHED:{http_status:403,number:40311,detail:[{}]},CHAT_STATE_CONFLICT:{http_status:409,number:40910,detail:[{kind:{presence:"required",values:["approval","branch","edit"]}},{kind:{presence:"required",values:["attachment"]},reason:{presence:"required",values:["processing","failed","already_bound"]}}]},CHAT_RUN_ACTIVE:{http_status:423,number:4233,detail:[{}]},CHAT_ADMISSION_BUSY:{http_status:423,number:4234,detail:[{}]},CHAT_CONCURRENCY_LIMIT:{http_status:429,number:4290,detail:[{scope:{presence:"required",values:["user","tenant","model"]}}]},CHAT_RATE_LIMIT:{http_status:429,number:4291,detail:[{}]},CHAT_BUDGET_EXCEEDED:{http_status:429,number:4292,detail:[{scope:{presence:"required",values:["run"]}},{scope:{presence:"required",values:["user","tenant"]},resets_at:{presence:"required",type:"instant"}}]}},request_invalid_types:["egress_denied","sql_statement_rejected","secret_in_text","individual_number_in_text","idempotency_key_reused","message_role","toggle_unknown","secret_name_unknown","reasoning_shape_invalid","reasoning_summary_unsupported","reasoning_level_unsupported","approval_stale_unconfirmed","model_unavailable","assistant_unavailable","declared_level_below_default","attachment_type_refused","attachment_too_large","attachment_too_many_pixels","attachment_too_many_pages","attachment_too_long","attachment_count_exceeded","attachment_unsupported_by_model","attachment_exceeds_provider_limit","attachment_unread_for_external_model"],host_refusal_roles:["chat_disabled","knowledge_body_hidden"],paths:{base:"/ai/chat",json:{listConversations:{method:"GET",path:"/conversations"},createConversation:{method:"POST",path:"/conversations"},getConversation:{method:"GET",path:"/conversations/{conversation_uid}"},updateConversation:{method:"PATCH",path:"/conversations/{conversation_uid}"},deleteConversation:{method:"DELETE",path:"/conversations/{conversation_uid}"},listMessages:{method:"GET",path:"/conversations/{conversation_uid}/messages"},getMessage:{method:"GET",path:"/conversations/{conversation_uid}/messages/{message_uid}"},getMessagePath:{method:"GET",path:"/conversations/{conversation_uid}/messages/{message_uid}/path"},getConversationTree:{method:"GET",path:"/conversations/{conversation_uid}/tree"},searchConversation:{method:"GET",path:"/conversations/{conversation_uid}/search"},setActiveRoot:{method:"PUT",path:"/conversations/{conversation_uid}/active-root"},setActiveChild:{method:"PUT",path:"/messages/{message_uid}/active-child"},startRun:{method:"POST",path:"/conversations/{conversation_uid}/runs"},getRun:{method:"GET",path:"/runs/{run_uid}"},cancelRun:{method:"POST",path:"/runs/{run_uid}/cancel"},exportConversation:{method:"GET",path:"/conversations/{conversation_uid}/export"},putFeedback:{method:"PUT",path:"/messages/{message_uid}/feedback"},listModels:{method:"GET",path:"/models"},getSettings:{method:"GET",path:"/settings"},updateSettings:{method:"PATCH",path:"/settings"},getPolicy:{method:"GET",path:"/policy"},consentPolicy:{method:"POST",path:"/policy-consents"},listPolicyVersions:{method:"GET",path:"/admin/policy"},publishPolicy:{method:"POST",path:"/admin/policy"},getAttachment:{method:"GET",path:"/attachments/{attachment_uid}"},updateAttachment:{method:"PATCH",path:"/attachments/{attachment_uid}"},deleteAttachment:{method:"DELETE",path:"/attachments/{attachment_uid}"}},upload:{createAttachment:{method:"POST",path:"/attachments"}},content:{getAttachmentContent:{method:"GET",path:"/attachments/{attachment_uid}/content"},getAttachmentPreview:{method:"GET",path:"/attachments/{attachment_uid}/preview"}},stream:{runEvents:{method:"GET",path:"/runs/{run_uid}/events"}}},limits:["CHAT_USER_MESSAGE_MAX_CHARS","CHAT_RUN_POLL_INTERVAL_MS","CHAT_RENDER_DIAGRAM_MAX_CHARS","CHAT_RENDER_DIAGRAM_MAX_EDGES","CHAT_RENDER_MAX_DIAGRAMS_PER_MESSAGE","CHAT_RENDER_DIAGRAM_CACHE_MAX_CHARS","CHAT_RENDER_HTML_CACHE_MAX_CHARS","CHAT_RENDER_HTML_MAX_BYTES","CHAT_RENDER_CONVERT_TIMEOUT_MS","CHAT_RENDER_LOAD_TIMEOUT_MS","CHAT_RENDER_MATH_MAX_SIZE_EM","CHAT_RENDER_MATH_MAX_EXPAND","CHAT_RENDER_LIST_OVERSCAN_ROWS","CHAT_RENDER_SMOOTH_HALF_LIFE_MS","CHAT_CONVERSATION_PAGE_SIZE","CHAT_TITLE_SEARCH_PAUSE_MS","CHAT_ATTACHMENT_MAX_COUNT","CHAT_ATTACHMENT_IMAGE_MAX_BYTES","CHAT_ATTACHMENT_PDF_MAX_BYTES","CHAT_ATTACHMENT_AUDIO_MAX_BYTES","CHAT_ATTACHMENT_AUDIO_MAX_SECONDS","CHAT_ATTACHMENT_POLL_INTERVAL_MS"],attachments:{kinds:{image:{flag:"supports_images",accepted_types:["image/png","image/jpeg","image/webp","image/gif"],failure_tags:["secret_in_text","individual_number_in_text"],part:"image_text",fields:{width:"required",height:"required",text_unread:"required"}},document:{flag:"supports_pdf",accepted_types:["application/pdf"],failure_tags:["ocr_unavailable","secret_in_text","individual_number_in_text"],part:"page",fields:{page_count:"required",unread_pages:"required"}},audio:{flag:"supports_audio",accepted_types:["audio/webm","audio/mp4","audio/wav","audio/mpeg","audio/ogg","audio/flac"],failure_tags:["transcription_unavailable","secret_in_text","individual_number_in_text"],part:"segment",fields:{duration_ms:"required"}}},origins:["user","tool"],states:["processing","ready","failed"],failure_tags:["transcription_unavailable","ocr_unavailable","secret_in_text","individual_number_in_text"],parts:{page:{sources:["text_layer","ocr"],fields:{kind:"required",page:"required",source:"required",text:"required"}},segment:{sources:["transcription"],fields:{kind:"required",start_ms:"required",end_ms:"required",source:"required",text:"required"}},image_text:{sources:["ocr"],fields:{kind:"required",source:"required",text:"required"}}},pdf_deliveries:["document","page_text"],resource:{attachment_uid:"required",origin:"required",kind:"required",content_type:"required",byte_size:"required",sha256:"required",file_name:"required",alt_text:"required",state:"required",failure_tag:"required",expires_at:"required",parts:"required"},message_item:{attachment_uid:"required",origin:"required",kind:"required",content_type:"required",byte_size:"required",file_name:"required",alt_text:"required"},upload:{model_uid:"required",file_name:"required",alt_text:"optional",file:"required"},update:{alt_text:"required"},fragments:{message:{attachments:"required"},message_request:{attachment_ids:"required"},model:{supports_images:"required",supports_pdf:"required",supports_audio:"required",pdf_delivery:"required"}}},vocabularies:{run_states:["queued","running","awaiting_approval","completed","failed","cancelled"],active_run_states:["queued","running","awaiting_approval"],run_kinds:["send","edit","regenerate"],finish_reasons:["stop","length"],message_roles:["user","assistant"],reasoning_levels:["off","low","medium","high","max"],title_origins:["user","model"],confidentiality_levels:["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"],model_unavailable_reasons:["access_denied","classification","disabled","ledger_mismatch","config_invalid","credential_refused","stopped","breaker_open"],model_upstream_unavailable_reasons:["stopped","breaker_open"],processing_locations:["internal","external"],export_formats:["markdown","json"],language_codes:["ja","en"],notification_levels:["all","finish","none"],stream_displays:["smooth","immediate","on_finish"],message_actions_displays:["auto","always","hover"],send_keys:["enter","ctrl_enter"]},queries:{listConversations:{cursor:"optional",until:"optional",q:"optional",pinned:"optional"},listMessages:{cursor:"optional"},getMessagePath:{cursor:"optional"},searchConversation:{q:"required"},exportConversation:{format:"required"},listModels:{conversation_uid:"optional",declared_level:"optional"}},resources:{conversation:{conversation_uid:"required",title:"required",title_origin:"required",model_uid:"required",reasoning_level:"required",declared_level:"required",pinned:"required",last_activity_at:"required",purge_due_at:"required",active_root_message_uid:"required",active_run:"required",created_at:"required"},active_run:{run_uid:"required",state:"required"},page:{items:"required",next_cursor:"required"},message:{message_uid:"required",conversation_uid:"required",parent_message_uid:"required",role:"required",text:"required",created_at:"required",active_child_message_uid:"required",sibling_message_uids:"required",attachments:"required"},message_role_fields:{user:{},assistant:{context_cut_before:"required",run:"required"}},message_run:{run_uid:"required",model:"required",state:"required",segment_no:"required",finish_reason:"required",failure:"required",cancelled_by:"required",stream_open:"required",view:"required"},message_run_model:{model_uid:"required",display_name:"required"},run_failure:{error_code:"required",detail:"required"},run_seed:{mark:"required",started:"required",steps:"required"},run_seed_step:{step:"required",kind:"required",text:"required",reasoning:"required",usage:"required",finish:"required"},run_request:{send:{kind:"required",client_request_id:"required",parent_message_uid:"required",text:"required",attachment_ids:"required",model_uid:"required",reasoning_level:"required"},edit:{kind:"required",client_request_id:"required",target_message_uid:"required",text:"required",attachment_ids:"required",model_uid:"required",reasoning_level:"required"},regenerate:{kind:"required",client_request_id:"required",target_message_uid:"required",model_uid:"required",reasoning_level:"required"}},run_accepted:{run_uid:"required",user_message_uid:"required",assistant_message_uid:"required"},conversation_request:{client_request_id:"required",text:"required",attachment_ids:"required",model_uid:"required",reasoning_level:"required",declared_level:"required"},conversation_accepted:{conversation:"required",run:"required"},run:{run_uid:"required",conversation_uid:"required",assistant_message_uid:"required",state:"required",segment_no:"required"},settings:{user_settings:"required",conversation_defaults:"required",limits:"required"},user_settings:{language_code:"required",notification_level:"required",stream_display:"required",follow_scroll:"required",reduce_motion:"required",message_actions_display:"required",collapse_action_labels:"required",send_key:"required",default_model_uid:"required"},user_settings_update:{language_code:"optional",notification_level:"optional",stream_display:"optional",follow_scroll:"optional",reduce_motion:"optional",message_actions_display:"optional",collapse_action_labels:"optional",send_key:"optional",default_model_uid:"optional"},conversation_defaults:{model_uid:"required",declared_level:"required"},model_list:{items:"required"},model:{model_uid:"required",display_name:"required",unavailable_reason:"required",reasoning_levels:"required",default_reasoning_level:"required",reasoning_summary:"required",supports_tools:"required",supports_images:"required",supports_pdf:"required",supports_audio:"required",pdf_delivery:"required",context_window_tokens:"required",max_output_tokens:"required",processing_location:"required",processing_countries:"required",storage_countries:"required",used_for_training:"required",retention_days:"required",contract_terms:"required",recent_failures:"required"},model_hidden:{model_uid:"required",unavailable_reason:"required"},recent_failures:{calls:"required",failures:"required"},error_body:{error_code:"required",error_msg:"required",request_id:"required",detail:"optional",failed_stage:"optional"}},exchanges:{listConversations:{status:200,body:null,answer:"conversation_page"},createConversation:{status:201,body:"conversation_request",answer:"conversation_accepted"},getConversation:{status:200,body:null,answer:"conversation"},listMessages:{status:200,body:null,answer:"message_page"},getMessage:{status:200,body:null,answer:"message"},getMessagePath:{status:200,body:null,answer:"message_page"},startRun:{status:202,body:"run_request",answer:"run_accepted"},getRun:{status:200,body:null,answer:"run"},cancelRun:{status:200,body:null,answer:"run"},listModels:{status:200,body:null,answer:"model_list"},getSettings:{status:200,body:null,answer:"settings"},updateSettings:{status:200,body:"user_settings_update",answer:"settings"},getAttachment:{status:200,body:null,answer:"attachment"},updateAttachment:{status:200,body:"attachment_update",answer:"attachment"},deleteAttachment:{status:204,body:null,answer:null},createAttachment:{status:201,body:"attachment_upload",answer:"attachment"}},invisible:{set:{default_ignorable:["U+00AD","U+034F","U+061C","U+115F..U+1160","U+17B4..U+17B5","U+180B..U+180F","U+200B..U+200F","U+202A..U+202E","U+2060..U+206F","U+3164","U+FE00..U+FE0F","U+FEFF","U+FFA0","U+FFF0..U+FFF8","U+1BCA0..U+1BCA3","U+1D173..U+1D17A","U+E0000..U+E0FFF"],controls:["U+0000..U+0008","U+000B..U+000C","U+000E..U+001F","U+007F..U+009F"],separators:["U+2028..U+2029"],interlinear_annotations:["U+FFF9..U+FFFB"],noncharacters:["U+FDD0..U+FDEF","U+FFFE..U+FFFF","U+1FFFE..U+1FFFF","U+2FFFE..U+2FFFF","U+3FFFE..U+3FFFF","U+4FFFE..U+4FFFF","U+5FFFE..U+5FFFF","U+6FFFE..U+6FFFF","U+7FFFE..U+7FFFF","U+8FFFE..U+8FFFF","U+9FFFE..U+9FFFF","U+AFFFE..U+AFFFF","U+BFFFE..U+BFFFF","U+CFFFE..U+CFFFF","U+DFFFE..U+DFFFF","U+EFFFE..U+EFFFF","U+FFFFE..U+FFFFF","U+10FFFE..U+10FFFF"]},exceptions:{variation_selectors:["U+180B..U+180D","U+180F","U+FE00..U+FE0F","U+E0100..U+E01EF"],joiners:["U+200C..U+200D"],tag_flags:[["U+1F3F4","U+E0067","U+E0062","U+E0065","U+E006E","U+E0067","U+E007F"],["U+1F3F4","U+E0067","U+E0062","U+E0073","U+E0063","U+E0074","U+E007F"],["U+1F3F4","U+E0067","U+E0062","U+E0077","U+E006C","U+E0073","U+E007F"]]},white_space:["U+0009..U+000D","U+0020","U+0085","U+00A0","U+1680","U+2000..U+200A","U+2028..U+2029","U+202F","U+205F","U+3000"]},drawable_diagrams:[{type:"mindmap",header:"mindmap"},{type:"architecture",header:"architecture-beta"},{type:"c4",header:"C4Context"},{type:"kanban",header:"kanban"},{type:"classDiagram",header:"classDiagram-v2"},{type:"class",header:"classDiagram"},{type:"er",header:"erDiagram"},{type:"gantt",header:"gantt"},{type:"info",header:"info"},{type:"pie",header:"pie"},{type:"requirement",header:"requirementDiagram"},{type:"sequence",header:"sequenceDiagram"},{type:"swimlane",header:"swimlane-beta"},{type:"flowchart-v2",header:"flowchart"},{type:"timeline",header:"timeline"},{type:"gitGraph",header:"gitGraph"},{type:"stateDiagram",header:"stateDiagram-v2"},{type:"quadrantChart",header:"quadrantChart"},{type:"sankey",header:"sankey"},{type:"packet",header:"packet"},{type:"xychart",header:"xychart"},{type:"block",header:"block"},{type:"eventmodeling",header:"eventmodeling"},{type:"treeView",header:"treeView-beta"},{type:"ishikawa",header:"ishikawa-beta"},{type:"railroad",header:"railroad-beta"},{type:"railroadEbnf",header:"railroad-ebnf-beta"},{type:"railroadAbnf",header:"railroad-abnf-beta"},{type:"railroadPeg",header:"railroad-peg-beta"},{type:"venn",header:"venn-beta"},{type:"wardley",header:"wardley-beta"},{type:"cynefin",header:"cynefin-beta"}]};var rt=e=>{if(!(Number.isInteger(e)&&e>=1))throw new RangeError(`the most members of one set of marks is not a positive integer: ${e}`);let t=[],n=new Set;return t.push(n),{has:r=>{for(let o of t)if(o.has(r))return!0;return!1},add:r=>{n.size===e&&(n=new Set,t.push(n)),n.add(r)}}};var Ne=e=>`U+${e.toString(16).toUpperCase().padStart(4,"0")}`,at=e=>{let t=/^U\+[0-9A-F]{4,6}$/.test(e)?Number.parseInt(e.slice(2),16):Number.NaN;if(!(t<=1114111)||t>=55296&&t<=57343||Ne(t)!==e)throw new Error(`not the contract's spelling of a code point: ${JSON.stringify(e)}`);return t},me=(e,t)=>{let n=[];for(let r of e){let o=r.split("..").map(at),s=o[0],d=o.at(-1);if(o.length>2||o.length===2&&!(s<d))throw new Error(`not the contract's spelling of a range of code points in ${t}: ${JSON.stringify(r)}`);let i=n.at(-1);if(i!==void 0&&!(s>i[1]+1))throw new Error(`not in order with a gap after every range in ${t}: ${JSON.stringify(r)}`);n.push([s,d])}return n},ie=(e,t)=>e.some(([n,r])=>n<=t&&t<=r),Nn=e=>{let t=[],n=Object.entries(e.set).flatMap(([i,c])=>me(c,`the set's ${i}`)).sort((i,c)=>i[0]-c[0]);for(let[i,c]of n){let u=t.at(-1);if(u===void 0||i>u[1]+1)t.push([i,c]);else if(i===u[1]+1)t[t.length-1]=[u[0],c];else throw new Error(`two categories of the set share ${Ne(i)}`)}let r=me(e.exceptions.variation_selectors,"the variation selectors"),o=me(e.exceptions.joiners,"the joiners");for(let[i,c]of[...r,...o])if(!t.some(u=>u[0]<=i&&c<=u[1]))throw new Error(`an exception is outside the set: ${Ne(i)}`);let s=me(e.white_space,"the white space"),d=e.exceptions.tag_flags.map(i=>{let[c,...u]=i.map(at);if(c===void 0||ie(t,c)||ie(s,c)||u.length===0||!u.every(R=>ie(t,R)))throw new Error(`a tag flag is not a visible character followed by characters of the set: ${JSON.stringify(i)}`);return[c,...u]});return{set:t,variationSelectors:r,joiners:o,tagFlags:d,whiteSpace:s}},$=Nn(_e.invisible),ge=e=>e.map(([t,n])=>t===n?`\\u{${t.toString(16)}}`:`\\u{${t.toString(16)}}-\\u{${n.toString(16)}}`).join(""),ot=`[^${ge($.set)}${ge($.whiteSpace)}]`,Ka=new RegExp(`(${$.tagFlags.map(e=>e.map(t=>`\\u{${t.toString(16)}}`).join("")).join("|")})|[${ge($.set)}]`,"gu"),Ja=new RegExp(ot,"uy"),Qa=new RegExp(`[${ge($.variationSelectors)}]`,"uy"),eo=new RegExp(ot,"u"),to=[...new Map($.tagFlags.flatMap(([e,...t])=>t.slice(0,-1).map((n,r)=>{let o=String.fromCodePoint(...t.slice(0,r+1));return[String.fromCodePoint(e)+o,o.length]})))].map(([e,t])=>({ending:e,held:t})),kn=(e,t)=>{let n=e.charCodeAt(t-1),r=e.charCodeAt(t-2);return n>=56320&&n<=57343&&r>=55296&&r<=56319?t-2:t-1};var st=e=>{let t=0;for(let r of e){if(!ie($.whiteSpace,r.codePointAt(0)))break;t+=r.length}let n=e.length;for(;n>t;){let r=kn(e,n);if(!ie($.whiteSpace,e.codePointAt(r)))break;n=r}return t===n?null:e.slice(t,n)};var m=F(_e),io=m.protocol_version,co=h(["chat_disabled","knowledge_body_hidden"]),Un=h(["CHAT_USER_MESSAGE_MAX_CHARS","CHAT_RUN_POLL_INTERVAL_MS","CHAT_RENDER_DIAGRAM_MAX_CHARS","CHAT_RENDER_DIAGRAM_MAX_EDGES","CHAT_RENDER_MAX_DIAGRAMS_PER_MESSAGE","CHAT_RENDER_DIAGRAM_CACHE_MAX_CHARS","CHAT_RENDER_HTML_CACHE_MAX_CHARS","CHAT_RENDER_HTML_MAX_BYTES","CHAT_RENDER_CONVERT_TIMEOUT_MS","CHAT_RENDER_LOAD_TIMEOUT_MS","CHAT_RENDER_MATH_MAX_SIZE_EM","CHAT_RENDER_MATH_MAX_EXPAND","CHAT_RENDER_LIST_OVERSCAN_ROWS","CHAT_RENDER_SMOOTH_HALF_LIFE_MS","CHAT_CONVERSATION_PAGE_SIZE","CHAT_TITLE_SEARCH_PAUSE_MS","CHAT_ATTACHMENT_MAX_COUNT","CHAT_ATTACHMENT_IMAGE_MAX_BYTES","CHAT_ATTACHMENT_PDF_MAX_BYTES","CHAT_ATTACHMENT_AUDIO_MAX_BYTES","CHAT_ATTACHMENT_AUDIO_MAX_SECONDS","CHAT_ATTACHMENT_POLL_INTERVAL_MS"]),lo=m.drawable_diagrams,y=h({run_states:["queued","running","awaiting_approval","completed","failed","cancelled"],active_run_states:["queued","running","awaiting_approval"],run_kinds:["send","edit","regenerate"],finish_reasons:["stop","length"],message_roles:["user","assistant"],reasoning_levels:["off","low","medium","high","max"],title_origins:["user","model"],confidentiality_levels:["PUBLIC","INTERNAL","DEPARTMENT","CONFIDENTIAL","RESTRICTED"],model_unavailable_reasons:["access_denied","classification","disabled","ledger_mismatch","config_invalid","credential_refused","stopped","breaker_open"],model_upstream_unavailable_reasons:["stopped","breaker_open"],processing_locations:["internal","external"],export_formats:["markdown","json"],language_codes:["ja","en"],notification_levels:["all","finish","none"],stream_displays:["smooth","immediate","on_finish"],message_actions_displays:["auto","always","hover"],send_keys:["enter","ctrl_enter"]}),Fn=/^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,mt=/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})\.[0-9]{7}Z$/,Hn=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,In=e=>{let t=mt.exec(e);if(t===null)return!1;let[n,r,o,s,d,i]=t.slice(1).map(Number),c=new Date(0);return c.setUTCFullYear(n,r-1,o),c.setUTCHours(s,d,i,0),n>=1&&c.getUTCFullYear()===n&&c.getUTCMonth()===r-1&&c.getUTCDate()===o&&c.getUTCHours()===s&&c.getUTCMinutes()===d&&c.getUTCSeconds()===i},p=a.z.string().regex(Fn),z=a.z.string().regex(mt).refine(In,{message:"not a real instant"}),C=a.z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),M=a.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),be=e=>!Hn.test(e),g=a.z.string().min(1).refine(be,{message:"a lone surrogate"}),H=a.z.string().refine(be,{message:"a lone surrogate"}),it=g.refine(e=>(st(e)??"")===e,{message:"white space at an end"}),je=h(Object.keys(m.failure_codes)),jn=a.z.enum(je),_=a.z.object({}).strict(),De=h({CHAT_PROVIDER_FAILED:a.z.object({reason:a.z.enum(["rate_limited","quota_exhausted","auth_failed","timeout","error"]),retry:a.z.enum(["exhausted","withheld","no_time","none"]),retry_after_seconds:C.optional()}).strict(),CHAT_PROVIDER_REFUSED:_,CHAT_MODEL_UNAVAILABLE:a.z.object({reason:a.z.enum(["access_denied","classification","stopped","breaker_open","ledger_mismatch","config_invalid","credential_refused","reasoning_level_unavailable"])}).strict(),CHAT_ASSISTANT_UNAVAILABLE:_,CHAT_CONTEXT_OVERFLOW:_,CHAT_CONTEXT_CHANGED:_,CHAT_KNOWLEDGE_UNAVAILABLE:_,CHAT_KNOWLEDGE_BODY_HIDDEN:_,CHAT_KNOWLEDGE_SCOPE_TOO_LARGE:_,CHAT_RUN_LIMIT_REACHED:a.z.object({kind:a.z.enum(["steps","tool_calls","events","active_time"])}).strict(),CHAT_CONFIRM_LIMIT_REACHED:_,CHAT_CONFIDENTIALITY_BLOCKED:_,CHAT_BUDGET_EXCEEDED:a.z.union([a.z.object({scope:a.z.enum(["run"])}).strict(),a.z.object({scope:a.z.enum(["user","tenant"]),resets_at:z}).strict()]),CHAT_RUN_INTERRUPTED:_,CHAT_STOPPED_BY_ADMIN:_,CHAT_ACCESS_REVOKED:_,CHAT_TOOL_ARGS_INVALID:_,CHAT_TOOL_UNAVAILABLE:_,CHAT_TOOL_TIMEOUT:_,CHAT_SOURCE_BUSY:_,CHAT_TOOL_CONTRACT_ERROR:_,CHAT_TOOL_INTERRUPTED:_,CHAT_TOOL_RESULT_SHAPE_CHANGED:_,CHAT_EGRESS_DENIED:_}),Dn=a.z.object({loc:a.z.array(a.z.union([H,C])),msg:g,type:g}).strict(),$n=a.z.array(Dn).min(1),dt=a.z.object({errors:$n}).strict(),gt=h({PERMISSION_DENIED:_,NOT_FOUND:a.z.object({resource:a.z.enum(["conversation","message","run","approval","source","tool","assistant","citation","attachment"])}).strict(),REQUEST_INVALID:dt,UPSTREAM_UNAVAILABLE:a.z.object({upstream:a.z.enum(["model","stream_store","attachment_store"])}).strict(),CONFIGURATION_ERROR:a.z.union([_,dt,a.z.object({reading:a.z.enum(["transcription","ocr"])}).strict()]),CHAT_POLICY_CONSENT_REQUIRED:_,CHAT_POLICY_NOT_PUBLISHED:_,CHAT_STATE_CONFLICT:a.z.union([a.z.object({kind:a.z.enum(["approval","branch","edit"])}).strict(),a.z.object({kind:a.z.enum(["attachment"]),reason:a.z.enum(["processing","failed","already_bound"])}).strict()]),CHAT_RUN_ACTIVE:_,CHAT_ADMISSION_BUSY:_,CHAT_CONCURRENCY_LIMIT:a.z.object({scope:a.z.enum(["user","tenant","model"])}).strict(),CHAT_RATE_LIMIT:_,CHAT_BUDGET_EXCEEDED:De.CHAT_BUDGET_EXCEEDED}),uo=h(["egress_denied","sql_statement_rejected","secret_in_text","individual_number_in_text","idempotency_key_reused","message_role","toggle_unknown","secret_name_unknown","reasoning_shape_invalid","reasoning_summary_unsupported","reasoning_level_unsupported","approval_stale_unconfirmed","model_unavailable","assistant_unavailable","declared_level_below_default","attachment_type_refused","attachment_too_large","attachment_too_many_pixels","attachment_too_many_pages","attachment_too_long","attachment_count_exceeded","attachment_unsupported_by_model","attachment_exceeds_provider_limit","attachment_unread_for_external_model"]),ft=a.z.object({call:p,status:a.z.enum(["succeeded","failed","denied","cancelled","interrupted"]),error_code:jn.nullable()}).strict(),Mn=a.z.object({input_tokens:C,output_tokens:C,cached_input_tokens:C,reasoning_tokens:C}).strict(),Pn=e=>a.z.object({error_code:a.z.literal(e),detail:De[e],retryable:a.z.boolean(),calls:a.z.array(ft)}).strict(),Ln=je.map(e=>Pn(e)),ce=h({"run.started":a.z.object({run_uid:p,conversation_uid:p,assistant_message_uid:p,protocol:a.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),model:a.z.object({model_uid:p,display_name:g}).strict(),started_at:z}).strict(),"step.started":a.z.object({step:M,kind:a.z.enum(["llm"])}).strict(),"step.retry":a.z.object({step:M,retry_no:a.z.number().int().positive().max(Number.MAX_SAFE_INTEGER),reason:a.z.enum(["rate_limited","timeout","error"]),wait_ms:C}).strict(),"text.delta":a.z.object({step:M,text:g}).strict(),"reasoning.delta":a.z.object({step:M,text:g}).strict(),usage:a.z.object({step:M,input_tokens:C,output_tokens:C,cached_input_tokens:C,reasoning_tokens:C,cost_micros:C}).strict(),"step.finished":a.z.object({step:M,finish_reason:a.z.enum(y.finish_reasons),reasoning_ms:C.optional()}).strict(),"step.reset":a.z.object({step:M}).strict(),"run.completed":a.z.object({finish_reason:a.z.enum(y.finish_reasons),usage_total:Mn,cost_total_micros:C}).strict(),"run.failed":a.z.discriminatedUnion("error_code",Ln),"run.cancelled":a.z.object({cancelled_by:a.z.enum(["user","admin"]),calls:a.z.array(ft)}).strict(),"resync-required":a.z.object({}).strict()});var po=h(Object.keys(m.events).filter(e=>m.events[e].start)),ho=h(Object.keys(m.events).filter(e=>m.events[e].terminal)),_o=h(["unknown_event","reserved_data","too_deep","not_json","shape"]),ct=m.data_max_depth;var Bn=(e,t)=>{let n=new Set,r=e.replace(/\{([a-z_]+)\}/g,(s,d)=>{n.add(d);let i=t[d];if(i===void 0||i==="")throw new RangeError(`path ${e} needs a value for {${d}}`);return encodeURIComponent(i)}),o=Object.keys(t).filter(s=>!n.has(s));if(o.length>0)throw new RangeError(`path ${e} names no ${o.map(s=>`{${s}}`).join(", ")}`);return r},yt=(e,t)=>({method:e.method,path:`${m.paths.base}${Bn(e.path,t)}`}),Et=(e,t={})=>yt(m.paths.json[e],t),bt=(e,t={})=>yt(m.paths.upload[e],t);var zn=h({image:"supports_images",document:"supports_pdf",audio:"supports_audio"}),mo=h(Object.keys(zn)),Z=h({image:["image/png","image/jpeg","image/webp","image/gif"],document:["application/pdf"],audio:["audio/webm","audio/mp4","audio/wav","audio/mpeg","audio/ogg","audio/flac"]}),Vn=h(["user","tool"]),Gn=h(["processing","ready","failed"]),Xn=h(["transcription_unavailable","ocr_unavailable","secret_in_text","individual_number_in_text"]),Zn=h({image:["secret_in_text","individual_number_in_text"],document:["ocr_unavailable","secret_in_text","individual_number_in_text"],audio:["transcription_unavailable","secret_in_text","individual_number_in_text"]}),Yn=h(["document","page_text"]),Wn=/^[0-9a-f]{64}$/,Kn=a.z.string().regex(Wn),N=C.positive(),Ct=a.z.object({kind:a.z.literal("page"),page:N,source:a.z.enum(["text_layer","ocr"]),text:g}).strict(),At=a.z.object({kind:a.z.literal("segment"),start_ms:C,end_ms:C,source:a.z.enum(["transcription"]),text:g}).strict(),Rt=a.z.object({kind:a.z.literal("image_text"),source:a.z.enum(["ocr"]),text:g}).strict(),go=h({page:Ct,segment:At,image_text:Rt}),Y={attachment_uid:p,origin:a.z.enum(Vn)},ke={byte_size:N,sha256:Kn,file_name:g,alt_text:g.nullable(),state:a.z.enum(Gn),failure_tag:a.z.enum(Xn).nullable(),expires_at:z.nullable()},qe={byte_size:N,file_name:g,alt_text:g.nullable()},W={image:{width:N,height:N,text_unread:a.z.boolean()},document:{page_count:N,unread_pages:a.z.array(N)},audio:{duration_ms:N}},Ue=h({image:a.z.object({...Y,kind:a.z.literal("image"),content_type:a.z.enum(Z.image),...ke,parts:a.z.array(Rt),...W.image}).strict(),document:a.z.object({...Y,kind:a.z.literal("document"),content_type:a.z.enum(Z.document),...ke,parts:a.z.array(Ct),...W.document}).strict(),audio:a.z.object({...Y,kind:a.z.literal("audio"),content_type:a.z.enum(Z.audio),...ke,parts:a.z.array(At),...W.audio}).strict()}),Fe=h({image:a.z.object({...Y,kind:a.z.literal("image"),content_type:a.z.enum(Z.image),...qe,...W.image}).strict(),document:a.z.object({...Y,kind:a.z.literal("document"),content_type:a.z.enum(Z.document),...qe,...W.document}).strict(),audio:a.z.object({...Y,kind:a.z.literal("audio"),content_type:a.z.enum(Z.audio),...qe,...W.audio}).strict()}),A=e=>(t,n)=>e.addIssue({code:a.z.ZodIssueCode.custom,path:[...t],message:n}),Tt=(e,t,n)=>{let r=0;for(let[o,s]of e.entries())s>t?n(["unread_pages",o],"past the last page"):s<=r&&n(["unread_pages",o],"not after the page before it"),r=s},Jn=(e,t,n,r)=>{let o=new Set(n),s=0;for(let[d,i]of e.entries())i.page>t?r(["parts",d,"page"],"past the last page"):i.page<s?r(["parts",d,"page"],"before the page of the part before it"):o.has(i.page)&&r(["parts",d,"page"],"a page named unread"),s=i.page},Qn=(e,t,n)=>{let r=0;for(let[o,s]of e.entries())s.end_ms<s.start_ms?n(["parts",o,"end_ms"],"before its start"):s.end_ms>t&&n(["parts",o,"end_ms"],"past the end of the audio"),s.start_ms<r&&n(["parts",o,"start_ms"],"before the start of the segment before it"),r=s.start_ms},er=(e,t)=>{let n=A(t);switch(e.state==="failed"!=(e.failure_tag!==null)&&n(["failure_tag"],"a failure tag goes with the failed state and with no other"),e.failure_tag!==null&&!Zn[e.kind].includes(e.failure_tag)&&n(["failure_tag"],"a failure tag the kind does not fail with"),e.state!=="ready"&&e.parts.length>0&&n(["parts"],"only a ready attachment holds read text"),e.kind){case"image":e.parts.length>1&&n(["parts"],"an image holds one read text at most"),e.text_unread&&(e.state!=="ready"&&n(["text_unread"],"only a ready attachment marks its text unread"),e.parts.length>0&&n(["text_unread"],"an image marked unread holds no read text"));break;case"document":e.state!=="ready"&&e.unread_pages.length>0&&n(["unread_pages"],"only a ready attachment names unread pages"),Tt(e.unread_pages,e.page_count,n),Jn(e.parts,e.page_count,e.unread_pages,n);break;case"audio":Qn(e.parts,e.duration_ms,n);break}},tr=a.z.discriminatedUnion("kind",[Ue.image,Ue.document,Ue.audio]).superRefine(er),nr=a.z.discriminatedUnion("kind",[Fe.image,Fe.document,Fe.audio]).superRefine((e,t)=>{e.kind==="document"&&Tt(e.unread_pages,e.page_count,A(t))}),Ce=(e,t,n)=>{let r=new Set;for(let[o,s]of e.entries())r.has(s)&&t(n(o),"given twice"),r.add(s)},rr=a.z.array(p).superRefine((e,t)=>Ce(e,A(t),n=>[n])),ar=a.z.array(nr).superRefine((e,t)=>Ce(e.map(n=>n.attachment_uid),A(t),n=>[n,"attachment_uid"])),le=h({message:{attachments:ar},message_request:{attachment_ids:rr},model:{supports_images:a.z.boolean(),supports_pdf:a.z.boolean(),supports_audio:a.z.boolean(),pdf_delivery:a.z.enum(Yn).nullable()}}),or=(e,t)=>{e.supports_pdf!==(e.pdf_delivery!==null)&&A(t)(["pdf_delivery"],"how a model takes a PDF goes with its flag for PDFs and with nothing else")},sr=a.z.object({model_uid:p,file_name:g,alt_text:g.optional(),file:a.z.instanceof(Blob)}).strict(),ir=a.z.object({alt_text:g.nullable()}).strict(),dr=/^[A-Za-z0-9_-]{1,1024}$/,cr=/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,St=/^(0|[1-9][0-9]{0,19})-(0|[1-9][0-9]{0,19})$/,lr=(1n<<64n)-1n,de=a.z.string().regex(dr),fe=a.z.string().regex(cr),ur=e=>{let t=St.exec(e);return t===null?!1:t.slice(1).every(n=>BigInt(n)<=lr)},pr=a.z.string().regex(St).refine(ur,{message:"a part above 64 bits"}).brand(),hr=a.z.object({step:M,kind:ce["step.started"].shape.kind,text:H,reasoning:H,usage:ce.usage.omit({step:!0}).nullable(),finish:ce["step.finished"].omit({step:!0}).nullable()}).strict(),$e=(e,t,n)=>{for(let[r,o]of e.steps.entries()){let s=e.steps[r-1];t.order&&s!==void 0&&s.step>=o.step&&n(["steps",r,"step"],"the seed's steps are not in increasing order of their numbers"),t.mark&&e.mark===null&&(o.text!==""||o.reasoning!=="")&&n(["steps",r],"a seed without a mark holds a step's text or reasoning")}},wt=a.z.object({mark:pr.nullable(),started:ce["run.started"].nullable(),steps:a.z.array(hr)}).strict(),_r=wt.superRefine((e,t)=>$e(e,{order:!0,mark:!1},A(t))),fo=wt.superRefine((e,t)=>$e(e,{order:!0,mark:!0},A(t))),mr=a.z.object({run_uid:p,state:a.z.enum(y.active_run_states)}).strict(),Me=a.z.object({conversation_uid:p,title:g.nullable(),title_origin:a.z.enum(y.title_origins).nullable(),model_uid:p,reasoning_level:a.z.enum(y.reasoning_levels),declared_level:a.z.enum(y.confidentiality_levels),pinned:a.z.boolean(),last_activity_at:z,purge_due_at:z.nullable(),active_root_message_uid:p,active_run:mr.nullable(),created_at:z}).strict().superRefine((e,t)=>{e.title===null!=(e.title_origin===null)&&A(t)(["title_origin"],"a title and its origin are null together")}),xt=e=>a.z.object({items:a.z.array(e),next_cursor:de.nullable()}).strict(),gr=xt(Me),fr=e=>a.z.object({error_code:a.z.literal(e),detail:De[e]}).strict(),yr=a.z.discriminatedUnion("error_code",je.map(e=>fr(e))),Er=a.z.object({model_uid:p,display_name:g.nullable()}).strict(),br=a.z.object({run_uid:p,model:Er,state:a.z.enum(y.run_states),segment_no:N,finish_reason:a.z.enum(y.finish_reasons).nullable(),failure:yr.nullable(),cancelled_by:ce["run.cancelled"].shape.cancelled_by.nullable(),stream_open:a.z.boolean(),view:_r}).strict().superRefine((e,t)=>{let n=A(t);e.state==="completed"!=(e.finish_reason!==null)&&n(["finish_reason"],"a run's finish reason goes with its completed state and with nothing else"),e.state==="failed"!=(e.failure!==null)&&n(["failure"],"a run's failure goes with its failed state and with nothing else"),e.state==="cancelled"!=(e.cancelled_by!==null)&&n(["cancelled_by"],"who cancelled a run goes with its cancelled state and with nothing else"),e.stream_open&&$e(e.view,{order:!1,mark:!0},(r,o)=>n(["view",...r],o))}),lt={message_uid:p,conversation_uid:p,parent_message_uid:p.nullable()},ut={created_at:z,active_child_message_uid:p.nullable(),sibling_message_uids:a.z.array(p),...le.message},pt=h({user:a.z.object({...lt,role:a.z.literal("user"),text:H,...ut}).strict(),assistant:a.z.object({...lt,role:a.z.literal("assistant"),text:H,...ut,context_cut_before:p.nullable(),run:br}).strict()}),Cr=(e,t)=>{let n=A(t);Ce(e.sibling_message_uids,n,r=>["sibling_message_uids",r]),e.sibling_message_uids.includes(e.message_uid)||n(["sibling_message_uids"],"a message is one of its siblings"),e.role==="user"&&e.text===""&&e.attachments.length===0&&n(["text"],"a message without text holds an attachment")},Ot=a.z.discriminatedUnion("role",[pt.user,pt.assistant]).superRefine(Cr),Ar=xt(Ot),ye={model_uid:p,reasoning_level:a.z.enum(y.reasoning_levels)},He=h({send:a.z.object({kind:a.z.literal("send"),client_request_id:fe,parent_message_uid:p,text:H,...le.message_request,...ye}).strict(),edit:a.z.object({kind:a.z.literal("edit"),client_request_id:fe,target_message_uid:p,text:H,...le.message_request,...ye}).strict(),regenerate:a.z.object({kind:a.z.literal("regenerate"),client_request_id:fe,target_message_uid:p,...ye}).strict()}),vt=(e,t)=>{e.text===""&&e.attachment_ids.length===0&&t(["text"],"a message without text binds an attachment")},Rr=a.z.discriminatedUnion("kind",[He.send,He.edit,He.regenerate]).superRefine((e,t)=>{e.kind!=="regenerate"&&vt(e,A(t))}),Nt=a.z.object({run_uid:p,user_message_uid:p.nullable(),assistant_message_uid:p}).strict(),Tr=a.z.object({client_request_id:fe,text:H,...le.message_request,...ye,declared_level:a.z.enum(y.confidentiality_levels)}).strict().superRefine((e,t)=>vt(e,A(t))),Sr=a.z.object({conversation:Me,run:Nt.extend({user_message_uid:p})}).strict(),wr=a.z.object({run_uid:p,conversation_uid:p,assistant_message_uid:p,state:a.z.enum(y.run_states),segment_no:N}).strict(),kt=a.z.object({language_code:a.z.enum(y.language_codes),notification_level:a.z.enum(y.notification_levels),stream_display:a.z.enum(y.stream_displays),follow_scroll:a.z.boolean(),reduce_motion:a.z.boolean(),message_actions_display:a.z.enum(y.message_actions_displays),collapse_action_labels:a.z.boolean(),send_key:a.z.enum(y.send_keys),default_model_uid:p.nullable()}).strict(),xr=kt.partial().superRefine((e,t)=>{Object.values(e).every(n=>n===void 0)&&A(t)([],"no setting; an update names at least one setting it changes")}),Or=a.z.object({model_uid:p.nullable(),declared_level:a.z.enum(y.confidentiality_levels)}).strict(),vr=a.z.object(Object.fromEntries(Un.map(e=>[e,N]))).strict(),Nr=a.z.object({user_settings:kt,conversation_defaults:Or,limits:vr}).strict(),kr=a.z.object({calls:C,failures:C}).strict().superRefine((e,t)=>{e.failures>e.calls&&A(t)(["failures"],"more failures than calls")}),qr=(e,t)=>{let n=-1;for(let[r,o]of e.reasoning_levels.entries()){let s=y.reasoning_levels.indexOf(o);s<=n&&t(["reasoning_levels",r],"not after the level before it in the vocabulary's order"),n=s}e.reasoning_levels.includes(e.default_reasoning_level)||t(["default_reasoning_level"],"not one of the model's reasoning levels")},Ur=a.z.object({model_uid:p,display_name:g,unavailable_reason:a.z.enum(y.model_unavailable_reasons).exclude(["access_denied"]).nullable(),reasoning_levels:a.z.array(a.z.enum(y.reasoning_levels)).min(1),default_reasoning_level:a.z.enum(y.reasoning_levels),reasoning_summary:a.z.boolean(),supports_tools:a.z.boolean(),...le.model,context_window_tokens:N,max_output_tokens:N,processing_location:a.z.enum(y.processing_locations),processing_countries:g,storage_countries:g,used_for_training:a.z.boolean(),retention_days:C,contract_terms:g,recent_failures:kr.nullable()}).strict().superRefine((e,t)=>{or(e,t),qr(e,A(t))}),Fr=a.z.object({model_uid:p,unavailable_reason:a.z.literal("access_denied")}).strict(),Hr=a.z.object({items:a.z.array(a.z.union([Ur,Fr]))}).strict().superRefine((e,t)=>{let n=A(t);for(let[r,o]of e.items.entries())r>0&&o.unavailable_reason==="access_denied"&&n(["items",r],"a hidden row comes first");Ce(e.items.map(r=>r.model_uid),n,r=>["items",r,"model_uid"])}),qt=new Map(Object.keys(m.business_codes).map(e=>[m.business_codes[e].number,e])),Ee="a value no JSON text reads as",Ir=(e,t)=>{let n=e.length,r=Reflect.ownKeys(e).length-1;return n!==r?{kind:"problem",message:Ee}:{kind:"array",source:e,length:r,depth:t,copy:[],next:0}},ht=(e,t)=>{let n=[];for(let r of Reflect.ownKeys(e)){if(typeof r=="symbol")return{kind:"problem",message:"a member name that is not a text"};if(!be(r))return{kind:"problem",message:"a lone surrogate"};n.push(r)}return{kind:"object",source:e,names:n,depth:t,copy:{},next:0}},jr=e=>{let t=e.kind==="array"?e.length:e.names.length;if(e.next===t)return;let n=e.next;return e.next+=1,e.kind==="array"?n:e.names[n]},_t=(e,t,n)=>{Object.defineProperty(e,t,{__proto__:null,value:n,writable:!0,enumerable:!0,configurable:!0})},Dr=e=>{if(!he(e))return{kind:"problem",message:"not a JSON object"};let t=ht(e,1);if(t.kind==="problem")return t;let n=rt(4194304);n.add(e);let r=[t];for(let o=r.at(-1);o!==void 0;o=r.at(-1)){let s=jr(o);if(s===void 0){r.pop();continue}let d=Object.getOwnPropertyDescriptor(o.source,s);if(d===void 0||d.enumerable!==!0||!Object.hasOwn(d,"value"))return{kind:"problem",message:Ee};let i=d.value;if(typeof i=="string"&&!be(i))return{kind:"problem",message:"a lone surrogate"};if(typeof i=="number"&&!(Math.abs(i)<=Number.MAX_SAFE_INTEGER))return{kind:"problem",message:`a number outside \xB1${Number.MAX_SAFE_INTEGER}`};if(i===null||typeof i=="string"||typeof i=="number"||typeof i=="boolean"){_t(o.copy,s,i);continue}if(typeof i!="object")return{kind:"problem",message:Ee};if(n.has(i))return{kind:"problem",message:"an array or object held twice"};if(!(Array.isArray(i)||he(i)))return{kind:"problem",message:Ee};n.add(i);let c=o.depth+1;if(c>ct)return{kind:"problem",message:`nests more than ${ct} arrays and objects`};let u=Array.isArray(i)?Ir(i,c):ht(i,c);if(u.kind==="problem")return u;_t(o.copy,s,u.copy),r.push(u)}return{kind:"copy",copy:t.copy}},$r=a.z.object({error_code:C,error_msg:g,request_id:g,detail:a.z.unknown(),failed_stage:g.optional()}).strict(),Ie=(e,t)=>{for(let n of t)e.addIssue({...n,path:n.path.slice(e.path.length),fatal:!0})},Ae=$r.transform((e,t)=>{let{detail:n,...r}=e;if(n===void 0)return r;let o={path:[...t.path,"detail"]};if(typeof n=="string"){let i=H.safeParse(n,o);return i.success?{...e,detail:n}:(Ie(t,i.error.issues),a.z.NEVER)}let s=Dr(n);if(s.kind==="problem")return Ie(t,[{code:a.z.ZodIssueCode.custom,path:o.path,message:s.message}]),a.z.NEVER;let d=qt.get(e.error_code);if(d!==void 0){let c=gt[d].safeParse(s.copy,o);if(!c.success)return Ie(t,c.error.issues),a.z.NEVER}return{...e,detail:s.copy}}),Ut=e=>{let t=qt.get(e.error_code);if(t===void 0)return null;let n=gt[t],r=typeof e.detail=="object"?n.parse(e.detail):null;return{name:t,detail:r}},K=h({listConversations:a.z.object({cursor:de.optional(),until:de.optional(),q:it.optional(),pinned:a.z.boolean().optional()}).strict().superRefine((e,t)=>{e.cursor!==void 0&&e.until!==void 0&&A(t)(["until"],"the rows after a cursor or the rows before one, not both")}),listMessages:a.z.object({cursor:de.optional()}).strict(),getMessagePath:a.z.object({cursor:de.optional()}).strict(),searchConversation:a.z.object({q:it}).strict(),exportConversation:a.z.object({format:a.z.enum(y.export_formats)}).strict(),listModels:a.z.object({conversation_uid:p.optional(),declared_level:a.z.enum(y.confidentiality_levels).optional()}).strict().superRefine((e,t)=>{e.conversation_uid!==void 0&&e.declared_level!==void 0&&A(t)(["declared_level"],"a conversation's list or a new conversation's, not both")})}),Ft=(e,t)=>{let r=K[e].parse(t),o=new URLSearchParams;for(let d of Object.keys(m.queries[e])){let i=r[d];i!==void 0&&o.append(d,String(i))}let s=o.toString();return s===""?"":`?${s}`},q=h({listConversations:{status:200,body:null,answer:"conversation_page"},createConversation:{status:201,body:"conversation_request",answer:"conversation_accepted"},getConversation:{status:200,body:null,answer:"conversation"},listMessages:{status:200,body:null,answer:"message_page"},getMessage:{status:200,body:null,answer:"message"},getMessagePath:{status:200,body:null,answer:"message_page"},startRun:{status:202,body:"run_request",answer:"run_accepted"},getRun:{status:200,body:null,answer:"run"},cancelRun:{status:200,body:null,answer:"run"},listModels:{status:200,body:null,answer:"model_list"},getSettings:{status:200,body:null,answer:"settings"},updateSettings:{status:200,body:"user_settings_update",answer:"settings"},getAttachment:{status:200,body:null,answer:"attachment"},updateAttachment:{status:200,body:"attachment_update",answer:"attachment"},deleteAttachment:{status:204,body:null,answer:null},createAttachment:{status:201,body:"attachment_upload",answer:"attachment"}}),Re=h({conversation_page:gr,conversation_request:Tr,conversation_accepted:Sr,conversation:Me,message_page:Ar,message:Ot,run_request:Rr,run_accepted:Nt,run:wr,model_list:Hr,settings:Nr,user_settings_update:xr,attachment:tr,attachment_update:ir,attachment_upload:sr});var Pe=e=>Object.getOwnPropertyDescriptor(Blob.prototype,e).get,Ht=e=>{try{return Reflect.apply(Pe("size"),e,[])}catch{return null}},It=e=>{let t,n;try{t=Reflect.apply(Pe("size"),e,[]),n=Reflect.apply(Pe("type"),e,[])}catch{return null}return Reflect.apply(Blob.prototype.slice,e,[0,t,n])};var V=(e,t,n,r)=>{let o=e.find(s=>s===t);if(o===void 0)throw new RangeError(`${n}: ${r} must be one of ${e.join(", ")}, got ${l(t)}`);return o};var Mr=h({listConversations:[],createConversation:[],getConversation:["conversation_uid"],listMessages:["conversation_uid"],getMessage:["conversation_uid","message_uid"],getMessagePath:["conversation_uid","message_uid"],startRun:["conversation_uid"],getRun:["run_uid"],cancelRun:["run_uid"],listModels:[],getSettings:[],updateSettings:[],getAttachment:["attachment_uid"],updateAttachment:["attachment_uid"],deleteAttachment:["attachment_uid"],createAttachment:[]}),Pr=Object.freeze(Object.keys(q)),Lr=Object.freeze({}),Br=(e,t,n)=>{let r=Mr[e];if(r.length===0){if(t!==void 0)throw new TypeError(`${n}: request.params must be undefined (the path of ${e} names no parameter), got ${l(t)}`);return Lr}x("object",t,n,"request.params");let o=t,s=Object.keys(o).find(i=>!r.includes(i));if(s!==void 0)throw new RangeError(`${n}: request.params must hold only the parameters the path of ${e} names (${r.join(", ")}), got the key ${l(s)}`);let d={};for(let i of r){let c=Object.hasOwn(o,i)?o[i]:void 0;nt(p,c,n,`request.params.${i}`,"a chat uid"),d[i]=c}return Object.freeze(d)},zr=(e,t,n)=>{if(!Object.hasOwn(K,e)){if(t!==void 0)throw new TypeError(`${n}: request.query must be undefined (${e} takes no query), got ${l(t)}`);return null}let r=K[e],o=t===void 0&&r.safeParse({}).success?{}:t;return F(B(r,o,n,"request.query",`the query of ${e}`))},Vr=(e,t,n)=>{let r=q[e].body;if(r===null){if(t!==void 0)throw new TypeError(`${n}: request.body must be undefined (${e} takes no body), got ${l(t)}`);return null}let o=B(Re[r],t,n,"request.body",`the body of ${e} (${r})`);if(r!=="attachment_upload")return F(o);let s=It(o.file);if(s===null)throw new RangeError(`${n}: request.body.file must be a Blob as the browser's Blob reads one, got ${l(o.file)}`);return F({...o,file:s})},Le=e=>{try{return Reflect.apply(Object.getOwnPropertyDescriptor(AbortSignal.prototype,"aborted").get,e,[]),!0}catch{return!1}},jt=(e,t,n)=>{let r=V(Pr,e,n,"endpoint");x("object",t,n,"request");let o=t,{params:s,query:d,body:i,signal:c}=o,u={endpoint:r,params:Br(r,s,n),query:zr(r,d,n),body:Vr(r,i,n)};if(c!==void 0&&!Le(c))throw new TypeError(`${n}: request.signal must be undefined or an AbortSignal, got ${l(c)}`);return Object.freeze({...u,signal:c===void 0?null:c})};var Dt=(e,t)=>{for(let[n,{attributes:r,operations:o,statics:s}]of Object.entries(t)){let d=Reflect.get(globalThis,n);if(typeof d!="function")throw new TypeError(`${e}: the runtime's ${n} must be a function, got ${l(d)}`);let i=d.prototype;if(typeof i!="object"||i===null)throw new TypeError(`${e}: the runtime's ${n}.prototype must be an object, got ${l(i)}`);for(let c of r){let u=Object.getOwnPropertyDescriptor(i,c)?.get;if(typeof u!="function")throw new TypeError(`${e}: the runtime's getter of ${n}.prototype.${c} must be a function, as Web IDL makes an attribute an accessor of its interface's own prototype, got ${l(u)}`)}for(let c of o){let u=Reflect.get(i,c);if(typeof u!="function")throw new TypeError(`${e}: the runtime's ${n}.prototype.${c} must be a function, got ${l(u)}`)}for(let c of s){let u=Reflect.get(d,c);if(typeof u!="function")throw new TypeError(`${e}: the runtime's ${n}.${c} must be a function, got ${l(u)}`)}}};var Te=require("zod");var Gr=Object.freeze({"\n":"%0A","\r":"%0D",'"':"%22"}),$t=e=>e.replace(/[\n\r"]/g,t=>Gr[t]);var Xr=new Set(["GET","HEAD"]),Zr=/^https?:\/\/[^/\\?#]+/i,Yr=Object.freeze(["http://chat-write-target-a.invalid","http://chat-write-target-b.invalid"]),Mt=e=>!Xr.has(e.toUpperCase()),Pt=e=>{let t=Zr.exec(e);return t===null?"":t[0]},Be=e=>{if(!e.startsWith("/"))return!1;try{return Yr.every(t=>new URL(e,t).origin===t)}catch(t){if(t instanceof TypeError)return!1;throw t}},Lt=(e,t,n,r)=>{let o;try{o=e(t)}catch(s){throw new RangeError(`${n}: ${r} must return without throwing, got ${l(s)}`,{cause:s})}if(typeof o!="string")throw new TypeError(`${n}: ${r} must return a string, got ${l(o)}`);if(!Be(o))throw new RangeError(`${n}: ${r} must return a path of the same origin that starts with one "/"`);return o};var Bt="application/json",Ve="multipart/form-data",zt=Object.freeze({body:void 0,filenames:Object.freeze([])}),Wr=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+/,Kr=/[\t ]*;[\t ]*(?:([!#$%&'*+.^_`|~0-9A-Za-z-]+)=([!#$%&'*+.^_`|~0-9A-Za-z-]+|"(?:[\t !#-\x5b\x5d-~\x80-\xff]|\\[\t -~\x80-\xff])*"))?/y,Jr=/^[0-9A-Za-z'()+_,./:=? -]{0,69}[0-9A-Za-z'()+_,./:=?-]$/,Qr=/^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[\t ]*([^\r\n]*?)[\t ]*$/,ea=Object.freeze(["content-disposition","content-type"]),ta=/^form-data/i,na=/[\t ]*;[\t ]*([!#$%&'*+.^_`|~0-9A-Za-z-]+)="([^"]*)"/y,ra=Object.freeze(["name","filename"]),Vt=Object.freeze(Object.keys(m.attachments.upload)),pe=new TextEncoder,ue=pe.encode(`\r
2
+ `),Gt=pe.encode(`\r
3
+ \r
4
+ `),ze=pe.encode("--"),aa=e=>{let t=Wr.exec(e);if(t===null)return null;let n=new RegExp(Kr.source,"y");n.lastIndex=t[0].length;let r=[];for(;n.lastIndex<e.length;){let o=n.exec(e);if(o===null)return null;let[,s,d]=o;if(s!==void 0){let i=d;r.push([s.toLowerCase(),i.startsWith('"')?i.slice(1,-1).replace(/\\([\s\S])/g,"$1"):i])}}return{essence:t[0].toLowerCase(),parameters:r}},oa=e=>{if(e===null||e.essence!==Ve||e.parameters.length!==1)return null;let[t,n]=e.parameters[0];return t==="boundary"&&Jr.test(n)?n:null},sa=async e=>typeof Blob.prototype.arrayBuffer=="function"?new Uint8Array(await Reflect.apply(Blob.prototype.arrayBuffer,e,[])):await new Promise((t,n)=>{let r=new FileReader;r.addEventListener("load",()=>t(new Uint8Array(r.result))),r.addEventListener("error",()=>n(r.error)),r.readAsArrayBuffer(e)}),J=(e,t,n)=>n+t.length<=e.length&&t.every((r,o)=>e[n+o]===r),Xt=(e,t,n)=>{let r=t[0];for(let o=e.indexOf(r,n);o!==-1;o=e.indexOf(r,o+1))if(J(e,t,o))return o;return-1},Zt=e=>new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e),ia=(e,t)=>{if(J(e,ue,0))throw t("with a part without headers");let n=Xt(e,Gt,0);if(n===-1)throw t("with a part without a blank line after its headers");let r;try{r=Zt(e.subarray(0,n))}catch{throw t("with headers that are not UTF-8")}let o=new Map;for(let s of r.split(`\r
5
+ `)){let d=Qr.exec(s);if(d===null)throw t(`with the header line ${l(s)}`);let[,i,c]=d,u=i.toLowerCase();if(!ea.includes(u))throw t(`with the header ${l(i)} in a part`);if(o.has(u))throw t(`with the header ${l(i)} twice in a part`);o.set(u,c)}return{headers:o,content:e.subarray(n+Gt.length)}},da=(e,t,n)=>{let r=pe.encode(`--${t}\r
6
+ `);if(!J(e,r,0))throw n("that does not begin with the delimiter of its boundary and CRLF");let o=pe.encode(`\r
7
+ --${t}`),s=[],d=r.length;for(;;){let i=Xt(e,o,d);if(i===-1)throw n("whose part is not closed by a delimiter");s.push(ia(e.subarray(d,i),n));let c=i+o.length;if(J(e,ue,c)){d=c+ue.length;continue}if(!J(e,ze,c))throw n('whose delimiter is followed by neither CRLF nor "--"');if(e.length!==c+ze.length+ue.length||!J(e,ue,c+ze.length))throw n("that does not end with CRLF right after its close delimiter");return s}},ca=e=>{if(!ta.test(e))return null;let t=new RegExp(na.source,"y");t.lastIndex=9;let n=new Map;for(;t.lastIndex<e.length;){let o=t.exec(e);if(o===null)return null;let[,s,d]=o,i=s.toLowerCase();if(!ra.includes(i)||n.has(i))return null;n.set(i,d)}let r=n.get("name");return r===void 0?null:{name:r,filename:n.get("filename")??null}},la=(e,t)=>{let n={},r=[],o=-1;for(let s of e){let d=s.headers.get("content-disposition");if(d===void 0)throw t("with a part without a Content-Disposition");let i=ca(d);if(i===null)throw t(`with the Content-Disposition ${l(d)}`);let c=Vt.indexOf(i.name);if(c===-1)throw t(`with a part named ${l(i.name)}`);if(c<=o)throw t(c===o?`with the part ${l(i.name)} twice`:`with the part ${l(i.name)} after the part ${l(Vt[o])}`);o=c;let u=s.headers.get("content-type");if(i.filename===null){if(u!==void 0)throw t(`with the text part ${l(i.name)} holding a Content-Type`);try{n[i.name]=Zt(s.content)}catch{throw t(`with the text part ${l(i.name)} that is not UTF-8`)}}else{if(u===void 0)throw t(`with the file part ${l(i.name)} without a Content-Type`);n[i.name]=new Blob([s.content],{type:u}),r.push(i.filename)}}return{body:n,filenames:r}},Yt=async(e,t,n,r)=>{if(q[e].body===null){if(n!=null)throw new TypeError(`${r}: init.body must be undefined or null (${e} takes no body), got ${l(n)}`);if(t!==null)throw new RangeError(`${r}: init.headers must hold no Content-Type (${e} takes no body), got ${l(t)}`);return zt}let o=t===null?null:aa(t);if(!Object.hasOwn(m.paths.upload,e)){if(o?.essence!==Bt)throw new RangeError(`${r}: the Content-Type of init.headers must declare ${Bt} (${e} takes a JSON body), got ${l(t)}`);if(typeof n!="string")throw new TypeError(`${r}: init.body must be a JSON text (${e} takes a JSON body), got ${l(n)}`);try{return{body:JSON.parse(n),filenames:zt.filenames}}catch{throw new RangeError(`${r}: init.body must be a JSON text (${e} takes a JSON body), got a text that is not JSON`)}}let s=oa(o);if(s===null)throw new RangeError(`${r}: the Content-Type of init.headers must declare ${Ve} with one boundary of RFC 2046 and no other parameter (${e} takes a multipart body), got ${l(t)}`);if(Ht(n)===null)throw new TypeError(`${r}: init.body must be a Blob (${e} takes a multipart body), got ${l(n)}`);let d=i=>new RangeError(`${r}: init.body must be a ${Ve} body of the upload's fields (RFC 7578), got a body ${i}`);return la(da(await sa(n),s,d),d)};var ua=Object.freeze(Object.keys(q).map(e=>{let t=Object.hasOwn(m.paths.upload,e),{method:n,path:r}=t?m.paths.upload[e]:m.paths.json[e];return Object.freeze({endpoint:e,upload:t,method:n,segments:Object.freeze(`${m.paths.base}${r}`.split("/"))})})),pa=/^\{([a-z_]+)\}$/,Wt=e=>e instanceof Te.z.ZodEffects?Wt(e.innerType()):e.shape,ha=new Map(Object.entries(K).map(([e,t])=>[e,Object.freeze(Object.entries(Wt(t)).filter(([,n])=>(n instanceof Te.z.ZodOptional?n.unwrap():n)instanceof Te.z.ZodBoolean).map(([n])=>n))])),Kt=(e,t)=>{x("object",e,t,"init");let{method:n,headers:r,body:o,signal:s}=e;return Object.freeze({method:n,headers:r,body:o,signal:s})},_a=(e,t,n)=>{for(let r of ua){let o=r.upload?n.uploadBaseUrl:n.jsonBaseUrl;if(r.method!==e||!t.startsWith(o))continue;let s=t.slice(o.length),d=s.indexOf("?"),i=d===-1?s:s.slice(0,d),c=i.split("/");if(c.length!==r.segments.length)continue;let u={};if(r.segments.every((I,G)=>{let j=c[G],te=pa.exec(I);return te===null?j===I:(u[te[1]]=j,j!=="")}))return{route:r,written:u,path:i,search:d===-1?"":s.slice(d)}}return null},ma=(e,t,n,r)=>{let o=[n.jsonBaseUrl,n.uploadBaseUrl].filter(d=>t.startsWith(d)).sort((d,i)=>i.length-d.length)[0],s=o===void 0?"a URL under neither base":`the URL ${l(t.slice(o.length))} after a base`;return new RangeError(`${r}: url and init.method must name an endpoint of the exchanges' table under the base of its channel, got ${l(e)} and ${s}`)},ga=(e,t,n,r)=>{let o=()=>new RangeError(`${r}: url must hold the path of ${e.endpoint} as the contract writes it, each parameter one segment encoded by encodeURIComponent, got the path ${l(n)}`),s={};for(let[i,c]of Object.entries(t))try{s[i]=decodeURIComponent(c)}catch{throw o()}if((e.upload?bt(e.endpoint,s).path:Et(e.endpoint,s).path)!==n)throw o();return s},fa=(e,t,n)=>{let r=ha.get(e);if(r===void 0){if(t!=="")throw new RangeError(`${n}: url must hold no query (${e} takes no query), got the query ${l(t)}`);return}let o=new Map;for(let[s,d]of new URLSearchParams(t.slice(1))){if(o.has(s))throw new RangeError(`${n}: url must hold each field of the query of ${e} once, got the field ${l(s)} twice`);o.set(s,r.includes(s)&&(d==="true"||d==="false")?d==="true":d)}return Object.fromEntries(o)},ya=(e,t,n,r)=>{if(!Mt(e))return t;let o=Pt(t),s=t.slice(o.length);return Be(s)?`${o}${Lt(n,s,r,"unstampWrite")}`:t},Jt=async(e,t,n,r,o)=>{x("string",e,o,"url");let s=t.method===void 0?"GET":t.method;if(typeof s!="string")throw new TypeError(`${o}: init.method must be undefined or a string, got ${l(s)}`);let d=ya(s,e,r,o),i=_a(s,d,n);if(i===null)throw ma(s,d,n,o);let{route:c,search:u}=i,R=ga(c,i.written,i.path,o),I;try{I=new Headers(t.headers)}catch(re){throw new TypeError(`${o}: init.headers must be headers the browser's Headers reads, got ${l(t.headers)}`,{cause:re})}let G=fa(c.endpoint,u,o),{body:j,filenames:te}=await Yt(c.endpoint,I.get("content-type"),t.body,o),ne=jt(c.endpoint,{params:Object.keys(R).length===0?void 0:R,query:G,body:j,signal:t.signal===null?void 0:t.signal},o);if(ne.query!==null&&Ft(c.endpoint,ne.query)!==u)throw new RangeError(`${o}: url must hold the query of ${c.endpoint} as chatQueryString writes it of the query its schema read, got the query ${l(u)}`);if(c.upload){let re=te[0],we=$t(ne.body.file_name);if(re!==we)throw new RangeError(`${o}: init.body must carry the filename of its file part as the transport writes it of file_name (${l(we)}), got ${l(re)}`)}return ne};var Q="createChatScenarioFetch",ee="ChatScenarioFetch.fetch",Ge="ChatScenarioFetch.plan",Ea="ChatScenarioFetch.hold",Qt="ChatScenarioHold.settle",ba="ChatScenarioFetch.assertDone",Se="chatScenarioRefusal",en=Object.freeze(Object.keys(q)),Ca=Object.freeze(Object.keys(m.business_codes)),on=h({answered:["kind","answer"],refused:["kind","status","body"],unreached:["kind"],response:["kind","response"]}),Aa=Object.freeze(Object.keys(on)),Xe=Object.freeze(Object.keys(Ae.innerType().shape).filter(e=>e!=="error_code")),Ra="application/json",tn=65536,Ta=1,nn=400,rn=599,Sa=F({Blob:{attributes:["size","type"],operations:["slice"],statics:[]},AbortSignal:{attributes:["aborted","reason"],operations:["addEventListener","removeEventListener"],statics:["any"]}}),wa=Object.freeze({kind:"unreached"}),xa=Object.freeze({waiting:"has taken no request",answering:"awaits the answer its response function makes",settled:"has answered its request",stopped:"was stopped"}),sn=e=>Object.getOwnPropertyDescriptor(AbortSignal.prototype,e).get,Ye=e=>Reflect.apply(sn("aborted"),e,[])===!0,We=e=>Reflect.apply(sn("reason"),e,[]),an=e=>{let t=Function.prototype.bind(void 0);return Reflect.apply(AbortSignal.prototype.addEventListener,e,["abort",t]),Reflect.apply(AbortSignal.prototype.removeEventListener,e,["abort",t]),e},Oa=e=>{let t=an(AbortSignal.any([an(e)]));if(Ye(t))throw new TypeError("the runtime's AbortSignal.any made an aborted signal from a signal that is not aborted");return t},dn=e=>typeof e=="object"&&e!==null||typeof e=="function",cn=(e,t)=>{let n=!1,r=s=>{n||(n=!0,t.rejected(s))},o=s=>{if(n)return;n=!0;let d;try{d=dn(s)?Reflect.get(s,"then"):void 0}catch(c){t.rejected(c);return}if(typeof d!="function"){t.fulfilled(s);return}let i=d;Promise.resolve().then(()=>cn((c,u)=>Reflect.apply(i,s,[c,u]),t))};try{e(o,r)}catch(s){r(s)}},ln=(e,t,n)=>{let r=s=>new RangeError(`${t}: ${n} must be a value JSON.stringify writes as a JSON text, got ${l(e)}`,s===void 0?void 0:{cause:s}),o;try{o=JSON.stringify(e)}catch(s){throw r(s)}if(o===void 0)throw r();return o},va=(e,t,n,r)=>{let o=q[e];if(o.answer===null){if(t!==null)throw new TypeError(`${n}: ${r} must be null (${e} answers no body), got ${l(t)}`);return Object.freeze({kind:"json",status:o.status,text:null})}let s=ln(t,n,r);return B(Re[o.answer],JSON.parse(s),n,r,`the answer of ${e} (${o.answer}) when written as a JSON text and read back`),Object.freeze({kind:"json",status:o.status,text:s})},Na=(e,t,n,r)=>{let o=Je(e,n,`${r}.status`,`an integer from ${nn} to ${rn}`,i=>Number.isInteger(i)&&i>=nn&&i<=rn),s=ln(t,n,`${r}.body`),d=Ut(B(Ae,JSON.parse(s),n,`${r}.body`,"a failed answer's body when written as a JSON text and read back"));if(d!==null){let i=m.business_codes[d.name].http_status;if(o!==i)throw new RangeError(`${n}: ${r}.status must be ${i}, the status of the business code ${d.name} its body carries, got ${o}`)}return Object.freeze({kind:"json",status:o,text:s})},Ze=(e,t,n,r)=>{x("object",t,n,r);let o=t,s=V(Aa,o.kind,n,`${r}.kind`),d=on[s],i=Object.keys(o).find(c=>!d.includes(c));if(i!==void 0)throw new RangeError(`${n}: ${r} must hold only the fields of a reply of the kind ${s} (${d.join(", ")}), got the key ${l(i)}`);switch(s){case"answered":return va(e,o.answer,n,`${r}.answer`);case"refused":{let{status:c,body:u}=o;return Na(c,u,n,r)}case"unreached":return wa;case"response":{let{response:c}=o;return x("function",c,n,`${r}.response`),Object.freeze({kind:"response",make:c})}}},ka=e=>{let t=new TextEncoder().encode(e),n=()=>{},r;return{stream:new ReadableStream({type:"bytes",start:d=>{r=d;for(let i=0;i<t.byteLength;i+=tn)d.enqueue(t.slice(i,i+tn))},pull:d=>{n(),d.close(),d.byobRequest?.respond(0)},cancel:()=>{n()}},{highWaterMark:Ta}),tie:d=>{let i=()=>{n(),r.error(We(d))};n=()=>Reflect.apply(AbortSignal.prototype.removeEventListener,d,["abort",i]),Reflect.apply(AbortSignal.prototype.addEventListener,d,["abort",i])}}},qa=e=>{if(e.text===null)return{response:new Response(null,{status:e.status}),tie:null};let t=ka(e.text);return{response:new Response(t.stream,{status:e.status,headers:{"Content-Type":Ra}}),tie:t.tie}},Ua=e=>{let t=Reflect.get(Blob.prototype,"arrayBuffer"),n=Reflect.get(globalThis,"FileReader");if(typeof t!="function"&&typeof n!="function")throw new TypeError(`${e}: the runtime's Blob.prototype.arrayBuffer or its FileReader must be a function, as an upload's file is read by one of them, got ${l(t)} and ${l(n)}`)},Fa=e=>e instanceof Error?`${e.name}: ${e.message}`:l(e),Ha=(e,t)=>{let n=V(Ca,e,Se,"name");x("object",t,Se,"fields");let r=t,o=Object.keys(r).find(R=>!Xe.includes(R));if(o!==void 0)throw new RangeError(`${Se}: fields must hold only the fields of a failed answer's body besides error_code (${Xe.join(", ")}), got the key ${l(o)}`);let{number:s,http_status:d}=m.business_codes[n],i=[["error_code",s],...Xe.map(R=>[R,r[R]])],c=Object.fromEntries(i.filter(([,R])=>R!==void 0)),u=B(Ae,c,Se,"fields",`the fields of a failed answer's body of ${n}`);return F({kind:"refused",status:d,body:u})},Ia=e=>{x("object",e,Q,"options");let{jsonBaseUrl:t,uploadBaseUrl:n,unstampWrite:r}=e;ve(t,Q,"jsonBaseUrl"),ve(n,Q,"uploadBaseUrl"),x("function",r,Q,"unstampWrite"),Dt(Q,Sa),Ua(Q);let o=Object.freeze({jsonBaseUrl:t,uploadBaseUrl:n}),s=new Map,d=[],i=[],c=[],u=new Set,R=new Set,I=Promise.resolve(),G=()=>{for(let O of R)O()},j=O=>{let E=s.get(O);if(E!==void 0)return E;let S=[];return s.set(O,S),S};return Object.freeze({fetch:(O,E)=>{let S;try{S=Kt(E,ee)}catch(w){return c.push(w),Promise.reject(w)}let v=Le(S.signal)?S.signal:null;if(v!==null&&Ye(v))return Promise.reject(We(v));let T=null;if(v!==null)try{T=Oa(v)}catch(w){let P=new TypeError(`${ee}: init.signal must be a signal the runtime's AbortSignal.any can make the request's own signal from, got ${l(v)}`,{cause:w});return c.push(P),Promise.reject(P)}return new Promise((w,P)=>{let k=!1,D=null,ae={};u.add(ae);let X=b=>{k||(k=!0,u.delete(ae),D!==null&&D.phase.kind==="answering"&&(D.phase={kind:"settled"}),T!==null&&(R.delete(U),Reflect.apply(AbortSignal.prototype.removeEventListener,T,["abort",xe])),b())},oe=b=>{U(),c.push(b),X(()=>P(b))},xe=()=>{D!==null&&(D.phase={kind:"stopped"}),X(()=>P(We(v)))},U=()=>(!k&&v!==null&&Ye(v)&&xe(),k),un=b=>{let f;try{f=qa(b)}catch(se){oe(se);return}X(()=>{T!==null&&f.tie!==null&&f.tie(T),w(f.response)})},pn=b=>{let f,se;try{f=Reflect.apply(b,void 0,[]),se=dn(f)?Reflect.get(f,"then"):void 0}catch(L){oe(L);return}if(typeof se!="function"){X(()=>w(f));return}let _n=se;cn((L,mn)=>Reflect.apply(_n,f,[L,mn]),{fulfilled:L=>{U(),X(()=>w(L))},rejected:L=>{U()||oe(L)}})},Ke=b=>{if(!U())switch(b.kind){case"unreached":X(()=>P(new TypeError(`${ee}: the request was not reached, as its step planned`)));return;case"json":un(b);return;case"response":pn(b.make)}},hn=b=>{let f=s.get(b.endpoint)?.shift();if(f===void 0)throw new RangeError(`${ee}: a request of ${b.endpoint} must find a step the scenario planned for it, got one when none is left`);if(i.push(b),f.kind==="hold"){D=f.state,u.delete(ae),f.state.phase={kind:"arrived",answer:Ke},f.state.arrive(b);return}Ke(f.kind==="reply"?f.reply:Ze(b.endpoint,Reflect.apply(f.step,void 0,[b]),ee,f.field))};T!==null&&(R.add(U),Reflect.apply(AbortSignal.prototype.addEventListener,T,["abort",xe])),I=I.then(async()=>{if(U())return;let b;try{b=await Jt(O,S,o,r,ee)}catch(f){U()||oe(f);return}if(!U())try{hn(b)}catch(f){oe(f)}})})},plan:(O,...E)=>{let S=V(en,O,Ge,"endpoint");if(E.length===0)throw new RangeError(`${Ge}: steps must be one step or more, got none`);let v=E.map((T,w)=>Object.freeze(typeof T=="function"?{kind:"function",step:T,field:`steps[${w}](request)`}:{kind:"reply",reply:Ze(S,T,Ge,`steps[${w}]`)}));j(S).push(...v)},hold:O=>{let E=V(en,O,Ea,"endpoint"),S,v=new Promise(k=>{S=k}),T={endpoint:E,phase:{kind:"waiting"},arrive:S};d.push(T),j(E).push(Object.freeze({kind:"hold",state:T}));let w=()=>{G();let{phase:k}=T;if(k.kind!=="arrived")throw new TypeError(`${Qt}: the held step of ${E} must hold a request it has neither answered nor stopped, got a step that ${xa[k.kind]}`);return k};return Object.freeze({arrived:v,settle:k=>{w();let D=Ze(E,k,Qt,"reply"),ae=w();T.phase={kind:"answering"},ae.answer(D)}})},requests:()=>Object.freeze([...i]),assertDone:()=>{G();let O=[...u.size>0?[`requests still being read: ${u.size}`]:[],...c.map(E=>`the breach ${Fa(E)}`),...[...s].filter(([,E])=>E.length>0).map(([E,S])=>`untaken steps of ${E}: ${S.length}`),...d.filter(E=>E.phase.kind==="arrived"||E.phase.kind==="answering").map(E=>`the held request of ${E.endpoint} neither answered nor stopped`)];if(O.length>0)throw new Error(`${ba}: the scenario must end with every request read, no breach, every step taken, and every held request answered or stopped, got ${O.join("; ")}`)}})};0&&(module.exports={chatScenarioRefusal,createChatScenarioFetch});
@@ -0,0 +1,50 @@
1
+ import { z } from "zod";
2
+ import { C as ChatFetch } from "./httpTransport-D_JJABMq.cjs";
3
+ import { d as ChatSingleEndpoint, b as ChatExchangeParams } from "./transport-5ExGY_ti.cjs";
4
+ import { R as ChatExchangeEndpointName, S as ChatExchangeShapeName, az as chatExchangeShapeSchemas, j as CHAT_EXCHANGES, ax as chatErrorBodySchema, $ as ChatQueryName, aR as chatQuerySchemas, B as ChatBusinessCodeName } from "./index-iHWm67aF.cjs";
5
+ type ShapeInput<Name> = Name extends ChatExchangeShapeName ? z.input<(typeof chatExchangeShapeSchemas)[Name]> : null;
6
+ type ShapeOutput<Name> = Name extends ChatExchangeShapeName ? z.output<(typeof chatExchangeShapeSchemas)[Name]> : null;
7
+ type ChatScenarioAnswer<Endpoint extends ChatExchangeEndpointName> = ShapeInput<(typeof CHAT_EXCHANGES)[Endpoint]["answer"]>;
8
+ type ChatScenarioRefusedReply = {
9
+ readonly kind: "refused";
10
+ readonly status: number;
11
+ readonly body: z.input<typeof chatErrorBodySchema>;
12
+ };
13
+ type ChatScenarioReply<Endpoint extends ChatExchangeEndpointName> = {
14
+ readonly kind: "answered";
15
+ readonly answer: ChatScenarioAnswer<Endpoint>;
16
+ } | ChatScenarioRefusedReply | {
17
+ readonly kind: "unreached";
18
+ } | {
19
+ readonly kind: "response";
20
+ readonly response: () => unknown;
21
+ };
22
+ type ChatScenarioRequest<Endpoint extends ChatExchangeEndpointName = ChatExchangeEndpointName> = Endpoint extends unknown ? {
23
+ readonly endpoint: Endpoint;
24
+ readonly params: ChatExchangeParams<Endpoint>;
25
+ readonly query: Endpoint extends ChatQueryName ? z.output<(typeof chatQuerySchemas)[Endpoint]> : null;
26
+ readonly body: ShapeOutput<(typeof CHAT_EXCHANGES)[Endpoint]["body"]>;
27
+ readonly signal: AbortSignal | null;
28
+ } : never;
29
+ type ChatScenarioStep<Endpoint extends ChatExchangeEndpointName> = ChatScenarioReply<Endpoint> | ((request: ChatScenarioRequest<Endpoint>) => ChatScenarioReply<Endpoint>);
30
+ type ChatScenarioHold<Endpoint extends ChatExchangeEndpointName> = {
31
+ readonly arrived: Promise<ChatScenarioRequest<Endpoint>>;
32
+ readonly settle: (reply: ChatScenarioReply<Endpoint>) => void;
33
+ };
34
+ type ChatUnstampWrite = (target: string) => string;
35
+ type ChatScenarioFetchOptions = {
36
+ readonly jsonBaseUrl: string;
37
+ readonly uploadBaseUrl: string;
38
+ readonly unstampWrite: ChatUnstampWrite;
39
+ };
40
+ type ChatScenarioFetch = {
41
+ readonly fetch: ChatFetch;
42
+ readonly plan: <Endpoint extends ChatExchangeEndpointName>(endpoint: ChatSingleEndpoint<Endpoint>, ...steps: readonly ChatScenarioStep<Endpoint>[]) => void;
43
+ readonly hold: <Endpoint extends ChatExchangeEndpointName>(endpoint: ChatSingleEndpoint<Endpoint>) => ChatScenarioHold<Endpoint>;
44
+ readonly requests: () => readonly ChatScenarioRequest[];
45
+ readonly assertDone: () => void;
46
+ };
47
+ type ChatScenarioRefusalFields = Omit<z.input<typeof chatErrorBodySchema>, "error_code">;
48
+ declare const chatScenarioRefusal: (name: ChatBusinessCodeName, fields: ChatScenarioRefusalFields) => ChatScenarioRefusedReply;
49
+ declare const createChatScenarioFetch: (options: ChatScenarioFetchOptions) => ChatScenarioFetch;
50
+ export { type ChatScenarioAnswer, type ChatScenarioFetch, type ChatScenarioFetchOptions, type ChatScenarioHold, type ChatScenarioRefusalFields, type ChatScenarioRefusedReply, type ChatScenarioReply, type ChatScenarioRequest, type ChatScenarioStep, type ChatUnstampWrite, chatScenarioRefusal, createChatScenarioFetch };
@@ -0,0 +1,50 @@
1
+ import { z } from "zod";
2
+ import { C as ChatFetch } from "./httpTransport-BAaKwioS.js";
3
+ import { d as ChatSingleEndpoint, b as ChatExchangeParams } from "./transport-Clvkp7mW.js";
4
+ import { R as ChatExchangeEndpointName, S as ChatExchangeShapeName, az as chatExchangeShapeSchemas, j as CHAT_EXCHANGES, ax as chatErrorBodySchema, $ as ChatQueryName, aR as chatQuerySchemas, B as ChatBusinessCodeName } from "./index-iHWm67aF.js";
5
+ type ShapeInput<Name> = Name extends ChatExchangeShapeName ? z.input<(typeof chatExchangeShapeSchemas)[Name]> : null;
6
+ type ShapeOutput<Name> = Name extends ChatExchangeShapeName ? z.output<(typeof chatExchangeShapeSchemas)[Name]> : null;
7
+ type ChatScenarioAnswer<Endpoint extends ChatExchangeEndpointName> = ShapeInput<(typeof CHAT_EXCHANGES)[Endpoint]["answer"]>;
8
+ type ChatScenarioRefusedReply = {
9
+ readonly kind: "refused";
10
+ readonly status: number;
11
+ readonly body: z.input<typeof chatErrorBodySchema>;
12
+ };
13
+ type ChatScenarioReply<Endpoint extends ChatExchangeEndpointName> = {
14
+ readonly kind: "answered";
15
+ readonly answer: ChatScenarioAnswer<Endpoint>;
16
+ } | ChatScenarioRefusedReply | {
17
+ readonly kind: "unreached";
18
+ } | {
19
+ readonly kind: "response";
20
+ readonly response: () => unknown;
21
+ };
22
+ type ChatScenarioRequest<Endpoint extends ChatExchangeEndpointName = ChatExchangeEndpointName> = Endpoint extends unknown ? {
23
+ readonly endpoint: Endpoint;
24
+ readonly params: ChatExchangeParams<Endpoint>;
25
+ readonly query: Endpoint extends ChatQueryName ? z.output<(typeof chatQuerySchemas)[Endpoint]> : null;
26
+ readonly body: ShapeOutput<(typeof CHAT_EXCHANGES)[Endpoint]["body"]>;
27
+ readonly signal: AbortSignal | null;
28
+ } : never;
29
+ type ChatScenarioStep<Endpoint extends ChatExchangeEndpointName> = ChatScenarioReply<Endpoint> | ((request: ChatScenarioRequest<Endpoint>) => ChatScenarioReply<Endpoint>);
30
+ type ChatScenarioHold<Endpoint extends ChatExchangeEndpointName> = {
31
+ readonly arrived: Promise<ChatScenarioRequest<Endpoint>>;
32
+ readonly settle: (reply: ChatScenarioReply<Endpoint>) => void;
33
+ };
34
+ type ChatUnstampWrite = (target: string) => string;
35
+ type ChatScenarioFetchOptions = {
36
+ readonly jsonBaseUrl: string;
37
+ readonly uploadBaseUrl: string;
38
+ readonly unstampWrite: ChatUnstampWrite;
39
+ };
40
+ type ChatScenarioFetch = {
41
+ readonly fetch: ChatFetch;
42
+ readonly plan: <Endpoint extends ChatExchangeEndpointName>(endpoint: ChatSingleEndpoint<Endpoint>, ...steps: readonly ChatScenarioStep<Endpoint>[]) => void;
43
+ readonly hold: <Endpoint extends ChatExchangeEndpointName>(endpoint: ChatSingleEndpoint<Endpoint>) => ChatScenarioHold<Endpoint>;
44
+ readonly requests: () => readonly ChatScenarioRequest[];
45
+ readonly assertDone: () => void;
46
+ };
47
+ type ChatScenarioRefusalFields = Omit<z.input<typeof chatErrorBodySchema>, "error_code">;
48
+ declare const chatScenarioRefusal: (name: ChatBusinessCodeName, fields: ChatScenarioRefusalFields) => ChatScenarioRefusedReply;
49
+ declare const createChatScenarioFetch: (options: ChatScenarioFetchOptions) => ChatScenarioFetch;
50
+ export { type ChatScenarioAnswer, type ChatScenarioFetch, type ChatScenarioFetchOptions, type ChatScenarioHold, type ChatScenarioRefusalFields, type ChatScenarioRefusedReply, type ChatScenarioReply, type ChatScenarioRequest, type ChatScenarioStep, type ChatUnstampWrite, chatScenarioRefusal, createChatScenarioFetch };
@@ -0,0 +1,7 @@
1
+ import{a as ye,b as ge,c as me,d as we,e as Ee,f as be,g as Re,h as Se}from"./chunk-WGNEBS4H.js";import{a as C,c as pe,d as G,f as J,h as fe}from"./chunk-7KWWXSGA.js";import{a as c,c as M}from"./chunk-PLNRET3Z.js";import{K as ie,L as de,Na as D,Oa as ce,Pa as le,Qa as he,Ra as N,Sa as ue,a as se,b as Z,f as R}from"./chunk-4NR4KSV6.js";import{z as V}from"zod";var Ce="application/json",K="multipart/form-data",Oe=Object.freeze({body:void 0,filenames:Object.freeze([])}),Ze=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+/,Ge=/[\t ]*;[\t ]*(?:([!#$%&'*+.^_`|~0-9A-Za-z-]+)=([!#$%&'*+.^_`|~0-9A-Za-z-]+|"(?:[\t !#-\x5b\x5d-~\x80-\xff]|\\[\t -~\x80-\xff])*"))?/y,Xe=/^[0-9A-Za-z'()+_,./:=? -]{0,69}[0-9A-Za-z'()+_,./:=?-]$/,Ke=/^([!#$%&'*+.^_`|~0-9A-Za-z-]+):[\t ]*([^\r\n]*?)[\t ]*$/,Ve=Object.freeze(["content-disposition","content-type"]),et=/^form-data/i,tt=/[\t ]*;[\t ]*([!#$%&'*+.^_`|~0-9A-Za-z-]+)="([^"]*)"/y,nt=Object.freeze(["name","filename"]),ke=Object.freeze(Object.keys(R.attachments.upload)),H=new TextEncoder,F=H.encode(`\r
2
+ `),$e=H.encode(`\r
3
+ \r
4
+ `),X=H.encode("--"),rt=e=>{let t=Ze.exec(e);if(t===null)return null;let n=new RegExp(Ge.source,"y");n.lastIndex=t[0].length;let r=[];for(;n.lastIndex<e.length;){let o=n.exec(e);if(o===null)return null;let[,a,i]=o;if(a!==void 0){let s=i;r.push([a.toLowerCase(),s.startsWith('"')?s.slice(1,-1).replace(/\\([\s\S])/g,"$1"):s])}}return{essence:t[0].toLowerCase(),parameters:r}},ot=e=>{if(e===null||e.essence!==K||e.parameters.length!==1)return null;let[t,n]=e.parameters[0];return t==="boundary"&&Xe.test(n)?n:null},at=async e=>typeof Blob.prototype.arrayBuffer=="function"?new Uint8Array(await Reflect.apply(Blob.prototype.arrayBuffer,e,[])):await new Promise((t,n)=>{let r=new FileReader;r.addEventListener("load",()=>t(new Uint8Array(r.result))),r.addEventListener("error",()=>n(r.error)),r.readAsArrayBuffer(e)}),_=(e,t,n)=>n+t.length<=e.length&&t.every((r,o)=>e[n+o]===r),xe=(e,t,n)=>{let r=t[0];for(let o=e.indexOf(r,n);o!==-1;o=e.indexOf(r,o+1))if(_(e,t,o))return o;return-1},Ae=e=>new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0}).decode(e),st=(e,t)=>{if(_(e,F,0))throw t("with a part without headers");let n=xe(e,$e,0);if(n===-1)throw t("with a part without a blank line after its headers");let r;try{r=Ae(e.subarray(0,n))}catch{throw t("with headers that are not UTF-8")}let o=new Map;for(let a of r.split(`\r
5
+ `)){let i=Ke.exec(a);if(i===null)throw t(`with the header line ${c(a)}`);let[,s,d]=i,l=s.toLowerCase();if(!Ve.includes(l))throw t(`with the header ${c(s)} in a part`);if(o.has(l))throw t(`with the header ${c(s)} twice in a part`);o.set(l,d)}return{headers:o,content:e.subarray(n+$e.length)}},it=(e,t,n)=>{let r=H.encode(`--${t}\r
6
+ `);if(!_(e,r,0))throw n("that does not begin with the delimiter of its boundary and CRLF");let o=H.encode(`\r
7
+ --${t}`),a=[],i=r.length;for(;;){let s=xe(e,o,i);if(s===-1)throw n("whose part is not closed by a delimiter");a.push(st(e.subarray(i,s),n));let d=s+o.length;if(_(e,F,d)){i=d+F.length;continue}if(!_(e,X,d))throw n('whose delimiter is followed by neither CRLF nor "--"');if(e.length!==d+X.length+F.length||!_(e,F,d+X.length))throw n("that does not end with CRLF right after its close delimiter");return a}},dt=e=>{if(!et.test(e))return null;let t=new RegExp(tt.source,"y");t.lastIndex=9;let n=new Map;for(;t.lastIndex<e.length;){let o=t.exec(e);if(o===null)return null;let[,a,i]=o,s=a.toLowerCase();if(!nt.includes(s)||n.has(s))return null;n.set(s,i)}let r=n.get("name");return r===void 0?null:{name:r,filename:n.get("filename")??null}},ct=(e,t)=>{let n={},r=[],o=-1;for(let a of e){let i=a.headers.get("content-disposition");if(i===void 0)throw t("with a part without a Content-Disposition");let s=dt(i);if(s===null)throw t(`with the Content-Disposition ${c(i)}`);let d=ke.indexOf(s.name);if(d===-1)throw t(`with a part named ${c(s.name)}`);if(d<=o)throw t(d===o?`with the part ${c(s.name)} twice`:`with the part ${c(s.name)} after the part ${c(ke[o])}`);o=d;let l=a.headers.get("content-type");if(s.filename===null){if(l!==void 0)throw t(`with the text part ${c(s.name)} holding a Content-Type`);try{n[s.name]=Ae(a.content)}catch{throw t(`with the text part ${c(s.name)} that is not UTF-8`)}}else{if(l===void 0)throw t(`with the file part ${c(s.name)} without a Content-Type`);n[s.name]=new Blob([a.content],{type:l}),r.push(s.filename)}}return{body:n,filenames:r}},Ne=async(e,t,n,r)=>{if(N[e].body===null){if(n!=null)throw new TypeError(`${r}: init.body must be undefined or null (${e} takes no body), got ${c(n)}`);if(t!==null)throw new RangeError(`${r}: init.headers must hold no Content-Type (${e} takes no body), got ${c(t)}`);return Oe}let o=t===null?null:rt(t);if(!Object.hasOwn(R.paths.upload,e)){if(o?.essence!==Ce)throw new RangeError(`${r}: the Content-Type of init.headers must declare ${Ce} (${e} takes a JSON body), got ${c(t)}`);if(typeof n!="string")throw new TypeError(`${r}: init.body must be a JSON text (${e} takes a JSON body), got ${c(n)}`);try{return{body:JSON.parse(n),filenames:Oe.filenames}}catch{throw new RangeError(`${r}: init.body must be a JSON text (${e} takes a JSON body), got a text that is not JSON`)}}let a=ot(o);if(a===null)throw new RangeError(`${r}: the Content-Type of init.headers must declare ${K} with one boundary of RFC 2046 and no other parameter (${e} takes a multipart body), got ${c(t)}`);if(fe(n)===null)throw new TypeError(`${r}: init.body must be a Blob (${e} takes a multipart body), got ${c(n)}`);let i=s=>new RangeError(`${r}: init.body must be a ${K} body of the upload's fields (RFC 7578), got a body ${s}`);return ct(it(await at(n),a,i),i)};var lt=Object.freeze(Object.keys(N).map(e=>{let t=Object.hasOwn(R.paths.upload,e),{method:n,path:r}=t?R.paths.upload[e]:R.paths.json[e];return Object.freeze({endpoint:e,upload:t,method:n,segments:Object.freeze(`${R.paths.base}${r}`.split("/"))})})),ht=/^\{([a-z_]+)\}$/,je=e=>e instanceof V.ZodEffects?je(e.innerType()):e.shape,ut=new Map(Object.entries(le).map(([e,t])=>[e,Object.freeze(Object.entries(je(t)).filter(([,n])=>(n instanceof V.ZodOptional?n.unwrap():n)instanceof V.ZodBoolean).map(([n])=>n))])),Te=(e,t)=>{C("object",e,t,"init");let{method:n,headers:r,body:o,signal:a}=e;return Object.freeze({method:n,headers:r,body:o,signal:a})},pt=(e,t,n)=>{for(let r of lt){let o=r.upload?n.uploadBaseUrl:n.jsonBaseUrl;if(r.method!==e||!t.startsWith(o))continue;let a=t.slice(o.length),i=a.indexOf("?"),s=i===-1?a:a.slice(0,i),d=s.split("/");if(d.length!==r.segments.length)continue;let l={};if(r.segments.every((O,j)=>{let k=d[j],P=ht.exec(O);return P===null?k===O:(l[P[1]]=k,k!=="")}))return{route:r,written:l,path:s,search:i===-1?"":a.slice(i)}}return null},ft=(e,t,n,r)=>{let o=[n.jsonBaseUrl,n.uploadBaseUrl].filter(i=>t.startsWith(i)).sort((i,s)=>s.length-i.length)[0],a=o===void 0?"a URL under neither base":`the URL ${c(t.slice(o.length))} after a base`;return new RangeError(`${r}: url and init.method must name an endpoint of the exchanges' table under the base of its channel, got ${c(e)} and ${a}`)},yt=(e,t,n,r)=>{let o=()=>new RangeError(`${r}: url must hold the path of ${e.endpoint} as the contract writes it, each parameter one segment encoded by encodeURIComponent, got the path ${c(n)}`),a={};for(let[s,d]of Object.entries(t))try{a[s]=decodeURIComponent(d)}catch{throw o()}if((e.upload?de(e.endpoint,a).path:ie(e.endpoint,a).path)!==n)throw o();return a},gt=(e,t,n)=>{let r=ut.get(e);if(r===void 0){if(t!=="")throw new RangeError(`${n}: url must hold no query (${e} takes no query), got the query ${c(t)}`);return}let o=new Map;for(let[a,i]of new URLSearchParams(t.slice(1))){if(o.has(a))throw new RangeError(`${n}: url must hold each field of the query of ${e} once, got the field ${c(a)} twice`);o.set(a,r.includes(a)&&(i==="true"||i==="false")?i==="true":i)}return Object.fromEntries(o)},mt=(e,t,n,r)=>{if(!Ee(e))return t;let o=be(t),a=t.slice(o.length);return Re(a)?`${o}${Se(n,a,r,"unstampWrite")}`:t},_e=async(e,t,n,r,o)=>{C("string",e,o,"url");let a=t.method===void 0?"GET":t.method;if(typeof a!="string")throw new TypeError(`${o}: init.method must be undefined or a string, got ${c(a)}`);let i=mt(a,e,r,o),s=pt(a,i,n);if(s===null)throw ft(a,i,n,o);let{route:d,search:l}=s,g=yt(d,s.written,s.path,o),O;try{O=new Headers(t.headers)}catch(L){throw new TypeError(`${o}: init.headers must be headers the browser's Headers reads, got ${c(t.headers)}`,{cause:L})}let j=gt(d.endpoint,l,o),{body:k,filenames:P}=await Ne(d.endpoint,O.get("content-type"),t.body,o),q=ge(d.endpoint,{params:Object.keys(g).length===0?void 0:g,query:j,body:k,signal:t.signal===null?void 0:t.signal},o);if(q.query!==null&&he(d.endpoint,q.query)!==l)throw new RangeError(`${o}: url must hold the query of ${d.endpoint} as chatQueryString writes it of the query its schema read, got the query ${c(l)}`);if(d.upload){let L=P[0],Y=me(q.body.file_name);if(L!==Y)throw new RangeError(`${o}: init.body must carry the filename of its file part as the transport writes it of file_name (${c(Y)}), got ${c(L)}`)}return q};var v="createChatScenarioFetch",B="ChatScenarioFetch.fetch",ee="ChatScenarioFetch.plan",wt="ChatScenarioFetch.hold",ve="ChatScenarioHold.settle",Et="ChatScenarioFetch.assertDone",W="chatScenarioRefusal",Be=Object.freeze(Object.keys(N)),bt=Object.freeze(Object.keys(R.business_codes)),ze=se({answered:["kind","answer"],refused:["kind","status","body"],unreached:["kind"],response:["kind","response"]}),Rt=Object.freeze(Object.keys(ze)),te=Object.freeze(Object.keys(D.innerType().shape).filter(e=>e!=="error_code")),St="application/json",Pe=65536,Ct=1,qe=400,Le=599,Ot=Z({Blob:{attributes:["size","type"],operations:["slice"],statics:[]},AbortSignal:{attributes:["aborted","reason"],operations:["addEventListener","removeEventListener"],statics:["any"]}}),kt=Object.freeze({kind:"unreached"}),$t=Object.freeze({waiting:"has taken no request",answering:"awaits the answer its response function makes",settled:"has answered its request",stopped:"was stopped"}),Ie=e=>Object.getOwnPropertyDescriptor(AbortSignal.prototype,e).get,re=e=>Reflect.apply(Ie("aborted"),e,[])===!0,oe=e=>Reflect.apply(Ie("reason"),e,[]),Ue=e=>{let t=Function.prototype.bind(void 0);return Reflect.apply(AbortSignal.prototype.addEventListener,e,["abort",t]),Reflect.apply(AbortSignal.prototype.removeEventListener,e,["abort",t]),e},xt=e=>{let t=Ue(AbortSignal.any([Ue(e)]));if(re(t))throw new TypeError("the runtime's AbortSignal.any made an aborted signal from a signal that is not aborted");return t},Me=e=>typeof e=="object"&&e!==null||typeof e=="function",Fe=(e,t)=>{let n=!1,r=a=>{n||(n=!0,t.rejected(a))},o=a=>{if(n)return;n=!0;let i;try{i=Me(a)?Reflect.get(a,"then"):void 0}catch(d){t.rejected(d);return}if(typeof i!="function"){t.fulfilled(a);return}let s=i;Promise.resolve().then(()=>Fe((d,l)=>Reflect.apply(s,a,[d,l]),t))};try{e(o,r)}catch(a){r(a)}},He=(e,t,n)=>{let r=a=>new RangeError(`${t}: ${n} must be a value JSON.stringify writes as a JSON text, got ${c(e)}`,a===void 0?void 0:{cause:a}),o;try{o=JSON.stringify(e)}catch(a){throw r(a)}if(o===void 0)throw r();return o},At=(e,t,n,r)=>{let o=N[e];if(o.answer===null){if(t!==null)throw new TypeError(`${n}: ${r} must be null (${e} answers no body), got ${c(t)}`);return Object.freeze({kind:"json",status:o.status,text:null})}let a=He(t,n,r);return J(ue[o.answer],JSON.parse(a),n,r,`the answer of ${e} (${o.answer}) when written as a JSON text and read back`),Object.freeze({kind:"json",status:o.status,text:a})},Nt=(e,t,n,r)=>{let o=pe(e,n,`${r}.status`,`an integer from ${qe} to ${Le}`,s=>Number.isInteger(s)&&s>=qe&&s<=Le),a=He(t,n,`${r}.body`),i=ce(J(D,JSON.parse(a),n,`${r}.body`,"a failed answer's body when written as a JSON text and read back"));if(i!==null){let s=R.business_codes[i.name].http_status;if(o!==s)throw new RangeError(`${n}: ${r}.status must be ${s}, the status of the business code ${i.name} its body carries, got ${o}`)}return Object.freeze({kind:"json",status:o,text:a})},ne=(e,t,n,r)=>{C("object",t,n,r);let o=t,a=M(Rt,o.kind,n,`${r}.kind`),i=ze[a],s=Object.keys(o).find(d=>!i.includes(d));if(s!==void 0)throw new RangeError(`${n}: ${r} must hold only the fields of a reply of the kind ${a} (${i.join(", ")}), got the key ${c(s)}`);switch(a){case"answered":return At(e,o.answer,n,`${r}.answer`);case"refused":{let{status:d,body:l}=o;return Nt(d,l,n,r)}case"unreached":return kt;case"response":{let{response:d}=o;return C("function",d,n,`${r}.response`),Object.freeze({kind:"response",make:d})}}},jt=e=>{let t=new TextEncoder().encode(e),n=()=>{},r;return{stream:new ReadableStream({type:"bytes",start:i=>{r=i;for(let s=0;s<t.byteLength;s+=Pe)i.enqueue(t.slice(s,s+Pe))},pull:i=>{n(),i.close(),i.byobRequest?.respond(0)},cancel:()=>{n()}},{highWaterMark:Ct}),tie:i=>{let s=()=>{n(),r.error(oe(i))};n=()=>Reflect.apply(AbortSignal.prototype.removeEventListener,i,["abort",s]),Reflect.apply(AbortSignal.prototype.addEventListener,i,["abort",s])}}},Tt=e=>{if(e.text===null)return{response:new Response(null,{status:e.status}),tie:null};let t=jt(e.text);return{response:new Response(t.stream,{status:e.status,headers:{"Content-Type":St}}),tie:t.tie}},_t=e=>{let t=Reflect.get(Blob.prototype,"arrayBuffer"),n=Reflect.get(globalThis,"FileReader");if(typeof t!="function"&&typeof n!="function")throw new TypeError(`${e}: the runtime's Blob.prototype.arrayBuffer or its FileReader must be a function, as an upload's file is read by one of them, got ${c(t)} and ${c(n)}`)},vt=e=>e instanceof Error?`${e.name}: ${e.message}`:c(e),on=(e,t)=>{let n=M(bt,e,W,"name");C("object",t,W,"fields");let r=t,o=Object.keys(r).find(g=>!te.includes(g));if(o!==void 0)throw new RangeError(`${W}: fields must hold only the fields of a failed answer's body besides error_code (${te.join(", ")}), got the key ${c(o)}`);let{number:a,http_status:i}=R.business_codes[n],s=[["error_code",a],...te.map(g=>[g,r[g]])],d=Object.fromEntries(s.filter(([,g])=>g!==void 0)),l=J(D,d,W,"fields",`the fields of a failed answer's body of ${n}`);return Z({kind:"refused",status:i,body:l})},an=e=>{C("object",e,v,"options");let{jsonBaseUrl:t,uploadBaseUrl:n,unstampWrite:r}=e;G(t,v,"jsonBaseUrl"),G(n,v,"uploadBaseUrl"),C("function",r,v,"unstampWrite"),we(v,Ot),_t(v);let o=Object.freeze({jsonBaseUrl:t,uploadBaseUrl:n}),a=new Map,i=[],s=[],d=[],l=new Set,g=new Set,O=Promise.resolve(),j=()=>{for(let w of g)w()},k=w=>{let u=a.get(w);if(u!==void 0)return u;let y=[];return a.set(w,y),y};return Object.freeze({fetch:(w,u)=>{let y;try{y=Te(u,B)}catch(m){return d.push(m),Promise.reject(m)}let E=ye(y.signal)?y.signal:null;if(E!==null&&re(E))return Promise.reject(oe(E));let f=null;if(E!==null)try{f=xt(E)}catch(m){let x=new TypeError(`${B}: init.signal must be a signal the runtime's AbortSignal.any can make the request's own signal from, got ${c(E)}`,{cause:m});return d.push(x),Promise.reject(x)}return new Promise((m,x)=>{let b=!1,$=null,U={};l.add(U);let T=p=>{b||(b=!0,l.delete(U),$!==null&&$.phase.kind==="answering"&&($.phase={kind:"settled"}),f!==null&&(g.delete(S),Reflect.apply(AbortSignal.prototype.removeEventListener,f,["abort",Q])),p())},z=p=>{S(),d.push(p),T(()=>x(p))},Q=()=>{$!==null&&($.phase={kind:"stopped"}),T(()=>x(oe(E)))},S=()=>(!b&&E!==null&&re(E)&&Q(),b),De=p=>{let h;try{h=Tt(p)}catch(I){z(I);return}T(()=>{f!==null&&h.tie!==null&&h.tie(f),m(h.response)})},Je=p=>{let h,I;try{h=Reflect.apply(p,void 0,[]),I=Me(h)?Reflect.get(h,"then"):void 0}catch(A){z(A);return}if(typeof I!="function"){T(()=>m(h));return}let Ye=I;Fe((A,Qe)=>Reflect.apply(Ye,h,[A,Qe]),{fulfilled:A=>{S(),T(()=>m(A))},rejected:A=>{S()||z(A)}})},ae=p=>{if(!S())switch(p.kind){case"unreached":T(()=>x(new TypeError(`${B}: the request was not reached, as its step planned`)));return;case"json":De(p);return;case"response":Je(p.make)}},We=p=>{let h=a.get(p.endpoint)?.shift();if(h===void 0)throw new RangeError(`${B}: a request of ${p.endpoint} must find a step the scenario planned for it, got one when none is left`);if(s.push(p),h.kind==="hold"){$=h.state,l.delete(U),h.state.phase={kind:"arrived",answer:ae},h.state.arrive(p);return}ae(h.kind==="reply"?h.reply:ne(p.endpoint,Reflect.apply(h.step,void 0,[p]),B,h.field))};f!==null&&(g.add(S),Reflect.apply(AbortSignal.prototype.addEventListener,f,["abort",Q])),O=O.then(async()=>{if(S())return;let p;try{p=await _e(w,y,o,r,B)}catch(h){S()||z(h);return}if(!S())try{We(p)}catch(h){z(h)}})})},plan:(w,...u)=>{let y=M(Be,w,ee,"endpoint");if(u.length===0)throw new RangeError(`${ee}: steps must be one step or more, got none`);let E=u.map((f,m)=>Object.freeze(typeof f=="function"?{kind:"function",step:f,field:`steps[${m}](request)`}:{kind:"reply",reply:ne(y,f,ee,`steps[${m}]`)}));k(y).push(...E)},hold:w=>{let u=M(Be,w,wt,"endpoint"),y,E=new Promise(b=>{y=b}),f={endpoint:u,phase:{kind:"waiting"},arrive:y};i.push(f),k(u).push(Object.freeze({kind:"hold",state:f}));let m=()=>{j();let{phase:b}=f;if(b.kind!=="arrived")throw new TypeError(`${ve}: the held step of ${u} must hold a request it has neither answered nor stopped, got a step that ${$t[b.kind]}`);return b};return Object.freeze({arrived:E,settle:b=>{m();let $=ne(u,b,ve,"reply"),U=m();f.phase={kind:"answering"},U.answer($)}})},requests:()=>Object.freeze([...s]),assertDone:()=>{j();let w=[...l.size>0?[`requests still being read: ${l.size}`]:[],...d.map(u=>`the breach ${vt(u)}`),...[...a].filter(([,u])=>u.length>0).map(([u,y])=>`untaken steps of ${u}: ${y.length}`),...i.filter(u=>u.phase.kind==="arrived"||u.phase.kind==="answering").map(u=>`the held request of ${u.endpoint} neither answered nor stopped`)];if(w.length>0)throw new Error(`${Et}: the scenario must end with every request read, no breach, every step taken, and every held request answered or stopped, got ${w.join("; ")}`)}})};export{on as chatScenarioRefusal,an as createChatScenarioFetch};
@@ -0,0 +1,128 @@
1
+ import { z } from "zod";
2
+ import { B as ChatBusinessCodeName, R as ChatExchangeEndpointName, P as ChatExchangeAnswer, I as ChatErrorBody, $ as ChatQueryName, aR as chatQuerySchemas, Q as ChatExchangeBody } from "./index-iHWm67aF.cjs";
3
+ declare const EXCHANGE_PATH_PARAMS: {
4
+ readonly listConversations: readonly [
5
+ ];
6
+ readonly createConversation: readonly [
7
+ ];
8
+ readonly getConversation: readonly [
9
+ "conversation_uid"
10
+ ];
11
+ readonly listMessages: readonly [
12
+ "conversation_uid"
13
+ ];
14
+ readonly getMessage: readonly [
15
+ "conversation_uid",
16
+ "message_uid"
17
+ ];
18
+ readonly getMessagePath: readonly [
19
+ "conversation_uid",
20
+ "message_uid"
21
+ ];
22
+ readonly startRun: readonly [
23
+ "conversation_uid"
24
+ ];
25
+ readonly getRun: readonly [
26
+ "run_uid"
27
+ ];
28
+ readonly cancelRun: readonly [
29
+ "run_uid"
30
+ ];
31
+ readonly listModels: readonly [
32
+ ];
33
+ readonly getSettings: readonly [
34
+ ];
35
+ readonly updateSettings: readonly [
36
+ ];
37
+ readonly getAttachment: readonly [
38
+ "attachment_uid"
39
+ ];
40
+ readonly updateAttachment: readonly [
41
+ "attachment_uid"
42
+ ];
43
+ readonly deleteAttachment: readonly [
44
+ "attachment_uid"
45
+ ];
46
+ readonly createAttachment: readonly [
47
+ ];
48
+ };
49
+ type ChatExchangePathParams = typeof EXCHANGE_PATH_PARAMS;
50
+ type ChatExchangeParamName<Endpoint extends ChatExchangeEndpointName> = ChatExchangePathParams[Endpoint][number];
51
+ type ChatExchangeParams<Endpoint extends ChatExchangeEndpointName> = {
52
+ readonly [Name in ChatExchangeParamName<Endpoint>]: string;
53
+ };
54
+ type ChatExchangeQuery<Endpoint extends ChatExchangeEndpointName> = Endpoint extends ChatQueryName ? z.input<(typeof chatQuerySchemas)[Endpoint]> : never;
55
+ type ParamsField<Endpoint extends ChatExchangeEndpointName> = [
56
+ ChatExchangeParamName<Endpoint>
57
+ ] extends [
58
+ never
59
+ ] ? {
60
+ readonly params?: undefined;
61
+ } : {
62
+ readonly params: ChatExchangeParams<Endpoint>;
63
+ };
64
+ type QueryField<Endpoint extends ChatExchangeEndpointName> = [
65
+ Endpoint
66
+ ] extends [
67
+ ChatQueryName
68
+ ] ? Partial<ChatExchangeQuery<Endpoint>> extends ChatExchangeQuery<Endpoint> ? {
69
+ readonly query?: ChatExchangeQuery<Endpoint>;
70
+ } : {
71
+ readonly query: ChatExchangeQuery<Endpoint>;
72
+ } : {
73
+ readonly query?: undefined;
74
+ };
75
+ type BodyField<Endpoint extends ChatExchangeEndpointName> = [
76
+ ChatExchangeBody<Endpoint>
77
+ ] extends [
78
+ null
79
+ ] ? {
80
+ readonly body?: undefined;
81
+ } : {
82
+ readonly body: ChatExchangeBody<Endpoint>;
83
+ };
84
+ type SoleMember<Member extends ChatExchangeEndpointName, Whole extends ChatExchangeEndpointName> = Member extends unknown ? ([
85
+ Whole
86
+ ] extends [
87
+ Member
88
+ ] ? Member : never) : never;
89
+ type ChatSingleEndpoint<Endpoint extends ChatExchangeEndpointName> = Endpoint & SoleMember<Endpoint, Endpoint>;
90
+ type ChatExchangeRequest<Endpoint extends ChatExchangeEndpointName> = ParamsField<Endpoint> & QueryField<Endpoint> & BodyField<Endpoint> & {
91
+ readonly signal?: AbortSignal;
92
+ };
93
+ type ChatExchangeBreach = {
94
+ readonly kind: "status";
95
+ readonly status: number;
96
+ } | {
97
+ readonly kind: "content-type";
98
+ readonly status: number;
99
+ readonly contentType: string | null;
100
+ } | {
101
+ readonly kind: "json";
102
+ readonly status: number;
103
+ } | {
104
+ readonly kind: "shape";
105
+ readonly status: number;
106
+ readonly error: z.ZodError;
107
+ } | {
108
+ readonly kind: "business-status";
109
+ readonly status: number;
110
+ readonly business: ChatBusinessCodeName;
111
+ };
112
+ type ChatExchangeOutcome<Endpoint extends ChatExchangeEndpointName> = {
113
+ readonly kind: "answered";
114
+ readonly answer: ChatExchangeAnswer<Endpoint>;
115
+ } | {
116
+ readonly kind: "refused";
117
+ readonly status: number;
118
+ readonly body: ChatErrorBody | null;
119
+ } | {
120
+ readonly kind: "unreached";
121
+ } | {
122
+ readonly kind: "incompatible";
123
+ readonly breach: ChatExchangeBreach;
124
+ };
125
+ type ChatTransport = {
126
+ readonly exchange: <Endpoint extends ChatExchangeEndpointName>(endpoint: ChatSingleEndpoint<Endpoint>, request: ChatExchangeRequest<Endpoint>) => Promise<ChatExchangeOutcome<Endpoint>>;
127
+ };
128
+ export type { ChatExchangeBreach as C, ChatExchangeOutcome as a, ChatExchangeParams as b, ChatExchangeRequest as c, ChatSingleEndpoint as d, ChatTransport as e };
@@ -0,0 +1,128 @@
1
+ import { z } from "zod";
2
+ import { B as ChatBusinessCodeName, R as ChatExchangeEndpointName, P as ChatExchangeAnswer, I as ChatErrorBody, $ as ChatQueryName, aR as chatQuerySchemas, Q as ChatExchangeBody } from "./index-iHWm67aF.js";
3
+ declare const EXCHANGE_PATH_PARAMS: {
4
+ readonly listConversations: readonly [
5
+ ];
6
+ readonly createConversation: readonly [
7
+ ];
8
+ readonly getConversation: readonly [
9
+ "conversation_uid"
10
+ ];
11
+ readonly listMessages: readonly [
12
+ "conversation_uid"
13
+ ];
14
+ readonly getMessage: readonly [
15
+ "conversation_uid",
16
+ "message_uid"
17
+ ];
18
+ readonly getMessagePath: readonly [
19
+ "conversation_uid",
20
+ "message_uid"
21
+ ];
22
+ readonly startRun: readonly [
23
+ "conversation_uid"
24
+ ];
25
+ readonly getRun: readonly [
26
+ "run_uid"
27
+ ];
28
+ readonly cancelRun: readonly [
29
+ "run_uid"
30
+ ];
31
+ readonly listModels: readonly [
32
+ ];
33
+ readonly getSettings: readonly [
34
+ ];
35
+ readonly updateSettings: readonly [
36
+ ];
37
+ readonly getAttachment: readonly [
38
+ "attachment_uid"
39
+ ];
40
+ readonly updateAttachment: readonly [
41
+ "attachment_uid"
42
+ ];
43
+ readonly deleteAttachment: readonly [
44
+ "attachment_uid"
45
+ ];
46
+ readonly createAttachment: readonly [
47
+ ];
48
+ };
49
+ type ChatExchangePathParams = typeof EXCHANGE_PATH_PARAMS;
50
+ type ChatExchangeParamName<Endpoint extends ChatExchangeEndpointName> = ChatExchangePathParams[Endpoint][number];
51
+ type ChatExchangeParams<Endpoint extends ChatExchangeEndpointName> = {
52
+ readonly [Name in ChatExchangeParamName<Endpoint>]: string;
53
+ };
54
+ type ChatExchangeQuery<Endpoint extends ChatExchangeEndpointName> = Endpoint extends ChatQueryName ? z.input<(typeof chatQuerySchemas)[Endpoint]> : never;
55
+ type ParamsField<Endpoint extends ChatExchangeEndpointName> = [
56
+ ChatExchangeParamName<Endpoint>
57
+ ] extends [
58
+ never
59
+ ] ? {
60
+ readonly params?: undefined;
61
+ } : {
62
+ readonly params: ChatExchangeParams<Endpoint>;
63
+ };
64
+ type QueryField<Endpoint extends ChatExchangeEndpointName> = [
65
+ Endpoint
66
+ ] extends [
67
+ ChatQueryName
68
+ ] ? Partial<ChatExchangeQuery<Endpoint>> extends ChatExchangeQuery<Endpoint> ? {
69
+ readonly query?: ChatExchangeQuery<Endpoint>;
70
+ } : {
71
+ readonly query: ChatExchangeQuery<Endpoint>;
72
+ } : {
73
+ readonly query?: undefined;
74
+ };
75
+ type BodyField<Endpoint extends ChatExchangeEndpointName> = [
76
+ ChatExchangeBody<Endpoint>
77
+ ] extends [
78
+ null
79
+ ] ? {
80
+ readonly body?: undefined;
81
+ } : {
82
+ readonly body: ChatExchangeBody<Endpoint>;
83
+ };
84
+ type SoleMember<Member extends ChatExchangeEndpointName, Whole extends ChatExchangeEndpointName> = Member extends unknown ? ([
85
+ Whole
86
+ ] extends [
87
+ Member
88
+ ] ? Member : never) : never;
89
+ type ChatSingleEndpoint<Endpoint extends ChatExchangeEndpointName> = Endpoint & SoleMember<Endpoint, Endpoint>;
90
+ type ChatExchangeRequest<Endpoint extends ChatExchangeEndpointName> = ParamsField<Endpoint> & QueryField<Endpoint> & BodyField<Endpoint> & {
91
+ readonly signal?: AbortSignal;
92
+ };
93
+ type ChatExchangeBreach = {
94
+ readonly kind: "status";
95
+ readonly status: number;
96
+ } | {
97
+ readonly kind: "content-type";
98
+ readonly status: number;
99
+ readonly contentType: string | null;
100
+ } | {
101
+ readonly kind: "json";
102
+ readonly status: number;
103
+ } | {
104
+ readonly kind: "shape";
105
+ readonly status: number;
106
+ readonly error: z.ZodError;
107
+ } | {
108
+ readonly kind: "business-status";
109
+ readonly status: number;
110
+ readonly business: ChatBusinessCodeName;
111
+ };
112
+ type ChatExchangeOutcome<Endpoint extends ChatExchangeEndpointName> = {
113
+ readonly kind: "answered";
114
+ readonly answer: ChatExchangeAnswer<Endpoint>;
115
+ } | {
116
+ readonly kind: "refused";
117
+ readonly status: number;
118
+ readonly body: ChatErrorBody | null;
119
+ } | {
120
+ readonly kind: "unreached";
121
+ } | {
122
+ readonly kind: "incompatible";
123
+ readonly breach: ChatExchangeBreach;
124
+ };
125
+ type ChatTransport = {
126
+ readonly exchange: <Endpoint extends ChatExchangeEndpointName>(endpoint: ChatSingleEndpoint<Endpoint>, request: ChatExchangeRequest<Endpoint>) => Promise<ChatExchangeOutcome<Endpoint>>;
127
+ };
128
+ export type { ChatExchangeBreach as C, ChatExchangeOutcome as a, ChatExchangeParams as b, ChatExchangeRequest as c, ChatSingleEndpoint as d, ChatTransport as e };