palbase 0.73.0 → 0.73.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/README.md +1 -1
  2. package/dist/ai/index.js +2 -2
  3. package/dist/ai-sdk/index.js +2 -2
  4. package/dist/backend/engine.js +2 -2
  5. package/dist/backend/env.js +1 -1
  6. package/dist/backend/index.js +3 -3
  7. package/dist/backend/stack.js +1 -1
  8. package/dist/backend/test.js +2 -2
  9. package/dist/chunks/{DIQMCEMJ.js → 2TKZTIMD.js} +2 -2
  10. package/dist/chunks/{YMIK6HLK.js → 3KCV4F4F.js} +2 -2
  11. package/dist/chunks/{PAQCJT7M.js → 4E4ABCSD.js} +2 -2
  12. package/dist/chunks/{IICQMY2Z.js → 5N5GHLUU.js} +2 -2
  13. package/dist/chunks/{EKOEK6LR.js → 5N6QKGPA.js} +2 -2
  14. package/dist/chunks/{MVKZWEHL.js → AXANFT2A.js} +2 -2
  15. package/dist/chunks/{P36C47FS.js → DNSLYLU6.js} +1 -1
  16. package/dist/chunks/{3DUDNEMM.js → GTKPHG5F.js} +2 -2
  17. package/dist/chunks/{757A6AR6.js → GWWU2FJ7.js} +2 -2
  18. package/dist/chunks/{PEQZDT6P.js → HRWVZ4PC.js} +2 -2
  19. package/dist/chunks/{LCDNCPQW.js → HYPCFC4K.js} +1 -1
  20. package/dist/chunks/{P4NZ4NZD.js → IVJOWYRE.js} +2 -2
  21. package/dist/chunks/{5OOA4R4H.js → MB7MHOQO.js} +1 -1
  22. package/dist/chunks/{VEL7X2G3.js → MFSC4OJV.js} +2 -2
  23. package/dist/chunks/{76W5ZO2L.js → SEICTPQP.js} +2 -2
  24. package/dist/chunks/{JG4V6LNY.js → SQNAPFXW.js} +2 -2
  25. package/dist/chunks/{4XSSQAES.js → SS2RVI27.js} +1 -1
  26. package/dist/chunks/{UFP6GLLW.js → TR2IPX2A.js} +2 -2
  27. package/dist/chunks/{25HECIZY.js → U3H6HER3.js} +1 -1
  28. package/dist/chunks/{SRN7N2WX.js → UOJVMV42.js} +2 -2
  29. package/dist/chunks/{SMECWMF7.js → UXHNXE3J.js} +2 -2
  30. package/dist/chunks/{CY6KUFZW.js → VCL3SAQL.js} +2 -2
  31. package/dist/chunks/{J7ZNBBRN.js → W2KD2I4Q.js} +1 -1
  32. package/dist/chunks/{J7Z2PYL4.js → YU3GFTZV.js} +1 -1
  33. package/dist/cli.js +8 -8
  34. package/dist/cloud/index.js +2 -2
  35. package/dist/refuse/ai-sdk.js +1 -1
  36. package/dist/refuse/ai.js +1 -1
  37. package/dist/refuse/backend.js +1 -1
  38. package/dist/refuse/cloud.js +1 -1
  39. package/dist/refuse/server.js +1 -1
  40. package/dist/server/index.js +2 -2
  41. package/dist/server/testing.js +2 -2
  42. package/dist/web/index.js +2 -2
  43. package/dist/web/message.js +2 -2
  44. package/dist/web/palbe.js +2 -2
  45. package/dist/web/payments-ui.js +2 -2
  46. package/dist/web/paywall.js +2 -2
  47. package/dist/web/push-sw.js +1 -1
  48. package/dist/web/ssr.js +2 -2
  49. package/dist/web/vite.js +2 -2
  50. package/package.json +2 -2
@@ -1,5 +1,5 @@
1
- /*! palbase 0.73.0 — Palbase SDK License (see LICENSE) */
2
- import{b as N,d as I,e as R}from"./VEL7X2G3.js";import{a as Q,f as Y,g as Z,j as X,k as ee,l as te,o as G,p as ne,q as se}from"./J7Z2PYL4.js";import{d as A}from"./YMIK6HLK.js";import{a as E,b as z,c as T,e as j}from"./PEQZDT6P.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=e,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function ie(n){return n instanceof p||typeof n=="object"&&n!==null&&n.name==="BackendError"&&typeof n.kind=="string"}function D(n){let e=n.body,t={code:n.code,message:n.message,status:n.status,requestId:n.requestId??We(e,"request_id"),data:S(e,"data"),cause:n};if(n.code==="network_error")return new p("network",t);if(n.status===401&&n.code==="insufficient_user_authentication")return new p("stepUpRequired",t);if(n.status===401&&n.code==="app_attest_required")return new p("attestationRequired",t);if(n.status===401)return new p("unauthorized",t);if(n.status===429)return new p("rateLimited",{...t,retryAfter:He(e)??n.retryAfter});let s=Je(e);return n.status===400&&s?new p("validation",{...t,fields:s}):new p("server",t)}function P(n){return n instanceof z||n instanceof Error&&n.name==="PalbaseError"}function re(n){return Array.isArray(n)&&n.length>0&&n.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Je(n){let e=S(S(n,"data"),"fields");if(re(e))return e;let t=S(n,"fields");return re(t)?t:void 0}function He(n){return oe(n,"retry_after")??oe(S(n,"data"),"retryAfter")}function S(n,e){if(typeof n=="object"&&n!==null)return n[e]}function oe(n,e){let t=S(n,e);return typeof t=="number"?t:void 0}function We(n,e){let t=S(n,e);return typeof t=="string"?t:void 0}var Ve=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ue=Object.freeze(["adoptSession","ai","analytics","anonymousTelemetry","appContext","appEvent","appVersion","auth","callOnSignOut","calls","cancelCallOnSignOut","captureOnce","chatToolCall","chatWorkspaceFile","configuration","consent","currentSession","defaults","flags","installation","keychainItem","module","moduleDirectory","notify","offerTaker","onAppEvent","onSessionChange","onSignOut","preferences","realtime","scope","send","setLanguage","setPreferredLanguages","signedInUserNow","socket","storage","storedUserId","telemetry","transport","transportFor","upload","version","watchSessions","palbe","data","stores","iap","payments","commerce","campaigns","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ze=new Set(Ue),Qe=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function O(n){return n==="then"||n==="toJSON"||Qe.has(n)}function ae(n){return n==="call"||n==="join"||O(n)}function de(n){return typeof n=="string"&&Ve.test(n)&&!ze.has(n)&&!O(n)}function le(n){return typeof n=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(n)}function ce(n){j(n)}function ue(n){return j(n).origin}var $=class n{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;execution={target:null,generation:0,workspaceSeq:0,machineId:null,machineStatus:null,failoverAt:null,lastHandoff:null,compactions:[],offloads:[]};handoffGens=new Set;compactionSeqs=new Set;offloadKeys=new Set;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},t,s,r=!0){this.me=e,this.reader=t,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let t=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...t!==void 0?{turns:t}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let f=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(f,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(f=>N(f)).filter(f=>f!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),t===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;t-=a.turns}while(t>0);return this.olderLeft}idFor(e,t){let s=t??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let u=w(i);u<=0||(this.paged.add(u),(this.pagedFrom===void 0||u<this.pagedFrom)&&(this.pagedFrom=u),(this.pagedTo===void 0||u>this.pagedTo)&&(this.pagedTo=u))}let t=new n(this.me);t.thoughts=this.thoughts,t.lowest=this.lowest-e.length;let s=t.lowest;for(let i of e)t.at=s++,t.fold(i);this.folded+=t.folded,this.lowest=t.lowest,this.chatId??=t.chatId;let r=new Map;for(let[i,u]of t.messages){let m=this.told.get(i)??[],k=u;if(m.length>0)for(let C of m)k=ye(k,C);else k=this.messages.get(i)??u;r.set(i,k);let _=[...t.told.get(i)??[],...m];_.length>0&&this.told.set(i,_)}for(let[i,u]of this.messages)r.has(i)||r.set(i,u);this.messages.clear();for(let[i,u]of r)this.messages.set(i,u);let o=new Map;for(let[i,u]of t.responses){let m=this.responses.get(i);o.set(i,m?Ze(u,m):u)}for(let[i,u]of this.responses)o.has(i)||o.set(i,u);this.responses.clear();for(let[i,u]of o)this.responses.set(i,u);let d=new Set;for(let i of t.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...t.order],l=new Set([...t.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&t.goalWords.has(i.event.seq))&&!(i.type==="voice"&&t.voiceWords.has(K(i.event)))&&!(i.type==="handoff"&&t.handoffGens.has(i.event.generation))&&!(i.type==="compaction"&&i.event.seq>0&&t.compactionSeqs.has(i.event.seq))){if(i.type==="message"&&i.began&&i.turn!==null){let u=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:u&&u.at<i.arrived?u.at-.5:i.arrived});continue}a.push(i)}a.sort((i,u)=>i.at-u.at),this.order=a;for(let i of t.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of t.voiceWords)this.voiceWords.add(i);let f=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=me(this.voice,i.event,f));for(let i of t.handoffGens)this.handoffGens.add(i);for(let i of t.compactionSeqs)this.compactionSeqs.add(i);for(let i of t.offloadKeys)this.offloadKeys.add(i);t.execution.generation>this.execution.generation&&(this.execution={...this.execution,target:t.execution.target,generation:t.execution.generation,workspaceSeq:t.execution.workspaceSeq,lastHandoff:t.execution.lastHandoff}),this.execution.machineStatus===null&&t.execution.machineStatus!==null&&(this.execution={...this.execution,machineId:t.execution.machineId,machineStatus:t.execution.machineStatus,failoverAt:t.execution.failoverAt});let c=[];for(let i of a)i.type==="compaction"&&c.push(i.event);let h=[...t.execution.offloads,...this.execution.offloads.filter(i=>!t.offloadKeys.has(ge(i)))];this.execution={...this.execution,compactions:c,offloads:h},this.turn??=t.turn;let y=new Map([...t.calls,...this.calls]);this.calls.clear();for(let[i,u]of y)this.calls.set(i,u);for(let[i,u]of t.history)this.history.has(i)||this.history.set(i,u);this.forkedFrom??=t.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,t,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==t){t=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let t=N(e);t&&this.take(t)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let t=w(e);t>0&&this.pagedTo!==void 0&&t>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=he(setTimeout(()=>this.quiet(),pe)));return}this.takeNow(e)}}quiet(){let e=this.held.map(w).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Ye?this.heldTimer=he(setTimeout(()=>this.quiet(),pe)):this.sortHeld()}takeNow(e){let t=w(e);t>0&&this.paged.has(t)||(t>0&&(this.oldestLive===void 0||t<this.oldestLive)&&(this.oldestLive=t),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),t=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(w(a))),d=o<0?-1:t.findIndex(a=>w(a)===w(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],t[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<t.length&&fe(e[o+l],t[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(f=>w(f)>0),l=a!==void 0&&this.pagedFrom!==void 0&&w(a)<this.pagedFrom;for(let f of e){let c=w(f);c>0&&!(this.pagedFrom!==void 0&&c<this.pagedFrom)&&(l=!1),(l?s:r).push(f)}}if(s.length>0){let a=Math.min(...s.map(w).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let t=this.response(e.response_id);t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(t.startedBy=e.user_id),e.goal&&(t.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let t=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){t.marks.set("thinking:unavailable",{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=t.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:t.marks.set(s,{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let t=K(e);if(this.voiceWords.has(t))return!1;this.voice=me(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let t=this.response(e.response_id);tt(t,e.offset,e.text),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"reset":{let t=this.response(e.response_id);e.offset<=t.from?(t.text="",t.from=Math.max(0,e.offset)):t.text=t.text.slice(0,R(t.text,e.offset-t.from)),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let t=this.response(e.response_id);t.runId=e.run_id,t.agent=e.name,t.named=!0,t.parentId??=e.parent_response_id;break}case"session.handed_off":{if(this.handoffGens.has(e.generation))return!1;this.handoffGens.add(e.generation),e.generation>=this.execution.generation&&(this.execution={...this.execution,target:e.to_target,generation:e.generation,workspaceSeq:e.workspace_seq,machineId:e.to_target.compute.machine_id??null,failoverAt:null,lastHandoff:e}),this.order.push({type:"handoff",event:e,at:this.at});break}case"session.machine_status":{this.execution={...this.execution,machineId:e.machine_id||this.execution.machineId,machineStatus:e.status,failoverAt:e.failover_at??null};break}case"context.offloaded":{let t=ge(e);if(this.offloadKeys.has(t))return!1;this.offloadKeys.add(t),this.execution={...this.execution,offloads:[...this.execution.offloads,e]};break}case"context.compacted":{if(e.seq>0){if(this.compactionSeqs.has(e.seq))return!1;this.compactionSeqs.add(e.seq)}this.execution={...this.execution,compactions:[...this.execution.compactions,e]},this.order.push({type:"compaction",event:e,at:this.at});break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let t=this.goal;if(!t||t.id!==e.goal_id)return;let s={...t,events:[...t.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let t=et(e),s=this.messages.get(t);this.messages.set(t,ye(s,e));let r=this.told.get(t);r?r.push(e):this.told.set(t,[e]),s||this.place(e,t),this.changed()}said(e){let t=`voice\0${e.id}`,s=this.messages.get(t);this.messages.set(t,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:t,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,t){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,f])=>l!==t&&f.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:t,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let t=this.responses.get(e);return t||(t={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,t),this.order.push({type:"response",key:e,at:this.at})),t}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let t of[...this.listeners])try{t(e)}catch{}}))}build(){let e=this.me(),t=c=>e!==void 0&&c.startedBy===e,s=new Map;for(let c of this.responses.values()){let h=c.parentId!==null?this.responses.get(c.parentId)??c:c;s.set(c.id,nt(c,h.startedBy??null,t(h),c.goal??h.goal))}let r=new Map([...this.messages].map(([c,h])=>[c,e!==void 0&&h.author===e?{...h,mine:!0}:h])),o=[...this.history.entries()].sort(([c],[h])=>c-h).flatMap(([c,h])=>h.map((y,i)=>st(y,`${c}:${i}`,e))),d=[...o];for(let c of this.order)c.type==="goal"?d.push({type:"goal",goal:c.event}):c.type==="voice"?d.push({type:"voice",voice:c.event}):c.type==="handoff"?d.push({type:"handoff",handoff:c.event}):c.type==="compaction"?d.push({type:"compaction",compaction:c.event}):c.type==="message"?d.push({type:"message",message:r.get(c.key)}):this.responses.get(c.key).parentId===null&&d.push({type:"response",response:s.get(c.key)});let a=o.flatMap(c=>c.type==="message"?[c.message]:[]),l=o.flatMap(c=>c.type==="response"?[c.response]:[]),f=[...this.calls.values()].filter(c=>s.get(c.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:f.filter(c=>c.status==="awaiting_approval"),outputs:f.filter(c=>c.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Xe(this.voice,e):null,execution:this.execution}}},pe=150,Ye=2e3;function fe(n,e){let t=w(n);return t>0||w(e)>0?t===w(e):JSON.stringify(n)===JSON.stringify(e)}function w(n){let e=n.seq;return typeof e=="number"&&e>0?e:0}function he(n){return n.unref?.(),n}function K(n){return`${n.voice_id}\0${n.status}`}function ge(n){return n.seq>0?`seq:${n.seq}`:`call:${n.call_id}:${n.ref??""}`}function me(n,e,t){return t.add(K(e)),(e.status==="closed"?n===null||n.voice_id===e.voice_id:!t.has(`${e.voice_id}\0closed`))?e:n}function ye(n,e){let t=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??n?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:n?.status==="delivered"?"delivered":t,error:e.error??null,responseId:e.response_id??n?.responseId??null,createdAt:e.created_at??n?.createdAt??"",mine:!1,metadata:e.metadata??n?.metadata??{},history:!1,truncated:!1,kind:e.kind??n?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:n?.voice??null,attachments:e.attachments?we(e.attachments):n?.attachments??[]}}function Ze(n,e){let t={...n,marks:new Map(n.marks)};e.status!==null&&(t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=e.end),e.startedBy!==void 0&&(t.startedBy=e.startedBy),e.goal&&(t.goal=e.goal),e.named&&(t.runId=e.runId,t.agent=e.agent,t.named=!0),t.parentId=n.parentId??e.parentId,e.cut!==null&&(n.text===""||e.cut<=n.from?(t.text=e.text,t.from=e.text===""?Math.max(0,e.cut):e.from):t.text=n.text.slice(0,R(n.text,e.cut-n.from))+e.text,t.cut=n.cut===null?e.cut:Math.min(n.cut,e.cut));let s=r=>{if(n.text==="")return null;if(r!==null&&r<=n.from)return r;let o=I(n.text);return n.from+(r===null?o:Math.min(o,r-n.from))};for(let[r,o]of e.marks){let d=t.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")t.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);t.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?n.cut:n.cut===null?o.cutAt:Math.min(o.cutAt,n.cut)})}else t.marks.set(r,o)}return t}function Xe(n,e){return{id:n.voice_id,userId:n.user_id,mine:e!==void 0&&n.user_id===e,delegation:n.delegation,status:n.status,seconds:typeof n.seconds=="number"?n.seconds:null,closeReason:n.close_reason??""}}function we(n){return n.map((e,t)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:t,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function et(n){return`${n.author??""}\0${n.client_id}`}function tt(n,e,t){if(n.text===""||e<=n.from){n.from=Math.max(0,e),n.text=t;return}n.text=n.text.slice(0,R(n.text,e-n.from))+t}function nt(n,e,t,s){let r=[...n.marks.values()].map((l,f)=>({m:l,i:f,at:R(n.text,Math.max(0,(Number(l.text_offset)||0)-n.from))}));r.sort((l,f)=>l.at-f.at||l.i-f.i);let o=[],d=[],a=0;for(let{m:l,at:f}of r)f>a&&o.push({type:"text",text:n.text.slice(a,f)}),a=Math.max(a,f),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<n.text.length&&o.push({type:"text",text:n.text.slice(a)}),{id:n.id,status:n.status,waiting:n.waiting,end:n.end,error:n.error,text:n.text,parts:o,runId:n.runId,agent:n.agent,parentId:n.parentId,startedBy:e,mine:t,thinking:d,goal:s,history:!1,truncated:!1}}function st(n,e,t){let s=n.text_truncated===!0;if(n.role==="user"){let r=n.author??null;return{type:"message",message:{clientId:n.client_id??"",id:n.message_id??null,text:n.text,author:r,authorName:n.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:n.created_at??"",mine:t!==void 0&&r===t,metadata:n.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(n.attachments??[])}}}return{type:"response",response:{id:n.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:n.text,parts:n.text===""?[]:[{type:"text",text:n.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var ve=[["ApiKeyAuth","userJWT"]];function be(n){return{async parts(e,t){let s={};t.limit!==void 0&&(s.limit=t.limit),t.turns!==void 0&&(s.turns=t.turns),t.cursor!==void 0?s.cursor=t.cursor:t.before!==void 0&&(s.before=t.before);let r=(await n.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${T("ListChatParts","chat_id",e)}/parts`,auth:ve,answers:{200:"json"},query:s,signal:t.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,t,s){if(typeof t!="string"||t==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await n.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${T("GetChatToolCall","chat_id",e)}/tool-calls/${T("GetChatToolCall","call_id",t)}`,auth:ve,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}}}}var M=class extends Error{reason;constructor(e,t){super(e),this.name="GatewayError",this.reason=t}},ke=new WeakMap;async function Ee(n,e,t,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:f,chat:c}=rt(e),h=ot(d,t),y=ke.get(n);y||ke.set(n,y=new Map);let i=y,u=i.get(h)??{count:0};i.set(h,u),u.count++;let m=n.channel(h,f&&s.history!==!1?{after:0}:{});if(c&&!u.chat){let g=t.chatId,x=new $(r,o,typeof g=="string"&&g!==""?g:void 0,f&&s.history!==!1);u.chat=x,u.unchat=m.on("broadcast",v=>{v.event==="chat"&&x.takePayload(v.payload)})}let k=()=>{--u.count>0||(i.delete(h),u.unchat?.(),u.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?xe(m.refusal,"unavailable"):"socket closed";throw k(),new M(`gateway ${JSON.stringify(h)} was not joined: ${g}`,g)}let _=!1,C=new Set,W=()=>{if(!_){_=!0,Fe();for(let g of[...C])g();k()}},Fe=m.onClosed(W),V=g=>{if(_)return()=>{};let x=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),v=()=>{C.delete(v),x()};return C.add(v),v},U={topic:h,get seq(){return m.logSeq},on(g,x){if(typeof g=="function")return V((v,b)=>g({event:v,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof x!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return V((v,b)=>{v===g&&x(b)})},off(g){C.has(g)&&g()},async send(g,x){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let v=_?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:x});if(v.status==="ok")return E(v.response.reply);let b=xe(v.response,"unavailable");throw new M(`gateway ${JSON.stringify(h)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:W};return c&&Object.defineProperty(U,"chat",{value:u.chat,enumerable:!0}),U}function rt(n){let e=typeof n=="object"&&n!==null?n:{},t=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!t(e.events)||!t(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function ot(n,e){let t=typeof e=="object"&&e!==null?e:{};return n.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(t,r)?t[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(n)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(n)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function xe(n,e){let t=n?.reason;return typeof t=="string"&&t!==""?t:e}var it=3600*1e3,q=new Map;function at(n,e,t=!1){let s=`${e.projectId}\0${e.signer}`,r=q.get(s);if(!t&&r&&Date.now()-r.at<it)return r.list;let o=(async()=>{let d=ne(),a;try{a=(await n.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await se(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return q.set(s,{list:o,at:Date.now()}),o.catch(()=>{q.get(s)?.list===o&&q.delete(s)}),o}async function _e(n,e,t,s,r,o){let a=(await at(n,e,o)).keys[0];return Z(a.kid,a.key,Y(e.projectId,t,s,r))}function L(n,e,t,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,t,s,(r,o)=>X(n.key,r,o))}function Se(n,e,t,s){return e===void 0||!t||t.length===0?Promise.resolve(e):G(e,"/response",t,async(r,o)=>{if(!ee(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await te(n.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(n){return n instanceof p&&(n.code==="encryption_key_retired"||n.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
1
+ /*! palbase 0.73.1 — Palbase SDK License (see LICENSE) */
2
+ import{b as N,d as I,e as R}from"./MFSC4OJV.js";import{a as Q,f as Y,g as Z,j as X,k as ee,l as te,o as G,p as ne,q as se}from"./YU3GFTZV.js";import{d as A}from"./3KCV4F4F.js";import{a as E,b as z,c as T,e as j}from"./HRWVZ4PC.js";var p=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,t){super(t.message,t.cause===void 0?void 0:{cause:t.cause}),this.name="BackendError",this.kind=e,this.code=t.code,this.status=t.status??0,this.requestId=t.requestId,this.fields=t.fields,this.retryAfter=t.retryAfter,this.data=t.data}};function ie(n){return n instanceof p||typeof n=="object"&&n!==null&&n.name==="BackendError"&&typeof n.kind=="string"}function D(n){let e=n.body,t={code:n.code,message:n.message,status:n.status,requestId:n.requestId??We(e,"request_id"),data:S(e,"data"),cause:n};if(n.code==="network_error")return new p("network",t);if(n.status===401&&n.code==="insufficient_user_authentication")return new p("stepUpRequired",t);if(n.status===401&&n.code==="app_attest_required")return new p("attestationRequired",t);if(n.status===401)return new p("unauthorized",t);if(n.status===429)return new p("rateLimited",{...t,retryAfter:He(e)??n.retryAfter});let s=Je(e);return n.status===400&&s?new p("validation",{...t,fields:s}):new p("server",t)}function P(n){return n instanceof z||n instanceof Error&&n.name==="PalbaseError"}function re(n){return Array.isArray(n)&&n.length>0&&n.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Je(n){let e=S(S(n,"data"),"fields");if(re(e))return e;let t=S(n,"fields");return re(t)?t:void 0}function He(n){return oe(n,"retry_after")??oe(S(n,"data"),"retryAfter")}function S(n,e){if(typeof n=="object"&&n!==null)return n[e]}function oe(n,e){let t=S(n,e);return typeof t=="number"?t:void 0}function We(n,e){let t=S(n,e);return typeof t=="string"?t:void 0}var Ve=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ue=Object.freeze(["adoptSession","ai","analytics","anonymousTelemetry","appContext","appEvent","appVersion","auth","callOnSignOut","calls","cancelCallOnSignOut","captureOnce","chatToolCall","chatWorkspaceFile","configuration","consent","currentSession","defaults","flags","installation","keychainItem","module","moduleDirectory","notify","offerTaker","onAppEvent","onSessionChange","onSignOut","preferences","realtime","scope","send","setLanguage","setPreferredLanguages","signedInUserNow","socket","storage","storedUserId","telemetry","transport","transportFor","upload","version","watchSessions","palbe","data","stores","iap","payments","commerce","campaigns","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),ze=new Set(Ue),Qe=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function O(n){return n==="then"||n==="toJSON"||Qe.has(n)}function ae(n){return n==="call"||n==="join"||O(n)}function de(n){return typeof n=="string"&&Ve.test(n)&&!ze.has(n)&&!O(n)}function le(n){return typeof n=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(n)}function ce(n){j(n)}function ue(n){return j(n).origin}var $=class n{me;reader;messages=new Map;told=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;execution={target:null,generation:0,workspaceSeq:0,machineId:null,machineStatus:null,failoverAt:null,lastHandoff:null,compactions:[],offloads:[]};handoffGens=new Set;compactionSeqs=new Set;offloadKeys=new Set;history=new Map;forkedFrom=null;calls=new Map;thoughts=new Set;at=0;next=0;lowest=0;folded=0;paged=new Set;pagedFrom;pagedTo;racing=!1;replays;held=[];racedPages=[];heldTimer;heldSince=0;oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;changing=!1;ended=!1;constructor(e=()=>{},t,s,r=!0){this.me=e,this.reader=t,this.chatId=s,this.replays=r}get hasOlder(){return this.olderLeft}loadOlder(e={}){return e.limit!==void 0&&e.turns!==void 0?Promise.reject(new TypeError("loadOlder: limit (events) or turns (turns), not both")):e.turns!==void 0&&(!Number.isSafeInteger(e.turns)||e.turns<1||e.turns>20)?Promise.reject(new TypeError(`loadOlder: turns is how many more of the chat's turns to read back to, 1 to 20 (got ${String(e.turns)})`)):(this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading)}async readOlder(e){let t=e.turns;do{if(!this.olderLeft)return!1;let s=this.olderCursor,r=this.next===0&&this.olderCursor===void 0,d={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...t!==void 0?{turns:t}:{},...e.signal?{signal:e.signal}:{}},a;if(e.load)a=await e.load(d);else{let f=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");a=await this.reader.parts(f,d)}if(this.ended)return!1;let l=(a?.parts??[]).map(f=>N(f)).filter(f=>f!==void 0);if(this.olderCursor=a?.nextCursor,this.olderLeft=typeof a?.nextCursor=="string"&&a.nextCursor!=="",this.before(l),r&&this.replays&&this.next===0&&this.pagedFrom!==void 0?(this.racing=!0,this.racedPages=l):this.racing&&(this.racedPages=l.concat(this.racedPages)),t===void 0||typeof a?.turns!="number"||s!==void 0&&this.olderCursor===s)break;t-=a.turns}while(t>0);return this.olderLeft}idFor(e,t){let s=t??this.chatId;if(typeof s!="string"||s==="")throw new TypeError(`${e}: the chat's id is not known yet (no chatId in the join, no message heard): give { chatId }`);return s}before(e){for(let i of e){let u=w(i);u<=0||(this.paged.add(u),(this.pagedFrom===void 0||u<this.pagedFrom)&&(this.pagedFrom=u),(this.pagedTo===void 0||u>this.pagedTo)&&(this.pagedTo=u))}let t=new n(this.me);t.thoughts=this.thoughts,t.lowest=this.lowest-e.length;let s=t.lowest;for(let i of e)t.at=s++,t.fold(i);this.folded+=t.folded,this.lowest=t.lowest,this.chatId??=t.chatId;let r=new Map;for(let[i,u]of t.messages){let m=this.told.get(i)??[],k=u;if(m.length>0)for(let C of m)k=ye(k,C);else k=this.messages.get(i)??u;r.set(i,k);let _=[...t.told.get(i)??[],...m];_.length>0&&this.told.set(i,_)}for(let[i,u]of this.messages)r.has(i)||r.set(i,u);this.messages.clear();for(let[i,u]of r)this.messages.set(i,u);let o=new Map;for(let[i,u]of t.responses){let m=this.responses.get(i);o.set(i,m?Ze(u,m):u)}for(let[i,u]of this.responses)o.has(i)||o.set(i,u);this.responses.clear();for(let[i,u]of o)this.responses.set(i,u);let d=new Set;for(let i of t.order)(i.type==="message"||i.type==="response")&&d.add(`${i.type}\0${i.key}`);let a=[...t.order],l=new Set([...t.messages.values()].flatMap(i=>i.responseId?[i.responseId]:[]));for(let i of this.order)if(!((i.type==="message"||i.type==="response")&&d.has(`${i.type}\0${i.key}`))&&!(i.type==="goal"&&i.event.seq>0&&t.goalWords.has(i.event.seq))&&!(i.type==="voice"&&t.voiceWords.has(K(i.event)))&&!(i.type==="handoff"&&t.handoffGens.has(i.event.generation))&&!(i.type==="compaction"&&i.event.seq>0&&t.compactionSeqs.has(i.event.seq))){if(i.type==="message"&&i.began&&i.turn!==null){let u=this.responses.get(i.turn);l.has(i.turn)?a.push({...i,began:!1,at:i.arrived}):a.push({...i,at:u&&u.at<i.arrived?u.at-.5:i.arrived});continue}a.push(i)}a.sort((i,u)=>i.at-u.at),this.order=a;for(let i of t.goalWords)this.goalWords.add(i);this.goal=null;for(let i of a)i.type==="goal"&&this.goalSaid(i.event);for(let i of t.voiceWords)this.voiceWords.add(i);let f=new Set;this.voice=null;for(let i of a)i.type==="voice"&&(this.voice=me(this.voice,i.event,f));for(let i of t.handoffGens)this.handoffGens.add(i);for(let i of t.compactionSeqs)this.compactionSeqs.add(i);for(let i of t.offloadKeys)this.offloadKeys.add(i);t.execution.generation>this.execution.generation&&(this.execution={...this.execution,target:t.execution.target,generation:t.execution.generation,workspaceSeq:t.execution.workspaceSeq,lastHandoff:t.execution.lastHandoff}),this.execution.machineStatus===null&&t.execution.machineStatus!==null&&(this.execution={...this.execution,machineId:t.execution.machineId,machineStatus:t.execution.machineStatus,failoverAt:t.execution.failoverAt});let c=[];for(let i of a)i.type==="compaction"&&c.push(i.event);let h=[...t.execution.offloads,...this.execution.offloads.filter(i=>!t.offloadKeys.has(ge(i)))];this.execution={...this.execution,compactions:c,offloads:h},this.turn??=t.turn;let y=new Map([...t.calls,...this.calls]);this.calls.clear();for(let[i,u]of y)this.calls.set(i,u);for(let[i,u]of t.history)this.history.has(i)||this.history.set(i,u);this.forkedFrom??=t.forkedFrom,this.changed()}get state(){return this.snapshot??=this.build()}subscribe(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}async*[Symbol.asyncIterator](){let e,t,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==t){t=o,yield o;continue}if(this.ended)return;await new Promise(d=>e=d)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0,clearTimeout(this.heldTimer);for(let e of[...this.enders])e()}}takePayload(e){let t=N(e);t&&this.take(t)}take(e){if(!this.ended){if(this.racing){this.held.length===0&&(this.heldSince=Date.now()),this.held.push(e);let t=w(e);t>0&&this.pagedTo!==void 0&&t>this.pagedTo?this.sortHeld():(clearTimeout(this.heldTimer),this.heldTimer=he(setTimeout(()=>this.quiet(),pe)));return}this.takeNow(e)}}quiet(){let e=this.held.map(w).filter(s=>s>0);e.length>0&&e.every(s=>!this.paged.has(s)&&this.pagedFrom!==void 0&&s<this.pagedFrom)&&Date.now()-this.heldSince<Ye?this.heldTimer=he(setTimeout(()=>this.quiet(),pe)):this.sortHeld()}takeNow(e){let t=w(e);t>0&&this.paged.has(t)||(t>0&&(this.oldestLive===void 0||t<this.oldestLive)&&(this.oldestLive=t),this.at=this.next++,this.fold(e)&&this.changed())}sortHeld(){clearTimeout(this.heldTimer),this.racing=!1;let e=this.held.splice(0),t=this.racedPages;this.racedPages=[];let s=[],r=[],o=e.findIndex(a=>this.paged.has(w(a))),d=o<0?-1:t.findIndex(a=>w(a)===w(e[o]));if(d>=0){let a=0;for(;a<o&&a<d&&fe(e[o-1-a],t[d-1-a]);)a++;let l=0;for(;o+l<e.length&&d+l<t.length&&fe(e[o+l],t[d+l]);)l++;s=e.slice(0,o-a),r=e.slice(o+l)}else{let a=e.find(f=>w(f)>0),l=a!==void 0&&this.pagedFrom!==void 0&&w(a)<this.pagedFrom;for(let f of e){let c=w(f);c>0&&!(this.pagedFrom!==void 0&&c<this.pagedFrom)&&(l=!1),(l?s:r).push(f)}}if(s.length>0){let a=Math.min(...s.map(w).filter(l=>l>0));this.before(s),Number.isFinite(a)&&(this.oldestLive=a,this.olderCursor=void 0)}for(let a of r)this.takeNow(a)}fold(e){switch(this.folded++,e.type){case"message":return this.chatId===void 0&&typeof e.message.chat_id=="string"&&e.message.chat_id!==""&&(this.chatId=e.message.chat_id),this.heard(e.message),!1;case"turn":{let t=this.response(e.response_id);t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(t.startedBy=e.user_id),e.goal&&(t.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let t=this.response(e.response_id);if(e.seq>0){if(this.thoughts.has(e.seq))return!1;this.thoughts.add(e.seq)}if(e.unavailable){t.marks.set("thinking:unavailable",{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:null,runId:e.run_id,text:"",unavailable:!0,model:e.model??null,reason:e.reason??null}});break}let s=`thinking:${e.step_id??`seq:${e.seq}`}`,r=t.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:t.marks.set(s,{type:"thinking",text_offset:t.from+I(t.text),loose:t.text==="",cutAt:t.cut,thinking:{stepId:e.step_id??null,runId:e.run_id,text:e.text,unavailable:!1,model:null,reason:null}});break}case"goal":if(e.seq>0){if(this.goalWords.has(e.seq))return!1;this.goalWords.add(e.seq)}this.goalSaid(e),this.order.push({type:"goal",event:e,at:this.at});break;case"voice":{let t=K(e);if(this.voiceWords.has(t))return!1;this.voice=me(this.voice,e,this.voiceWords),this.order.push({type:"voice",event:e,at:this.at});break}case"transcript":return this.said(e),!1;case"history":e.forked_from&&(this.forkedFrom={chatId:e.forked_from.chat_id,beforeMessage:e.forked_from.before_message}),this.history.set(e.part,e.items);break;case"text":{let t=this.response(e.response_id);tt(t,e.offset,e.text),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"reset":{let t=this.response(e.response_id);e.offset<=t.from?(t.text="",t.from=Math.max(0,e.offset)):t.text=t.text.slice(0,R(t.text,e.offset-t.from)),t.cut=t.cut===null?e.offset:Math.min(t.cut,e.offset);break}case"tool":{this.response(typeof e.agent_response_id=="string"&&e.agent_response_id!==""?e.agent_response_id:e.response_id).marks.set(`tool:${e.call_id}`,e),this.calls.set(e.call_id,e);break}case"agent":{if(this.response(e.parent_response_id).marks.set(e.run_id?`agent:${e.run_id}`:`agent:seq:${e.seq}`,e),!e.response_id)break;let t=this.response(e.response_id);t.runId=e.run_id,t.agent=e.name,t.named=!0,t.parentId??=e.parent_response_id;break}case"session.handed_off":{if(this.handoffGens.has(e.generation))return!1;this.handoffGens.add(e.generation),e.generation>=this.execution.generation&&(this.execution={...this.execution,target:e.to_target,generation:e.generation,workspaceSeq:e.workspace_seq,machineId:e.to_target.compute.machine_id??null,failoverAt:null,lastHandoff:e}),this.order.push({type:"handoff",event:e,at:this.at});break}case"session.machine_status":{this.execution={...this.execution,machineId:e.machine_id||this.execution.machineId,machineStatus:e.status,failoverAt:e.failover_at??null};break}case"context.offloaded":{let t=ge(e);if(this.offloadKeys.has(t))return!1;this.offloadKeys.add(t),this.execution={...this.execution,offloads:[...this.execution.offloads,e]};break}case"context.compacted":{if(e.seq>0){if(this.compactionSeqs.has(e.seq))return!1;this.compactionSeqs.add(e.seq)}this.execution={...this.execution,compactions:[...this.execution.compactions,e]},this.order.push({type:"compaction",event:e,at:this.at});break}}return!0}goalSaid(e){if(e.kind==="set"&&e.goal){this.goal={id:e.goal_id,objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null,events:[e]};return}let t=this.goal;if(!t||t.id!==e.goal_id)return;let s={...t,events:[...t.events,e]};e.kind==="updated"&&e.goal?Object.assign(s,{objective:e.goal.objective,rubric:e.goal.rubric,status:e.goal.status,stopCode:e.goal.stop_code,stopReason:e.goal.stop_reason,phase:e.goal.phase,maxTurns:e.goal.max_turns??null,maxCostUsd:e.goal.max_cost_usd??null}):e.kind==="status_changed"&&typeof e.to=="string"?Object.assign(s,{status:e.to,stopCode:e.code??"",stopReason:e.reason??""}):e.kind==="cleared"&&Object.assign(s,{status:"cleared",stopReason:e.reason??""}),this.goal=s}heard(e){let t=et(e),s=this.messages.get(t);this.messages.set(t,ye(s,e));let r=this.told.get(t);r?r.push(e):this.told.set(t,[e]),s||this.place(e,t),this.changed()}said(e){let t=`voice\0${e.id}`,s=this.messages.get(t);this.messages.set(t,{clientId:"",id:e.id,text:e.text,author:e.user_id,authorName:e.author_name,delivery:"next",status:"delivered",error:null,responseId:null,createdAt:e.created_at,mine:!1,metadata:{},history:!1,truncated:!1,kind:"voice",voice:{id:e.voice_id,role:e.role},attachments:[]}),s||this.order.push({type:"message",key:t,at:this.at,arrived:this.at,turn:null,began:!1}),this.changed()}place(e,t){let s=e.response_id??null,r=s!==null&&![...this.messages.entries()].some(([l,f])=>l!==t&&f.responseId===s),o=r?this.responses.get(s):void 0,d={type:"message",key:t,at:o?o.at-.5:this.at,arrived:this.at,turn:s,began:r},a=o?this.order.findIndex(l=>l.type==="response"&&l.key===s):-1;a>=0?this.order.splice(a,0,d):this.order.push(d)}response(e){let t=this.responses.get(e);return t||(t={id:e,status:null,waiting:null,end:null,error:null,text:"",from:0,cut:null,marks:new Map,runId:null,agent:null,named:!1,parentId:null,startedBy:void 0,goal:null,at:this.at},this.responses.set(e,t),this.order.push({type:"response",key:e,at:this.at})),t}changed(){this.snapshot=void 0,!this.changing&&(this.changing=!0,queueMicrotask(()=>{if(this.changing=!1,this.listeners.size===0)return;let e=this.state;for(let t of[...this.listeners])try{t(e)}catch{}}))}build(){let e=this.me(),t=c=>e!==void 0&&c.startedBy===e,s=new Map;for(let c of this.responses.values()){let h=c.parentId!==null?this.responses.get(c.parentId)??c:c;s.set(c.id,nt(c,h.startedBy??null,t(h),c.goal??h.goal))}let r=new Map([...this.messages].map(([c,h])=>[c,e!==void 0&&h.author===e?{...h,mine:!0}:h])),o=[...this.history.entries()].sort(([c],[h])=>c-h).flatMap(([c,h])=>h.map((y,i)=>st(y,`${c}:${i}`,e))),d=[...o];for(let c of this.order)c.type==="goal"?d.push({type:"goal",goal:c.event}):c.type==="voice"?d.push({type:"voice",voice:c.event}):c.type==="handoff"?d.push({type:"handoff",handoff:c.event}):c.type==="compaction"?d.push({type:"compaction",compaction:c.event}):c.type==="message"?d.push({type:"message",message:r.get(c.key)}):this.responses.get(c.key).parentId===null&&d.push({type:"response",response:s.get(c.key)});let a=o.flatMap(c=>c.type==="message"?[c.message]:[]),l=o.flatMap(c=>c.type==="response"?[c.response]:[]),f=[...this.calls.values()].filter(c=>s.get(c.response_id)?.mine===!0);return{items:d,messages:[...a,...r.values()],responses:[...l,...s.values()],turn:this.turn,waiting:{approvals:f.filter(c=>c.status==="awaiting_approval"),outputs:f.filter(c=>c.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Xe(this.voice,e):null,execution:this.execution}}},pe=150,Ye=2e3;function fe(n,e){let t=w(n);return t>0||w(e)>0?t===w(e):JSON.stringify(n)===JSON.stringify(e)}function w(n){let e=n.seq;return typeof e=="number"&&e>0?e:0}function he(n){return n.unref?.(),n}function K(n){return`${n.voice_id}\0${n.status}`}function ge(n){return n.seq>0?`seq:${n.seq}`:`call:${n.call_id}:${n.ref??""}`}function me(n,e,t){return t.add(K(e)),(e.status==="closed"?n===null||n.voice_id===e.voice_id:!t.has(`${e.voice_id}\0closed`))?e:n}function ye(n,e){let t=e.status==="delivered"||e.status==="failed"?e.status:"pending";return{clientId:e.client_id,id:e.id??n?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:n?.status==="delivered"?"delivered":t,error:e.error??null,responseId:e.response_id??n?.responseId??null,createdAt:e.created_at??n?.createdAt??"",mine:!1,metadata:e.metadata??n?.metadata??{},history:!1,truncated:!1,kind:e.kind??n?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:n?.voice??null,attachments:e.attachments?we(e.attachments):n?.attachments??[]}}function Ze(n,e){let t={...n,marks:new Map(n.marks)};e.status!==null&&(t.status=e.status,t.waiting=e.waiting,t.error=e.error,t.end=e.end),e.startedBy!==void 0&&(t.startedBy=e.startedBy),e.goal&&(t.goal=e.goal),e.named&&(t.runId=e.runId,t.agent=e.agent,t.named=!0),t.parentId=n.parentId??e.parentId,e.cut!==null&&(n.text===""||e.cut<=n.from?(t.text=e.text,t.from=e.text===""?Math.max(0,e.cut):e.from):t.text=n.text.slice(0,R(n.text,e.cut-n.from))+e.text,t.cut=n.cut===null?e.cut:Math.min(n.cut,e.cut));let s=r=>{if(n.text==="")return null;if(r!==null&&r<=n.from)return r;let o=I(n.text);return n.from+(r===null?o:Math.min(o,r-n.from))};for(let[r,o]of e.marks){let d=t.marks.get(r);if(d?.type==="thinking"&&o.type==="thinking"&&r!=="thinking:unavailable")t.marks.set(r,{...d,thinking:{...d.thinking,text:d.thinking.text+o.thinking.text}});else if(o.type==="thinking"&&o.loose){let a=s(o.cutAt);t.marks.set(r,a!==null?{...o,text_offset:a,loose:!1}:{...o,cutAt:o.cutAt===null?n.cut:n.cut===null?o.cutAt:Math.min(o.cutAt,n.cut)})}else t.marks.set(r,o)}return t}function Xe(n,e){return{id:n.voice_id,userId:n.user_id,mine:e!==void 0&&n.user_id===e,delegation:n.delegation,status:n.status,seconds:typeof n.seconds=="number"?n.seconds:null,closeReason:n.close_reason??""}}function we(n){return n.map((e,t)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:t,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function et(n){return`${n.author??""}\0${n.client_id}`}function tt(n,e,t){if(n.text===""||e<=n.from){n.from=Math.max(0,e),n.text=t;return}n.text=n.text.slice(0,R(n.text,e-n.from))+t}function nt(n,e,t,s){let r=[...n.marks.values()].map((l,f)=>({m:l,i:f,at:R(n.text,Math.max(0,(Number(l.text_offset)||0)-n.from))}));r.sort((l,f)=>l.at-f.at||l.i-f.i);let o=[],d=[],a=0;for(let{m:l,at:f}of r)f>a&&o.push({type:"text",text:n.text.slice(a,f)}),a=Math.max(a,f),l.type==="thinking"?(o.push({type:"thinking",thinking:l.thinking}),d.push(l.thinking)):o.push(l.type==="tool"?{type:"tool",tool:l}:{type:"agent",agent:l});return a<n.text.length&&o.push({type:"text",text:n.text.slice(a)}),{id:n.id,status:n.status,waiting:n.waiting,end:n.end,error:n.error,text:n.text,parts:o,runId:n.runId,agent:n.agent,parentId:n.parentId,startedBy:e,mine:t,thinking:d,goal:s,history:!1,truncated:!1}}function st(n,e,t){let s=n.text_truncated===!0;if(n.role==="user"){let r=n.author??null;return{type:"message",message:{clientId:n.client_id??"",id:n.message_id??null,text:n.text,author:r,authorName:n.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:n.created_at??"",mine:t!==void 0&&r===t,metadata:n.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:we(n.attachments??[])}}}return{type:"response",response:{id:n.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:n.text,parts:n.text===""?[]:[{type:"text",text:n.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var ve=[["ApiKeyAuth","userJWT"]];function be(n){return{async parts(e,t){let s={};t.limit!==void 0&&(s.limit=t.limit),t.turns!==void 0&&(s.turns=t.turns),t.cursor!==void 0?s.cursor=t.cursor:t.before!==void 0&&(s.before=t.before);let r=(await n.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${T("ListChatParts","chat_id",e)}/parts`,auth:ve,answers:{200:"json"},query:s,signal:t.signal})).data;return{parts:r.parts,...r.next_cursor!==void 0?{nextCursor:r.next_cursor}:{},...r.turns!==void 0?{turns:r.turns}:{}}},async toolCall(e,t,s){if(typeof t!="string"||t==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await n.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${T("GetChatToolCall","chat_id",e)}/tool-calls/${T("GetChatToolCall","call_id",t)}`,auth:ve,answers:{200:"json"},signal:s})).data;return{callId:r.call_id,name:r.name,status:r.status,runId:r.run_id,responseId:r.response_id,input:r.input,output:r.output,outputBytes:r.output_bytes,imageCount:r.image_count,isError:r.is_error}}}}var M=class extends Error{reason;constructor(e,t){super(e),this.name="GatewayError",this.reason=t}},ke=new WeakMap;async function Ee(n,e,t,s={},r=()=>{},o){let{pattern:d,events:a,messages:l,durable:f,chat:c}=rt(e),h=ot(d,t),y=ke.get(n);y||ke.set(n,y=new Map);let i=y,u=i.get(h)??{count:0};i.set(h,u),u.count++;let m=n.channel(h,f&&s.history!==!1?{after:0}:{});if(c&&!u.chat){let g=t.chatId,x=new $(r,o,typeof g=="string"&&g!==""?g:void 0,f&&s.history!==!1);u.chat=x,u.unchat=m.on("broadcast",v=>{v.event==="chat"&&x.takePayload(v.payload)})}let k=()=>{--u.count>0||(i.delete(h),u.unchat?.(),u.chat?.end(),m.leave())};try{await m.join()}catch{let g=m.state==="refused"?xe(m.refusal,"unavailable"):"socket closed";throw k(),new M(`gateway ${JSON.stringify(h)} was not joined: ${g}`,g)}let _=!1,C=new Set,W=()=>{if(!_){_=!0,Fe();for(let g of[...C])g();k()}},Fe=m.onClosed(W),V=g=>{if(_)return()=>{};let x=m.on("broadcast",b=>{typeof b.event=="string"&&a.has(b.event)&&g(b.event,E(b.payload))}),v=()=>{C.delete(v),x()};return C.add(v),v},U={topic:h,get seq(){return m.logSeq},on(g,x){if(typeof g=="function")return V((v,b)=>g({event:v,payload:b}));if(!a.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no event ${JSON.stringify(String(g))}`);if(typeof x!="function")throw new TypeError(`gateway ${JSON.stringify(d)}: on(${JSON.stringify(g)}, \u2026) takes the function the event is handed to`);return V((v,b)=>{v===g&&x(b)})},off(g){C.has(g)&&g()},async send(g,x){if(!l.has(g))throw new TypeError(`gateway ${JSON.stringify(d)} declares no message ${JSON.stringify(String(g))}`);let v=_?{status:"error",response:{reason:"not joined"}}:await m.push("broadcast",{type:"broadcast",event:g,payload:x});if(v.status==="ok")return E(v.response.reply);let b=xe(v.response,"unavailable");throw new M(`gateway ${JSON.stringify(h)} did not take ${JSON.stringify(g)}: ${b}`,b)},leave:W};return c&&Object.defineProperty(U,"chat",{value:u.chat,enumerable:!0}),U}function rt(n){let e=typeof n=="object"&&n!==null?n:{},t=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!t(e.events)||!t(e.messages))throw new TypeError("join takes a gateway of the backend's generated module: its pattern, its events and its messages");return{pattern:e.pattern,events:new Set(e.events),messages:new Set(e.messages),durable:e.durable===!0,chat:e.chat===!0}}function ot(n,e){let t=typeof e=="object"&&e!==null?e:{};return n.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(t,r)?t[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(n)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(n)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function xe(n,e){let t=n?.reason;return typeof t=="string"&&t!==""?t:e}var it=3600*1e3,q=new Map;function at(n,e,t=!1){let s=`${e.projectId}\0${e.signer}`,r=q.get(s);if(!t&&r&&Date.now()-r.at<it)return r.list;let o=(async()=>{let d=ne(),a;try{a=(await n.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:d},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(l){throw new p("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:l})}try{return await se(a,e.signer,e.projectId,d)}catch(l){throw new p("decode",{code:"encryption_keys_unverified",message:"the project's list of encryption keys does not verify with the key this app was built with: nothing is sealed to it",cause:l})}})();return q.set(s,{list:o,at:Date.now()}),o.catch(()=>{q.get(s)?.list===o&&q.delete(s)}),o}async function _e(n,e,t,s,r,o){let a=(await at(n,e,o)).keys[0];return Z(a.kid,a.key,Y(e.projectId,t,s,r))}function L(n,e,t,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,t,s,(r,o)=>X(n.key,r,o))}function Se(n,e,t,s){return e===void 0||!t||t.length===0?Promise.resolve(e):G(e,"/response",t,async(r,o)=>{if(!ee(o))throw new p("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await te(n.key,r,o)}catch(d){throw new p("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:d})}})}function Ce(n){return n instanceof p&&(n.code==="encryption_key_retired"||n.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
3
  `);let t=[],s=this.pending.indexOf(`
4
4
  `);for(;s!==-1;){let r=this.pending.slice(0,s);this.pending=this.pending.slice(s+1);let o=r.endsWith("\r")?r.slice(0,-1):r;if(o==="")this.dataLines.length>0&&t.push({event:this.eventName,payload:this.dataLines.join(`
5
5
  `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let d=o.slice(5);this.dataLines.push(d.startsWith(" ")?d.slice(1):d)}else if(o.startsWith("event:")){let d=o.slice(6);this.eventName=d.startsWith(" ")?d.slice(1):d}}s=this.pending.indexOf(`