palbase 0.14.2 → 0.16.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.
Files changed (61) hide show
  1. package/dist/ai/index.js +2 -2
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +3 -3
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/{427AGWP3.js → 2JBRAHJV.js} +2 -2
  8. package/dist/chunks/{7DQ76T2V.js → 5W7IKTRI.js} +2 -2
  9. package/dist/chunks/{6NC5RYCS.js → 7HYPHYX5.js} +1 -1
  10. package/dist/chunks/{44ULNVPP.js → A4YMCQOP.js} +1 -1
  11. package/dist/chunks/{PRJZTG2I.js → C5PO7C6L.js} +1 -1
  12. package/dist/chunks/{4UQ4J7RV.js → CFGQWDV5.js} +3 -3
  13. package/dist/chunks/CXZ6WKOI.js +18 -0
  14. package/dist/chunks/{JKWWY2LJ.js → EHWHP4MD.js} +2 -2
  15. package/dist/chunks/{WXNFMEW7.js → EJHB65XA.js} +2 -2
  16. package/dist/chunks/{LUFWGH2V.js → HVC5H5HY.js} +2 -2
  17. package/dist/chunks/{CUL5OL4P.js → IA4LTPBJ.js} +2 -2
  18. package/dist/chunks/{RD5JFDGQ.js → JOWAWH33.js} +2 -2
  19. package/dist/chunks/L73SEFXF.js +21 -0
  20. package/dist/chunks/LY7D5Q3R.js +2 -0
  21. package/dist/chunks/NQNE5PZW.js +13 -0
  22. package/dist/chunks/{W3OCV3QH.js → QN5WMSP7.js} +2 -2
  23. package/dist/chunks/{SBUC7GHR.js → S7WYS4NC.js} +2 -2
  24. package/dist/chunks/TGVFGW5G.js +2 -0
  25. package/dist/chunks/{HHZSOYPP.js → TIC3NMUT.js} +1 -1
  26. package/dist/chunks/{DIOZGDFQ.js → VNLECYBD.js} +1 -1
  27. package/dist/chunks/{ZZNGA77G.js → VTUZYTKZ.js} +1 -1
  28. package/dist/chunks/{A46IASZE.js → WCTVLG4W.js} +2 -2
  29. package/dist/chunks/{P67I4TNQ.js → YUBOQ3NU.js} +1 -1
  30. package/dist/cli.js +127 -127
  31. package/dist/refuse/ai.js +1 -1
  32. package/dist/refuse/backend.js +1 -1
  33. package/dist/refuse/server.js +1 -1
  34. package/dist/server/index.js +2 -2
  35. package/dist/server/testing.js +2 -2
  36. package/dist/web/index.js +2 -2
  37. package/dist/web/message.js +2 -2
  38. package/dist/web/palbe.js +2 -2
  39. package/dist/web/paywall.js +2 -2
  40. package/dist/web/push-sw.js +1 -1
  41. package/dist/web/ssr.js +2 -2
  42. package/dist/web/vite.js +2 -2
  43. package/package.json +2 -2
  44. package/types/ai/src/ai.d.ts +18 -1
  45. package/types/ai/src/chats.d.ts +13 -2
  46. package/types/ai/src/index.d.ts +1 -1
  47. package/types/backend/src/decorators.d.ts +20 -0
  48. package/types/backend/src/engine.d.ts +9 -0
  49. package/types/backend/src/openapi.d.ts +3 -0
  50. package/types/backend/src/router.d.ts +2 -0
  51. package/types/internal/src/modules/ai.d.ts +67 -2
  52. package/types/internal/src/modules/analytics.d.ts +6 -2
  53. package/types/internal/src/modules/auth.d.ts +33 -14
  54. package/types/internal/src/modules/journeys.d.ts +45 -0
  55. package/types/web/src/backend-error.d.ts +6 -1
  56. package/types/web/src/inapp.d.ts +2 -0
  57. package/dist/chunks/3AENUHVO.js +0 -2
  58. package/dist/chunks/5H7UNNH6.js +0 -13
  59. package/dist/chunks/BRHGS5AI.js +0 -18
  60. package/dist/chunks/OMK2YEDZ.js +0 -2
  61. package/dist/chunks/QZH6GPCR.js +0 -21
@@ -402,6 +402,10 @@ export type JourneyConvertedEvent = {
402
402
  * The run's id
403
403
  */
404
404
  run_id: string;
405
+ /**
406
+ * A test user's run (POST /journeys/{key}/test); absent on a person's
407
+ */
408
+ test?: boolean;
405
409
  /**
406
410
  * The person
407
411
  */
@@ -427,6 +431,10 @@ export type JourneyEndedEvent = {
427
431
  * The run's id
428
432
  */
429
433
  run_id: string;
434
+ /**
435
+ * A test user's run (POST /journeys/{key}/test); absent on a person's
436
+ */
437
+ test?: boolean;
430
438
  /**
431
439
  * The person
432
440
  */
@@ -448,6 +456,10 @@ export type JourneyEnteredEvent = {
448
456
  * The run's id
449
457
  */
450
458
  run_id: string;
459
+ /**
460
+ * A test user's run (POST /journeys/{key}/test); absent on a person's
461
+ */
462
+ test?: boolean;
451
463
  /**
452
464
  * The person
453
465
  */
@@ -483,6 +495,10 @@ export type JourneyEventEvent = {
483
495
  * The step's id
484
496
  */
485
497
  step: string;
498
+ /**
499
+ * A test user's run (POST /journeys/{key}/test); absent on a person's
500
+ */
501
+ test?: boolean;
486
502
  /**
487
503
  * The person
488
504
  */
@@ -599,6 +615,10 @@ export type JourneyStepEvent = {
599
615
  * The step's id
600
616
  */
601
617
  step: string;
618
+ /**
619
+ * A test user's run (POST /journeys/{key}/test); absent on a person's
620
+ */
621
+ test?: boolean;
602
622
  /**
603
623
  * The person
604
624
  */
@@ -759,6 +779,10 @@ export type Run = {
759
779
  * The steps it took, in order
760
780
  */
761
781
  steps: RunStep[];
782
+ /**
783
+ * A run tried on a test user (POST /journeys/{key}/test): its waits a minute long, counted in no report and no month's people
784
+ */
785
+ test: boolean;
762
786
  /**
763
787
  * The person
764
788
  */
@@ -997,6 +1021,15 @@ export type StepStats = {
997
1021
  */
998
1022
  step: string;
999
1023
  };
1024
+ /**
1025
+ * The test user a journey is tried on.
1026
+ */
1027
+ export type TestRunWrite = {
1028
+ /**
1029
+ * One of the project's test users (Auth › Test accounts)
1030
+ */
1031
+ user_id: string;
1032
+ };
1000
1033
  /**
1001
1034
  * What a definition's check found.
1002
1035
  */
@@ -1219,5 +1252,17 @@ export declare function client(t: Transport): {
1219
1252
  }; /** Stops the call: the request in flight, a wait before a retry, a proof-of-work being solved. */
1220
1253
  signal?: AbortSignal;
1221
1254
  }): Promise<Reply<200, Journey>>;
1255
+ /**
1256
+ * Try a journey on a test user
1257
+ *
1258
+ * Runs a journey — a draft too — for one of the project's test users (Auth › Test accounts), from its start, now: its messages are sent and its coupons given as a person's would be, but each wait lasts a minute, and the run is counted in no report and no month's people (its events carry test: true). A test run of the user's open in the journey ends first. Refused for a user who is no test user (422 not_a_test_user) and for a stopped journey (409 journey_stopped).
1259
+ */
1260
+ testJourney(input: {
1261
+ path: {
1262
+ key: string;
1263
+ };
1264
+ body: TestRunWrite; /** Stops the call: the request in flight, a wait before a retry, a proof-of-work being solved. */
1265
+ signal?: AbortSignal;
1266
+ }): Promise<Reply<201, Run>>;
1222
1267
  };
1223
1268
  export type Client = ReturnType<typeof client>;
@@ -3,7 +3,12 @@ export interface FieldError {
3
3
  field: string;
4
4
  message: string;
5
5
  }
6
- export type BackendErrorKind = 'validation' | 'unauthorized' | 'rateLimited' | 'server' | 'network' | 'decode';
6
+ /**
7
+ * stepUpRequired: the route asks for a stronger sign-in than the user's (401 insufficient_user_authentication, RFC
8
+ * 9470; `data.acr_values` names the level, e.g. 'aal2'). The session is fine: step the user up (pb.auth's step-up)
9
+ * and call again.
10
+ */
11
+ export type BackendErrorKind = 'validation' | 'unauthorized' | 'stepUpRequired' | 'rateLimited' | 'server' | 'network' | 'decode';
7
12
  interface BackendErrorParams {
8
13
  code: string;
9
14
  message: string;
@@ -71,6 +71,8 @@ export declare class InApp {
71
71
  private limits;
72
72
  private shown;
73
73
  private loaded;
74
+ /** The page went out of view since the campaigns were last asked for. */
75
+ private away;
74
76
  private memorySession;
75
77
  private memoryPending;
76
78
  private showing;
@@ -1,2 +0,0 @@
1
- /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
- import{a as d,b as u}from"./JKWWY2LJ.js";var p={too_many_chats:()=>"this user is in as many chats as they may be (100): delete or leave one before starting another",too_many_endpoints:()=>"the project holds as many tool endpoints as it may (32): delete one (ai.endpoints.delete) before putting another",too_many_messages:t=>`this user has sent as many messages this minute as the project allows${t.retryAfter!==void 0?`: write again in ${t.retryAfter} s`:""}`,history_full:()=>"the project keeps as much chat history as it may: delete chats to write again",not_your_turn:()=>"this turn is another member's: only the member who started it (or the project's server) answers its tools and decides its approvals",not_a_member:()=>"the member the server acts as (as) is not in this chat: put them in it first (chats.members.put), or act as the server",goal_lapsed:()=>"the goal was set as a member who no longer stands where they stood then (out of the chat, or the chat no longer theirs alone): it is not resumed \u2014 clear it, or set another for the chat as it is now",goal_achieved:()=>"the goal is achieved: set a new one (chats.goal.set) to work on",turn_running:()=>"the chat's agent is at work on a turn: fork it once the turn has ended, or stop it first (chats.stop)",fork_too_large:()=>"what came before that message is more than a fork begins with (512 KiB): fork it before an earlier message",too_many_voices:t=>`this user has started as many voices this hour as the project allows (5)${t.retryAfter!==void 0?`: start again in ${t.retryAfter} s`:""}`,voice_active:()=>"another member's voice is live in this chat \u2014 one voice talks in a chat at a time: wait for it to end",not_your_voice:()=>"this voice is another member's: only its member \u2014 or the server as itself \u2014 reads, tells and closes it",voice_closed:()=>"the voice has ended: start a new one (chats.voice.start)",no_workspace:()=>"this chat works in no workspace, and files go into one: start the chat with a workspace, or send pictures as images",attachment_not_found:()=>"a picture or a file given is not one its writer may attach: a file of the project's storage \u2014 for a member, their own or a public bucket's",attachment_too_large:()=>"an attachment is past its bound: 5 MiB a picture, 15 MiB a file",attachment_changed:()=>"a file changed while it was being attached: send the message again",unsupported_image:()=>"a picture is not png, jpeg, webp or gif by its bytes: send it as a file",image_not_found:()=>"a picture given is not a file of the project's storage: upload it first (storage.from(bucket).upload(path, file)) and give that bucket and path",storage_unavailable:t=>`the project's storage did not answer when the model was to read a picture${t.retryAfter!==void 0?`: try again in ${t.retryAfter} s`:"; try again shortly"}`,draft_changed:()=>"the agent's draft was saved again since its revision was read: read it again (ai.agents.get) and make the change on that one",agent_defined_in_code:()=>"this agent is the backend's code's (its build's contract names it): it is changed in the code, and has no draft, versions or delete",nothing_to_publish:()=>"the agent's draft is the version published already: save a change to it first (ai.agents.saveDraft)",agent_not_published:()=>"the agent has no version published yet: publish its draft (ai.agents.publish) before a chat or an answer names it"},g=new WeakSet;function c(t){if(!(t instanceof u)||g.has(t))return t;let r=p[t.code];if(!r)return t;let s=new u({op:t.op,status:t.status,code:t.code,message:`${r(t)} (${t.op}: ${t.status} ${t.code})`,requestId:t.requestId,retryAfter:t.retryAfter,body:t.body,cause:t});return g.add(s),s}function m(t){return t.catch(r=>{throw c(r)})}function _(t){if(typeof t!="object"||t===null)return;let r=t,s=r.data;if(typeof r.type!="string"||typeof s!="object"||s===null||Array.isArray(s))return;let e=d(s),i=typeof r.id=="number"&&Number.isSafeInteger(r.id)?r.id:0;switch(r.type){case"message":return typeof e.client_id=="string"?{type:"message",seq:i,message:e}:void 0;case"turn":{if(typeof e.response_id!="string"||typeof e.status!="string")return;let n={...e,type:"turn",seq:i};return n.waiting??=null,n.error??=null,n}case"text":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"text",response_id:e.response_id,offset:n,text:typeof e.text=="string"?e.text:""}}case"reset":{let n=e.offset;return typeof e.response_id!="string"||typeof n!="number"||!Number.isInteger(n)||n<0?void 0:{type:"reset",response_id:e.response_id,offset:n}}case"tool":{if(typeof e.call_id!="string"||typeof e.response_id!="string")return;let n=e.omitted_bytes;return{...e,type:"tool",seq:i,omittedBytes:typeof n=="number"&&Number.isSafeInteger(n)&&n>0?n:0,outputTruncated:e.output_truncated===!0}}case"agent":return typeof e.parent_response_id=="string"?{...e,type:"agent",seq:i}:void 0;case"thinking":{if(typeof e.response_id!="string")return;let n=typeof e.run_id=="string"?e.run_id:"";return e.unavailable===!0?{type:"thinking",seq:i,response_id:e.response_id,run_id:n,text:"",unavailable:!0,model:typeof e.model=="string"?e.model:"",reason:typeof e.reason=="string"?e.reason:""}:typeof e.text!="string"?void 0:{type:"thinking",seq:i,response_id:e.response_id,run_id:n,...typeof e.step_id=="string"&&e.step_id!==""?{step_id:e.step_id}:{},text:e.text}}case"goal":{if(typeof e.goal_id!="string"||typeof e.kind!="string")return;let{seq:n,...o}=e;return{...o,type:"goal",seq:i,...typeof n=="number"?{turn:n}:{}}}case"history":{if(!Array.isArray(e.items)||typeof e.part!="number"||!Number.isInteger(e.part)||e.part<0)return;let n=e.items.filter(a=>typeof a=="object"&&a!==null&&(a.role==="user"||a.role==="assistant")&&typeof a.text=="string"),o=e.forked_from;return{type:"history",forked_from:o&&typeof o.chat_id=="string"?o:null,part:e.part,parts:typeof e.parts=="number"?e.parts:e.part+1,items:n}}case"voice":return typeof e.voice_id!="string"||e.voice_id===""||typeof e.status!="string"?void 0:{...e,type:"voice",seq:i,user_id:typeof e.user_id=="string"?e.user_id:null};case"transcript":return typeof e.id!="string"||e.id===""||typeof e.text!="string"?void 0:{type:"transcript",seq:i,id:e.id,voice_id:typeof e.voice_id=="string"?e.voice_id:"",role:typeof e.role=="string"?e.role:"",user_id:typeof e.user_id=="string"?e.user_id:null,author_name:typeof e.author_name=="string"?e.author_name:"",text:e.text,final:e.final!==!1,created_at:typeof e.created_at=="string"?e.created_at:""};default:return}}function b(t){let r=0;for(let s=0;s<t.length;s++){let e=t.charCodeAt(s);e<128?r+=1:e<2048?r+=2:e>=55296&&e<=56319&&s+1<t.length&&(t.charCodeAt(s+1)&64512)===56320?(r+=4,s++):r+=3}return r}function l(t,r){if(r<=0)return 0;let s=0;for(let e=0;e<t.length;e++){let i=t.charCodeAt(e),n=3,o=1;if(i<128?n=1:i<2048?n=2:i>=55296&&i<=56319&&e+1<t.length&&(t.charCodeAt(e+1)&64512)===56320&&(n=4,o=2),s+=n,s>=r)return e+o;e+=o-1}return t.length}function v(t,r){return t.slice(l(t,r))}export{m as a,_ as b,b as c,l as d,v as e};
@@ -1,13 +0,0 @@
1
- /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
- import{a as z,f as Q,g as Y,j as Z,k as X,l as ee,o as G,p as te,q as ne}from"./ZZNGA77G.js";import{b as M,c as N,d as T}from"./3AENUHVO.js";import{d as A}from"./RD5JFDGQ.js";import{a as b,b as V,c as _,e as j}from"./JKWWY2LJ.js";var l=class extends Error{kind;code;status;requestId;fields;retryAfter;data;constructor(e,n){super(n.message,n.cause===void 0?void 0:{cause:n.cause}),this.name="BackendError",this.kind=e,this.code=n.code,this.status=n.status??0,this.requestId=n.requestId,this.fields=n.fields,this.retryAfter=n.retryAfter,this.data=n.data}};function oe(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function q(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??qe(e,"request_id"),data:E(e,"data"),cause:t};if(t.code==="network_error")return new l("network",n);if(t.status===401)return new l("unauthorized",n);if(t.status===429)return new l("rateLimited",{...n,retryAfter:Ne(e)??t.retryAfter});let s=Me(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function R(t){return t instanceof V||t instanceof Error&&t.name==="PalbaseError"}function se(t){return Array.isArray(t)&&t.length>0&&t.every(e=>typeof e=="object"&&e!==null&&typeof e.field=="string"&&typeof e.message=="string")}function Me(t){let e=E(E(t,"data"),"fields");if(se(e))return e;let n=E(t,"fields");return se(n)?n:void 0}function Ne(t){return re(t,"retry_after")??re(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function re(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function qe(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var De=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ke=Object.freeze(["adoptSession","analytics","appContext","appVersion","auth","callOnSignOut","cancelCallOnSignOut","configuration","consent","currentSession","flags","installation","module","moduleDirectory","notify","onSessionChange","onSignOut","preferences","realtime","scope","send","socket","storage","storedUserId","telemetry","transport","version","palbe","data","stores","purchases","messaging","notifications","perf","debug","equals","hashCode","toString","self","Type","init","deinit","subscript","then","constructor","__proto__"]),Be=new Set(Ke),Le=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Le.has(t)}function ae(t){return t==="call"||t==="join"||P(t)}function ie(t){return typeof t=="string"&&De.test(t)&&!Be.has(t)&&!P(t)}function de(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function le(t){j(t)}function ce(t){return j(t).origin}var I=class{me;reader;messages=new Map;responses=new Map;order=[];turn=null;goal=null;goalWords=new Set;voiceWords=new Set;voice=null;history=new Map;forkedFrom=null;calls=new Map;taken=[];older=[];oldestLive;olderCursor;olderLeft=!0;loading;chatId;listeners=new Set;enders=new Set;snapshot;told=!1;ended=!1;constructor(e=()=>{},n,s){this.me=e,this.reader=n,this.chatId=s}get hasOlder(){return this.olderLeft}loadOlder(e={}){return this.loading??=this.readOlder(e).finally(()=>this.loading=void 0),this.loading}async readOlder(e){if(!this.olderLeft)return!1;let s={...this.olderCursor!==void 0?{cursor:this.olderCursor}:this.oldestLive!==void 0?{before:this.oldestLive}:{},...e.limit!==void 0?{limit:e.limit}:{},...e.signal?{signal:e.signal}:{}},r;if(e.load)r=await e.load(s);else{let a=this.idFor("loadOlder",e.chatId);if(!this.reader)throw new TypeError("loadOlder: this chat reads its past through the app's way: give load");r=await this.reader.parts(a,s)}if(this.ended)return!1;let o=(r?.parts??[]).map(a=>M(a)).filter(a=>a!==void 0);return this.older=[...o,...this.older],this.olderCursor=r?.nextCursor,this.olderLeft=typeof r?.nextCursor=="string"&&r.nextCursor!=="",this.refold(),this.olderLeft}idFor(e,n){let s=n??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}refold(){this.messages.clear(),this.responses.clear(),this.order.length=0,this.turn=null,this.goal=null,this.goalWords.clear(),this.voiceWords.clear(),this.voice=null,this.history.clear(),this.forkedFrom=null,this.calls.clear();for(let e of this.older)this.fold(e);for(let e of this.taken)this.fold(e);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,n,s=this.subscribe(()=>e?.()),r=()=>e?.();this.enders.add(r);try{for(;;){let o=this.state;if(o!==n){n=o,yield o;continue}if(this.ended)return;await new Promise(a=>e=a)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0;for(let e of[...this.enders])e()}}takePayload(e){let n=M(e);n&&this.take(n)}take(e){if(this.ended)return;this.taken.push(e);let n=e.seq;typeof n=="number"&&n>0&&(this.oldestLive===void 0||n<this.oldestLive)&&(this.oldestLive=n),this.fold(e)&&this.changed()}fold(e){switch(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 n=this.response(e.response_id);n.status=e.status,n.waiting=e.waiting,n.error=e.error,n.end=typeof e.end=="string"?e.end:null,e.user_id!==void 0&&(n.startedBy=e.user_id),e.goal&&(n.goal={goalId:e.goal.goal_id,role:e.goal.role,seq:e.goal.seq}),this.turn=e;break}case"thinking":{let n=this.response(e.response_id);if(e.seq>0){if(n.thought.has(e.seq))return!1;n.thought.add(e.seq)}if(e.unavailable){n.marks.set("thinking:unavailable",{type:"thinking",text_offset:N(n.text),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=n.marks.get(s);r?r.thinking={...r.thinking,text:r.thinking.text+e.text}:n.marks.set(s,{type:"thinking",text_offset:N(n.text),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});break;case"voice":{let n=`${e.voice_id}\0${e.status}`;if(this.voiceWords.has(n))return!1;this.voiceWords.add(n),(e.status==="closed"?this.voice===null||this.voice.voice_id===e.voice_id:!this.voiceWords.has(`${e.voice_id}\0closed`))&&(this.voice=e),this.order.push({type:"voice",event:e});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 n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,T(n.text,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 n=this.response(e.response_id);if(n.runId=e.run_id,n.agent=e.name,n.parentId===null){n.parentId=e.parent_response_id;let s=this.order.findIndex(r=>r.type==="response"&&r.key===e.response_id);s>=0&&this.order.splice(s,1)}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 n=this.goal;if(!n||n.id!==e.goal_id)return;let s={...n,events:[...n.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 n=Fe(e),s=this.messages.get(n),r=e.status==="delivered"||e.status==="failed"?e.status:"pending";this.messages.set(n,{clientId:e.client_id,id:e.id??s?.id??null,text:e.text,author:e.author??null,authorName:e.author_name??"",delivery:e.delivery??"next",status:s?.status==="delivered"?"delivered":r,error:e.error??null,responseId:e.response_id??s?.responseId??null,createdAt:e.created_at??s?.createdAt??"",mine:!1,metadata:e.metadata??s?.metadata??{},history:!1,truncated:!1,kind:e.kind??s?.kind??"text",voice:e.voice?{id:e.voice.id,role:e.voice.role}:s?.voice??null,attachments:e.attachments?ue(e.attachments):s?.attachments??[]}),s||this.place(e,n),this.changed()}said(e){let n=`voice\0${e.id}`,s=this.messages.get(n);this.messages.set(n,{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:n}),this.changed()}place(e,n){let s=e.response_id??null,o=s!==null&&![...this.messages.entries()].some(([a,i])=>a!==n&&i.responseId===s)?this.order.findIndex(a=>a.type==="response"&&a.key===s):-1;o>=0?this.order.splice(o,0,{type:"message",key:n}):this.order.push({type:"message",key:n})}response(e){let n=this.responses.get(e);return n||(n={id:e,status:null,waiting:null,end:null,error:null,text:"",marks:new Map,thought:new Set,runId:null,agent:null,parentId:null,startedBy:void 0,goal:null},this.responses.set(e,n),this.order.push({type:"response",key:e})),n}changed(){this.snapshot=void 0,!this.told&&(this.told=!0,queueMicrotask(()=>{this.told=!1;let e=this.state;for(let n of[...this.listeners])try{n(e)}catch{}}))}build(){let e=this.me(),n=d=>e!==void 0&&d.startedBy===e,s=new Map;for(let d of this.responses.values()){let u=d.parentId!==null?this.responses.get(d.parentId)??d:d;s.set(d.id,We(d,u.startedBy??null,n(u),d.goal??u.goal))}let r=new Map([...this.messages].map(([d,u])=>[d,e!==void 0&&u.author===e?{...u,mine:!0}:u])),o=[...this.history.entries()].sort(([d],[u])=>d-u).flatMap(([d,u])=>u.map((f,m)=>He(f,`${d}:${m}`,e))),a=[...o];for(let d of this.order)d.type==="goal"?a.push({type:"goal",goal:d.event}):d.type==="voice"?a.push({type:"voice",voice:d.event}):d.type==="message"?a.push({type:"message",message:r.get(d.key)}):this.responses.get(d.key).parentId===null&&a.push({type:"response",response:s.get(d.key)});let i=o.flatMap(d=>d.type==="message"?[d.message]:[]),c=o.flatMap(d=>d.type==="response"?[d.response]:[]),p=[...this.calls.values()].filter(d=>s.get(d.response_id)?.mine===!0);return{items:a,messages:[...i,...r.values()],responses:[...c,...s.values()],turn:this.turn,waiting:{approvals:p.filter(d=>d.status==="awaiting_approval"),outputs:p.filter(d=>d.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Je(this.voice,e):null}}};function Je(t,e){return{id:t.voice_id,userId:t.user_id,mine:e!==void 0&&t.user_id===e,delegation:t.delegation,status:t.status,seconds:typeof t.seconds=="number"?t.seconds:null,closeReason:t.close_reason??""}}function ue(t){return t.map((e,n)=>({kind:e.kind,name:e.name,contentType:e.content_type,size:e.size,sha256:e.sha256,position:n,bucket:e.bucket,path:e.path,workspacePath:e.workspace_path??null}))}function Fe(t){return`${t.author??""}\0${t.client_id}`}function We(t,e,n,s){let r=[...t.marks.values()].map((c,p)=>({m:c,i:p,at:T(t.text,Math.max(0,Number(c.text_offset)||0))}));r.sort((c,p)=>c.at-p.at||c.i-p.i);let o=[],a=[],i=0;for(let{m:c,at:p}of r)p>i&&o.push({type:"text",text:t.text.slice(i,p)}),i=Math.max(i,p),c.type==="thinking"?(o.push({type:"thinking",thinking:c.thinking}),a.push(c.thinking)):o.push(c.type==="tool"?{type:"tool",tool:c}:{type:"agent",agent:c});return i<t.text.length&&o.push({type:"text",text:t.text.slice(i)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:o,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:a,goal:s,history:!1,truncated:!1}}function He(t,e,n){let s=t.text_truncated===!0;if(t.role==="user"){let r=t.author??null;return{type:"message",message:{clientId:t.client_id??"",id:t.message_id??null,text:t.text,author:r,authorName:t.author_name??"",delivery:"next",status:"delivered",error:null,responseId:null,createdAt:t.created_at??"",mine:n!==void 0&&r===n,metadata:t.metadata??{},history:!0,truncated:s,kind:"text",voice:null,attachments:ue(t.attachments??[])}}}return{type:"response",response:{id:t.response_id??`history:${e}`,status:"completed",waiting:null,end:"completed",error:null,text:t.text,parts:t.text===""?[]:[{type:"text",text:t.text}],runId:null,agent:null,parentId:null,startedBy:null,mine:!1,thinking:[],goal:null,history:!0,truncated:s}}}var D=[["ApiKeyAuth","userJWT"]];function pe(t){return{async parts(e,n){let s={};n.limit!==void 0&&(s.limit=n.limit),n.cursor!==void 0?s.cursor=n.cursor:n.before!==void 0&&(s.before=n.before);let r=(await t.send({op:"ListChatParts",method:"GET",path:`/ai/chats/${_("ListChatParts","chat_id",e)}/parts`,auth:D,answers:{200:"json"},query:s,signal:n.signal})).data;return r.next_cursor===void 0?{parts:r.parts}:{parts:r.parts,nextCursor:r.next_cursor}},async toolCall(e,n,s){if(typeof n!="string"||n==="")throw new TypeError("chatToolCall: callId is a tool part's call_id");let r=(await t.send({op:"GetChatToolCall",method:"GET",path:`/ai/chats/${_("GetChatToolCall","chat_id",e)}/tool-calls/${_("GetChatToolCall","call_id",n)}`,auth:D,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}},async workspaceFile(e,n,s,r){if(typeof n!="string"||n==="")throw new TypeError("chatWorkspaceFile: path is the file as the workspace's tree names it, relative to its root");let o={path:n};return s!==void 0&&(o.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:D,answers:{200:"raw"},query:o,signal:r})).data.blob()}}}var $=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},he=new WeakMap;async function fe(t,e,n,s={},r=()=>{},o){let{pattern:a,events:i,messages:c,durable:p,chat:d}=Ue(e),u=Ve(a,n),f=he.get(t);f||he.set(t,f=new Map);let m=f,g=m.get(u)??{count:0};m.set(u,g),g.count++;let y=t.channel(u,p&&s.history!==!1?{after:0}:{});if(d&&!g.chat){let h=n.chatId,k=new I(r,o,typeof h=="string"&&h!==""?h:void 0);g.chat=k,g.unchat=y.on("broadcast",w=>{w.event==="chat"&&k.takePayload(w.payload)})}let x=()=>{--g.count>0||(m.delete(u),g.unchat?.(),g.chat?.end(),y.leave())};try{await y.join()}catch{let h=y.state==="refused"?ge(y.refusal,"unavailable"):"socket closed";throw x(),new $(`gateway ${JSON.stringify(u)} was not joined: ${h}`,h)}let C=!1,S=new Set,W=()=>{if(!C){C=!0,Ge();for(let h of[...S])h();x()}},Ge=y.onClosed(W),H=h=>{if(C)return()=>{};let k=y.on("broadcast",v=>{typeof v.event=="string"&&i.has(v.event)&&h(v.event,b(v.payload))}),w=()=>{S.delete(w),k()};return S.add(w),w},U={topic:u,get seq(){return y.logSeq},on(h,k){if(typeof h=="function")return H((w,v)=>h({event:w,payload:v}));if(!i.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no event ${JSON.stringify(String(h))}`);if(typeof k!="function")throw new TypeError(`gateway ${JSON.stringify(a)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return H((w,v)=>{w===h&&k(v)})},off(h){S.has(h)&&h()},async send(h,k){if(!c.has(h))throw new TypeError(`gateway ${JSON.stringify(a)} declares no message ${JSON.stringify(String(h))}`);let w=C?{status:"error",response:{reason:"not joined"}}:await y.push("broadcast",{type:"broadcast",event:h,payload:k});if(w.status==="ok")return b(w.response.reply);let v=ge(w.response,"unavailable");throw new $(`gateway ${JSON.stringify(u)} did not take ${JSON.stringify(h)}: ${v}`,v)},leave:W};return d&&Object.defineProperty(U,"chat",{value:g.chat,enumerable:!0}),U}function Ue(t){let e=typeof t=="object"&&t!==null?t:{},n=s=>Array.isArray(s)&&s.every(r=>typeof r=="string");if(typeof e.pattern!="string"||e.pattern===""||!n(e.events)||!n(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 Ve(t,e){let n=typeof e=="object"&&e!==null?e:{};return t.split(":").map(s=>{if(!(s.startsWith("{")&&s.endsWith("}")&&s.length>2))return s;let r=s.slice(1,-1),o=Object.hasOwn(n,r)?n[r]:void 0;if(typeof o!="string"||o==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(o.includes(":"))throw new TypeError(`gateway ${JSON.stringify(t)}: the value of ${JSON.stringify(r)} is one segment of the channel's name and cannot hold ":"`);return o}).join(":")}function ge(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var ze=3600*1e3,O=new Map;function Qe(t,e,n=!1){let s=`${e.projectId}\0${e.signer}`,r=O.get(s);if(!n&&r&&Date.now()-r.at<ze)return r.list;let o=(async()=>{let a=te(),i;try{i=(await t.send({op:"GetTransitPublicKeys",method:"GET",path:"/secrets/transit/public",query:{nonce:a},auth:[["ApiKeyAuth"]],answers:{200:"json"}})).data}catch(c){throw new l("network",{code:"encryption_keys_unavailable",message:"the project's encryption keys could not be fetched: no encrypted field is sent without them",cause:c})}try{return await ne(i,e.signer,e.projectId,a)}catch(c){throw new l("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:c})}})();return O.set(s,{list:o,at:Date.now()}),o.catch(()=>{O.get(s)?.list===o&&O.delete(s)}),o}async function ye(t,e,n,s,r,o){let i=(await Qe(t,e,o)).keys[0];return Y(i.kid,i.key,Q(e.projectId,n,s,r))}function K(t,e,n,s){return e==null||!s||s.length===0?Promise.resolve(e):G(e,n,s,(r,o)=>Z(t.key,r,o))}function me(t,e,n,s){return e===void 0||!n||n.length===0?Promise.resolve(e):G(e,"/response",n,async(r,o)=>{if(!X(o))throw new l("decode",{code:"field_not_encrypted",message:`${s}: ${r} came plain where the backend's contract says it is encrypted`});try{return await ee(t.key,r,o)}catch(a){throw new l("decode",{code:"field_unopenable",message:`${s}: ${r} does not open with this call's key`,cause:a})}})}function we(t){return t instanceof l&&(t.code==="encryption_key_retired"||t.code==="encryption_key_unknown")}var B=class{pending="";dataLines=[];eventName;consume(e){this.pending+=e.replace(/\r\n/g,`
3
- `);let n=[],s=this.pending.indexOf(`
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&&n.push({event:this.eventName,payload:this.dataLines.join(`
5
- `)}),this.dataLines=[],this.eventName=void 0;else if(!o.startsWith(":")){if(o.startsWith("data:")){let a=o.slice(5);this.dataLines.push(a.startsWith(" ")?a.slice(1):a)}else if(o.startsWith("event:")){let a=o.slice(6);this.eventName=a.startsWith(" ")?a.slice(1):a}}s=this.pending.indexOf(`
6
- `)}return n}};async function*ve(t,e){let n=t.getReader(),s=new TextDecoder,r=new B;try{for(;;){let{done:o,value:a}=await n.read();if(o)break;for(let i of r.consume(s.decode(a,{stream:!0}))){if(i.event==="error")throw new l("network",{code:"stream_failed",message:`stream failed: ${i.payload}`});let c;try{c=JSON.parse(i.payload)}catch{throw new l("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${i.payload.slice(0,120)}`})}yield b(c)}}}finally{e.abort();try{await n.cancel()}catch{}}}var Ye={},be=new WeakMap;function Nt(t,e,n,s,r,o=()=>{}){be.set(t,{project:e,machine:n,storage:s,socket:r,me:o})}var _e=new Map,ke=new WeakMap;function qt(t,e,n,s,r,o){if(!ie(e))throw new l("validation",{code:"reserved_namespace",message:`Cannot register backend ${JSON.stringify(String(e))}: a backend's name is an identifier the client does not keep.`});let a=ce(t);if(!de(n))throw new TypeError(`${JSON.stringify(String(n))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);le(s),Ce(r);for(let i of Object.keys(r))if(ae(i))throw Ee(i);if(o!==void 0)nt(o);else if(xe(r))throw new l("validation",{code:"invalid_namespace_tree",message:`Backend ${e}: its routes carry encrypted fields, and its module holds no project id and signing key to seal them with \u2014 generate it again with palbase apps:sync`});(_e.get(e)??Ze(e)).set(a,{machine:n,url:s,tree:r,...o?{transit:{...o}}:{}})}function Ze(t){let e=new Map;return _e.set(t,e),Object.defineProperty(Ye,t,{configurable:!0,get(){return Xe(this,t,e)}}),e}function Xe(t,e,n){let s=be.get(t);if(!s)return;let r=n.get(s.project);if(!r)throw new TypeError(`pb.${e} is the backend of ${[...n.keys()].join(" and ")}: this client is ${s.project}'s, and its user's session never goes to another project's machine`);let o=ke.get(t);o||ke.set(t,o=new Map);let a=o.get(e);if(a?.registration===r)return a.ns;let i={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine,...r.transit?{transit:{project:s.storage,config:r.transit}}:{}},c=Object.assign({call:(p,d,u)=>dt(i.machine,p,d,u),join:(p,d,u)=>fe(s.socket,p,d,u,s.me,pe(s.storage))},Se(r.tree,i));return o.set(e,{registration:r,ns:c}),c}function Ee(t){return new l("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(t)}: the name is reserved.`})}function L(t){return typeof t.path=="string"&&typeof t.method=="string"}function et(t,e){if(t.pathParams!==void 0){if(!Array.isArray(t.pathParams)||!t.pathParams.every(n=>typeof n=="string"))throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams must be an array of strings.`});for(let n of t.pathParams)if(!t.path.includes(`{${n}}`))throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': pathParams entry '${n}' has no '{${n}}' placeholder in the path.`})}if(t.sse!==void 0&&typeof t.sse!="boolean")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': sse must be a boolean.`});if(t.idempotent!==void 0&&typeof t.idempotent!="boolean")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': idempotent must be a boolean.`});if(t.upload!==void 0&&typeof t.upload!="boolean")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': upload must be a boolean.`});if(t.upload===!0&&(t.method!=="POST"||t.sse===!0))throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an upload endpoint is a POST, and no stream.`});if(t.sse===!0&&t.input==="query")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': an sse endpoint cannot take query input.`});if(t.input!==void 0&&t.input!=="body"&&t.input!=="query"&&t.input!=="none")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': input must be 'body', 'query' or 'none'.`});if(t.encryption!==void 0&&tt(t,e),t.errors!==void 0){for(let[n,s]of Object.entries(t.errors))if(typeof s!="function")throw new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': errors['${n}'] must be a function.`})}}function tt(t,e){let n=t.encryption,s=r=>new l("validation",{code:"invalid_namespace_tree",message:`Descriptor '${e}': encryption ${r}.`});if(typeof n!="object"||n===null)throw s("is { request, response }");for(let[r,o]of[["request",["/body/","/query/"]],["response",["/response"]]]){let a=n[r];if(a!==void 0&&(!Array.isArray(a)||!a.every(i=>typeof i=="string"&&o.some(c=>i===c||i.startsWith(c.endsWith("/")?c:`${c}/`)))))throw s(`${r} is a list of places under ${o.join(" or ")}`)}if(t.upload===!0)throw s("is no upload\u2019s: storage seals nothing");if(t.sse===!0&&(n.response?.length??0)>0)throw s("of a streamed answer is none")}function xe(t){return L(t)?t.encryption!==void 0:Object.values(t).some(e=>xe(e))}function nt(t){if(typeof t!="object"||t===null||typeof t.projectId!="string"||!/^[0-9a-f-]{36}$/.test(t.projectId)||typeof t.signer!="string"||!/^[A-Za-z0-9_-]{43}$/.test(t.signer))throw new l("validation",{code:"invalid_namespace_tree",message:"The backend's encryption is { projectId, signer }: the project's id and its Ed25519 signing key, base64url"})}function Ce(t){if(typeof t!="object"||t===null)throw new l("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});let e=Object.getPrototypeOf(t);if(e!==Object.prototype&&e!==null)throw new l("validation",{code:"invalid_namespace_tree",message:"Namespace tree nodes must be plain objects."});for(let[n,s]of Object.entries(t)){if(P(n))throw Ee(n);typeof s=="object"&&s!==null&&L(s)?(s.method=s.method.toUpperCase(),et(s,s.path)):Ce(s)}}function Se(t,e){if(L(t))return t.upload===!0?async(...s)=>at(e,t,s):async(...s)=>Pe(e.machine(),t,s,e.transit);let n={};for(let[s,r]of Object.entries(t))n[s]=Se(r,e);return n}function J(t){if(t==null)return"";let e=Object.entries(t).filter(([,s])=>s!=null).sort(([s],[r])=>s<r?-1:s>r?1:0);return e.length===0?"":`?${e.map(([s,r])=>{if(typeof r!="string"&&typeof r!="number"&&typeof r!="boolean")throw new l("validation",{code:"invalid_query_value",message:`Query parameter '${s}' must be a string, number, or boolean.`});return`${encodeURIComponent(s)}=${encodeURIComponent(String(r))}`}).join("&")}`}function Te(t,e,n){try{return _(t.path,e,n)}catch(s){if(!R(s)||s.code!=="invalid_path_parameter")throw s;let r=String(n);throw new l("validation",{code:"invalid_path_parameter",message:`${t.path}: ${e} cannot be ${r===""?"empty":JSON.stringify(r)}`})}}function Re(t,e){let n=t.pathParams??[],s=t.path;for(let r=0;r<n.length;r++){let o=e[r];if(typeof o!="string"&&typeof o!="number")throw new l("validation",{code:"missing_path_param",message:`${t.path}: path parameter '${n[r]}' must be a string or number`});s=s.replace(`{${n[r]}}`,Te(t,`path parameter '${n[r]}'`,o))}return s}var st=new Set(["POST","PUT","PATCH","DELETE"]);async function Pe(t,e,n,s){let r=e.pathParams??[],o=Re(e,n),a=o;if(e.input==="none"&&n.length>r.length+1)throw new l("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let i=e.input==="none"?void 0:n[r.length],c=e.input==="none"?r.length:r.length+1,p=n[c],d;if(e.input==="query")a+=J(i);else if(e.input!=="none")if(e.method==="GET"){if(i!==void 0)throw new l("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else d=i;let u={...p?.headers};if(st.has(e.method)&&!Object.keys(u).some(f=>f.toLowerCase()==="idempotency-key")&&(u["Idempotency-Key"]=A()),e.encryption!==void 0){if(!s)throw new l("validation",{code:"encryption_unconfigured",message:`${e.method} ${e.path}: the route carries encrypted fields, and this backend's module holds no key to seal them with`});return rt(t,e,o,i,d,u,p?.signal,r.map((f,m)=>String(n[m])),s)}try{return e.sse===!0?await Ae(t,e,a,d,u,p?.signal):await Oe(t,e,a,d,u,p?.signal)}catch(f){throw F(e,f)}}async function rt(t,e,n,s,r,o,a,i,c){let p=e.encryption;for(let d=0;;d++){let u=await ye(c.project,c.config,e.method,e.path,i,d>0);try{let f=e.input==="query"?n+J(await K(u,s,"/query",p.request)):n,m=await K(u,r,"/body",p.request),g={...o,[z]:u.header};return e.sse===!0?await Ae(t,e,f,m,g,a):b(await me(u,await Oe(t,e,f,m,g,a),p.response,`${e.method} ${e.path}`))}catch(f){if(d===0&&we(f))continue;throw F(e,f)}}}function F(t,e){return t.errors&&oe(e)&&Object.hasOwn(t.errors,e.code)?t.errors[e.code](e):e}var ot=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function at(t,e,n){let s=e.pathParams??[],r=Re(e,n),o=e.input==="none"?s.length:s.length+1;if(n.length>o+2)throw new l("validation",{code:"unexpected_argument",message:`${e.path}: an upload takes its path params, ${e.input==="none"?"":"its input, "}the file and options`});let a=e.input==="none"?void 0:n[s.length],i=n[o],c=n[o+1];if(!(i instanceof Blob))throw new l("validation",{code:"invalid_file",message:`${e.path}: the file is a Blob (a File is one)`});let p=`/storage/upload/${t.name}/${Te(e,"the route",r.slice(1))}`;e.input==="query"&&(p+=J(a));let d=it(e.input==="query"?void 0:a,i),u=d.body.size,f=0,m=g=>{f=g;try{c?.onProgress?.({loaded:g,total:u})}catch{}};c?.onProgress&&m(0);try{let g;try{let y={op:`Upload ${e.path}`,method:"POST",path:p,auth:ot,answers:Ie,body:{kind:"raw",contentType:d.type,value:d.body},signal:c?.signal,...c?.onProgress?{onUploadProgress:x=>m(x)}:{}};g=(await t.storage.send(y)).data}catch(y){throw R(y)?q(y):y}return c?.onProgress&&f<u&&m(u),await je(e,g,c?.signal)}catch(g){throw F(e,g)}}function it(t,e){let n=`Palbase-${A()}`,s=i=>i.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",o=(i,c)=>`--${n}\r
7
- Content-Disposition: form-data; ${i}\r
8
- Content-Type: ${c}\r
9
- \r
10
- `,a=[];return t!==void 0&&a.push(o('name="body"',"application/json"),JSON.stringify(t),`\r
11
- `),a.push(o(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
12
- --${n}--\r
13
- `),{body:new Blob(a),type:`multipart/form-data; boundary=${n}`}}async function dt(t,e,n,s){if(typeof e!="string"||e===""||e==="/")throw new l("validation",{code:"invalid_endpoint_name",message:'Endpoint name must be a non-empty path like "todos/create"'});let r=e.startsWith("/")?e:`/${e}`;return Pe(t(),{method:"POST",path:r},[n,s])}var Ie=Object.fromEntries(Array.from({length:100},(t,e)=>[200+e,"raw"])),lt=[["userJWT"],[]];async function $e(t,e,n,s,r,o){let a={op:`${e.method} ${e.path}`,method:e.method,path:n,auth:lt,answers:Ie,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:o};try{return(await t.send(a)).data}catch(i){throw R(i)?q(i):i}}async function Oe(t,e,n,s,r,o){return je(e,await $e(t,e,n,s,r,o),o)}async function je(t,e,n){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(o){throw n?.aborted?o:new l("network",{code:"network_error",message:`${t.method} ${t.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:o})}if(r!=="")try{return b(JSON.parse(r))}catch(o){throw new l("decode",{code:"invalid_json",message:`${t.method} ${t.path}: the answer is not JSON`,status:e.status,requestId:s,cause:o})}}async function Ae(t,e,n,s,r,o){let a=new AbortController;o&&(o.aborted?a.abort():o.addEventListener("abort",()=>a.abort(),{once:!0}));let i=await $e(t,e,n,s,{accept:"text/event-stream",...r},a.signal);if(!i.body)throw new l("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:i.status});return ve(i.body,a)}export{l as a,oe as b,Ke as c,ie as d,pe as e,$ as f,Ye as g,Nt as h,qt as i};
@@ -1,18 +0,0 @@
1
- /*! palbase 0.14.2 — Palbase SDK License (see LICENSE) */
2
- import{a as q,c as he,d as ye,e as we}from"./3AENUHVO.js";import{a as be}from"./44ULNVPP.js";import{a as pe}from"./OMK2YEDZ.js";import{a as ge,b as fe,c as me}from"./RD5JFDGQ.js";import{b as $,d as ue}from"./JKWWY2LJ.js";async function*ke(e,t={}){let o=e.getReader(),a=new TextDecoder,i="",l="",u=[],h,r=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",r,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:s}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(s,{stream:!0});for(let d=i.indexOf(`
3
- `);d>=0;d=i.indexOf(`
4
- `)){let p=i.slice(0,i[d-1]==="\r"?d-1:d);i=i.slice(d+1),p===""?(l!==""&&(yield h===void 0?{event:l,data:u.join(`
5
- `)}:{event:l,data:u.join(`
6
- `),id:h}),l="",u=[],h=void 0):p.startsWith("event:")?l=ee(p,6):p.startsWith("data:")?u.push(ee(p,5)):p.startsWith("id:")&&(h=ee(p,3))}}}finally{t.signal?.removeEventListener("abort",r);try{await o.cancel()}catch{}}}function ee(e,t){let o=e.slice(t);return o.startsWith(" ")?o.slice(1):o}var ct=/\s/;function W(e,t){for(;t<e.length&&ct.test(e[t]);)t++;return t}function Te(e,t){let o="";for(let a=t+1;a<e.length;a++){let i=e[a];if(i==='"')return{value:o,complete:!0,empty:!1,at:a+1};if(i!=="\\"){o+=i;continue}let l=e[a+1];if(l===void 0)break;if(l==="u"){let u=e.slice(a+2,a+6);if(u.length<4)break;o+=String.fromCharCode(Number.parseInt(u,16)),a+=5;continue}o+={n:`
7
- `,t:" ",r:"\r",b:"\b",f:"\f"}[l]??l,a++}return{value:o,complete:!1,empty:!1,at:e.length}}function te(e,t){t=W(e,t);let o=e[t];if(o===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(o==='"')return Te(e,t);if(o==="{")return lt(e,t);if(o==="[")return ut(e,t);let a=t;for(;a<e.length&&/[-+0-9.A-Za-z]/.test(e[a]);)a++;if(a===e.length)return{value:void 0,complete:!1,empty:!0,at:a};try{return{value:JSON.parse(e.slice(t,a)),complete:!0,empty:!1,at:a}}catch{return{value:void 0,complete:!1,empty:!0,at:e.length}}}function lt(e,t){let o={},a=t+1;for(;;){if(a=W(e,a),e[a]==="}")return{value:o,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(e[a]!=='"')return{value:o,complete:!1,empty:!1,at:e.length};let i=Te(e,a);if(!i.complete)return{value:o,complete:!1,empty:!1,at:e.length};if(a=W(e,i.at),e[a]!==":")return{value:o,complete:!1,empty:!1,at:e.length};let l=te(e,a+1);if(l.empty||Object.defineProperty(o,i.value,{value:l.value,enumerable:!0,writable:!0,configurable:!0}),!l.complete)return{value:o,complete:!1,empty:!1,at:e.length};a=l.at}}function ut(e,t){let o=[],a=t+1;for(;;){if(a=W(e,a),e[a]==="]")return{value:o,complete:!0,empty:!1,at:a+1};if(e[a]===","){a++;continue}if(a>=e.length)return{value:o,complete:!1,empty:!1,at:a};let i=te(e,a);if(i.empty||o.push(i.value),!i.complete)return{value:o,complete:!1,empty:!1,at:e.length};a=i.at}}function ne(e){let t=te(e,0);return t.empty?void 0:t.value}var w=class extends Error{path;constructor(t,o){super(`${t}: ${o}`),this.name="AISchemaError",this.path=t}},pt=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),gt=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),ft=new Set(["object","array","string","integer","number","boolean"]),Se=12,xe=512,mt=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function M(e,t="answer"){if(!mt.test(t))throw new w(t||"(name)","a schema name starts with a letter and holds letters, digits, _ and -, 64 at most");let o=e?.["~standard"];if(!o||o.version!==1||typeof o.validate!="function")throw new w(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!o.jsonSchema||typeof o.jsonSchema.output!="function")throw new w(t,`${o.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=o.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(u){throw new w(t,`the schema has a part JSON Schema cannot say (${u.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(a.type!=="object")throw new w(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let l=re(a,t,0,{properties:0});return{name:t,json:l,async check(u){let h=await o.validate(u);if(h.issues){let r=h.issues[0],n=(r?.path??[]).map(s=>String(typeof s=="object"?s.key:s)).join(".");throw new w(n?`${t}.${n}`:t,`the model's answer does not match the schema: ${r?.message??"invalid"}`)}return h.value}}}function re(e,t,o,a){if(o>Se)throw new w(t,`nests deeper than ${Se} levels, the most the provider takes`);for(let u of["anyOf","oneOf","allOf"])if(u in e)throw new w(t,ht(e[u])??"is a union of several shapes: the provider holds a model to one shape per field \u2014 use an enum, or one object with every field");for(let u of["$ref","$defs","definitions","$dynamicRef"])if(u in e)throw new w(t,"refers to another schema (a recursive or shared type): the provider takes no references \u2014 write the shape out, a bounded number of levels deep");if(e.type==="object"&&("propertyNames"in e||"patternProperties"in e||e.additionalProperties!==void 0&&e.additionalProperties!==!1))throw new w(t,"accepts fields it does not name (a record, passthrough or catchall): the provider holds a model only to the fields named \u2014 name them");for(let u of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(u in e)throw new w(t,`uses ${u}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new w(t,`may be ${e.type.join(" or ")}: one type per field \u2014 a nullable field is not expressible; give it a value that means "none" (an empty string, an enum member)`);let i=e.type;if(typeof i!="string"&&!("enum"in e))throw new w(t,"has no type: the provider holds a model only to a typed value");if(typeof i=="string"&&!ft.has(i))throw new w(t,`is of type ${i}, which the provider does not take`);let l={};for(let[u,h]of Object.entries(e))if(!(u==="$schema"||u==="id"||u==="$id")&&!gt.has(u)){if(!pt.has(u))throw new w(t,`uses ${u}, which the provider cannot hold a model to`);l[u]=h}if("enum"in e&&typeof i!="string"){let u=e.enum,h=new Set(u.map(r=>r===null?"null":typeof r));if(h.size!==1||h.has("null"))throw new w(t,"an enum of values of several types (or with null): one type per field");l.type=h.has("string")?"string":h.has("boolean")?"boolean":"number"}if(i==="object"){let u=e.properties??{},h=Object.keys(u);if(h.length===0)throw new w(t,"is an object with no fields (a record, or any object): the provider holds a model only to named fields \u2014 name them");if(e.additionalProperties!==void 0&&e.additionalProperties!==!1)throw new w(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(a.properties+=h.length,a.properties>xe)throw new w(t,`the schema has more than ${xe} fields in all, the most the provider takes`);let r=new Set(e.required??[]),n={};for(let s of h){if(!r.has(s))throw new w(`${t}.${s}`,'is optional: the provider makes the model write every field \u2014 make it required (give it a value that means "none"), or leave it out of the schema');n[s]=re(u[s],`${t}.${s}`,o+1,a)}l.properties=n,l.required=h,l.additionalProperties=!1}if(i==="array"){let u=e.items;if(!u||typeof u!="object"||Array.isArray(u))throw new w(t,"is a list with no one shape for its items: the provider takes a list of one shape");l.items=re(u,`${t}[]`,o+1,a)}return l}function ht(e){if(Array.isArray(e)&&e.length===2&&e.some(t=>t?.type==="null"))return'is nullable: the provider makes the model write a value of one type \u2014 drop .nullable() and give it a value that means "none"'}var yt=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function F(e){return Array.isArray(e)&&e.length>0&&e.every(Ae)?e.map(ve):Ae(e)?[ve(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function Ae(e){if(typeof e!="object"||e===null)return!1;let t=e;return t.type==="text"?typeof t.text=="string":t.type==="image"?(typeof t.mediaType=="string"||typeof t.media_type=="string")&&(typeof t.data=="string"||t.data instanceof Uint8Array):t.type===void 0&&typeof t.mediaType=="string"&&t.bytes instanceof Uint8Array}function ve(e){if("type"in e&&e.type==="text")return{type:"text",text:e.text};let t="bytes"in e||"mediaType"in e?e.mediaType:e.media_type;if(!yt.has(t))throw new TypeError(`a tool's picture is image/png, image/jpeg, image/webp or image/gif (got ${JSON.stringify(t)})`);let o="bytes"in e?e.bytes:e.data;return{type:"image",media_type:t,data:typeof o=="string"?o:wt(o)}}function wt(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}var Oe=Symbol.for("palbase.ai.deferred"),_e=60,Re=86400;function Me(e={}){let t=e?.expiresInSeconds;if(t!==void 0&&(!Number.isInteger(t)||t<_e||t>Re))throw new TypeError(`ai.deferred: expiresInSeconds is how long the call waits for its answer, ${_e} to ${Re} seconds (got ${String(t)})`);return Object.freeze({[Oe]:!0,...t!==void 0?{expiresInSeconds:t}:{}})}function bt(e){return typeof e=="object"&&e!==null&&e[Oe]===!0}var kt=Symbol.for("palbase.ai.declared"),Tt=Symbol.for("palbase.ai.tool_error"),se=class extends Error{constructor(t){super(t),this.name="ToolError",Object.defineProperty(this,Tt,{value:!0})}};function j(){let e=globalThis,t=e[kt]??={tools:new Map,clientTools:new Map,agents:new Map,repos:new Map,twice:new Set};return t.repos??=new Map,t.clientTools??=new Map,t}function X(e,t,o,a,i=(l,u)=>l===u){let l=e.get(o);l===void 0?e.set(o,a):i(l,a)||j().twice.add(`${t}:${o}`)}var je=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,v=/^[a-z][a-z0-9_-]{0,63}$/;function Be(e,t){if(e===void 0)return{type:"object",properties:{}};let o=e?.["~standard"];if(!o||o.version!==1||typeof o.validate!="function")throw new TypeError(`${t}: input is a Standard Schema \u2014 a zod (4.2+), valibot or arktype object schema`);if(!o.jsonSchema||typeof o.jsonSchema.output!="function")throw new TypeError(`${t}: ${o.vendor}'s schema cannot say itself as JSON Schema; use a version that implements Standard JSON Schema`);let a;try{a=o.jsonSchema.output({target:"draft-2020-12",libraryOptions:{unrepresentable:"throw"}})}catch(h){throw new TypeError(`${t}: the input has a part JSON Schema cannot say (${h.message}) \u2014 a function, a transform, a date: take a string and convert it in run`)}if(a.type!=="object")throw new TypeError(`${t}: a tool takes an object \u2014 wrap the input in z.object({ \u2026 })`);let i=JSON.stringify(a);if(/"\$(ref|defs|dynamicRef)"/.test(i))throw new TypeError(`${t}: the input refers to another schema (a recursive or shared type) \u2014 write the shape out`);let{$schema:l,...u}=a;return u}function De(e){let t=`ai.tool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!je.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);if(typeof e.run!="function")throw new TypeError(`${t}: run(input, ctx) is what a call does`);if(e.machine!==void 0&&!v.test(e.machine))throw new TypeError(`${t}: machine is the name of one of the project's machines`);if(e.input===void 0)throw new TypeError(`${t}: input is what it takes \u2014 z.object({}) for nothing`);let o=Be(e.input,t),a=e.input["~standard"],i=e.run,l={source:"backend",name:e.name,description:e.description,input:e.input,parameters:o,approval:e.approval===!0,...e.machine!==void 0?{machine:e.machine}:{},async call(h,r){let n=await a.validate(h);if(n.issues){let d=n.issues[0],p=(d?.path??[]).map(_=>String(typeof _=="object"?_.key:_)).join(".");return{output:[{type:"text",text:`the input does not match ${e.name}'s schema${p?` at ${p}`:""}: ${d?.message??"invalid"}`}],is_error:!0}}let s=await i(n.value,r);return bt(s)?r.chatId===""?{output:[{type:"text",text:`${e.name} answers later, and a one-shot answer waits for no call: it answers at once, or in a chat`}],is_error:!0}:{deferred:!0,...s.expiresInSeconds!==void 0?{expires_in_seconds:s.expiresInSeconds}:{}}:{output:F(s),is_error:!1}}};Object.freeze(l);let u=j();return u.clientTools.has(l.name)&&u.twice.add(`tool:${l.name}`),X(u.tools,"tool",l.name,l),l}function Ne(e){let t=`ai.clientTool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!je.test(e.name))throw new TypeError(`${t}: name is letters, digits, _ and -, starting with a letter, at most 64`);if(typeof e.description!="string"||e.description.trim()==="")throw new TypeError(`${t}: description says what it does \u2014 the agent reads it to choose`);let o=Object.freeze({source:"client",name:e.name,description:e.description,parameters:Be(e.input,t),approval:e.approval===!0}),a=j();return a.tools.has(o.name)&&a.twice.add(`tool:${o.name}`),X(a.clientTools,"tool",o.name,o,(i,l)=>JSON.stringify(i)===JSON.stringify(l)),o}var St=/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;function Ue(e){let t=e??{};if(typeof t.name!="string"||!v.test(t.name))throw new TypeError("ai.repo: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");if(typeof t.repository!="string"||!St.test(t.repository))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): repository is a GitHub repository, owner/name`);if(typeof t.token!="function")throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): token is the function that gives a token for one clone or push`);if(t.machine!==void 0&&!v.test(t.machine))throw new TypeError(`ai.repo(${JSON.stringify(t.name)}): machine is the project's machine that gives its tokens`);let o=t.token,a={kind:"repo",name:t.name,repository:t.repository,defaultBranch:t.defaultBranch??"main",...t.machine!==void 0?{machine:t.machine}:{},async token(i){return await o(i)}};return X(j().repos,"repo",t.name,a),a}function Ge(e){if(typeof e!="function")throw new TypeError("ai.repoTokens(give): give is the function that gives a token for one clone or push of a repository put by name");let t=j();t.repoTokens===void 0?t.repoTokens=e:t.repoTokens!==e&&t.twice.add("repoTokens")}function Le(e,t,o={}){let a=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!v.test(e))throw new TypeError(`${a}: name is lowercase letters, digits, _ and -, starting with a letter, at most 64`);if(typeof t!="function")throw new TypeError(`${a}: the agent is a function of the turn's context that returns its definition`);let i=o??{};if(i.machine!==void 0&&!v.test(i.machine))throw new TypeError(`${a}: machine is the name of one of the project's machines`);let l=i.description===void 0?void 0:Je(i.description,a),u={kind:"agent",name:e,...l!==void 0?{description:l}:{},...i.machine!==void 0?{machine:i.machine}:{},async resolve(h){let r=await t(h),n=Z(r,`${a} for chat ${h.chatId}`);if(n.backend!==void 0)throw new TypeError(`${a}: a backend's agent is its definition \u2014 it names no other backend`);return n.description===void 0&&l!==void 0&&(n.description=l),{definition:n,tools:xt(r)}}};return Object.freeze(u),X(j().agents,"agent",e,u),u}function z(e){return typeof e=="object"&&e!==null&&e.kind==="agent"?e:void 0}function xt(e){return[...e.tools??[],...(e.subagents??[]).flatMap(o=>o.tools??[])].filter(o=>o.source==="backend")}var Ce=["web.search","web.fetch","workspace.fetch_archive"];function K(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a tool is ai.tool(\u2026), ai.clientTool(\u2026), { source: 'https', name }, { source: 'mcp', name } or { source: 'platform', name }`);let o=e.approval===!0?{approval:!0}:{};switch(e.source){case"backend":if(typeof e.call!="function")throw new TypeError(`${t}: a backend tool is made with ai.tool({ name, description, input, run })`);return{source:"backend",name:e.name,description:e.description,parameters:e.parameters,...o,...e.machine!==void 0?{machine:e.machine}:{}};case"client":return{source:"client",name:e.name,description:e.description,parameters:e.parameters,...o};case"https":if(typeof e.name!="string"||!v.test(e.name))throw new TypeError(`${t}: { source: 'https', name } names an endpoint the project put`);return{source:"https",name:e.name,...o};case"mcp":if(typeof e.name!="string"||!v.test(e.name))throw new TypeError(`${t}: { source: 'mcp', name } names an MCP server the project put`);return{source:"mcp",name:e.name,...o,...e.only!==void 0?{only:[...e.only]}:{}};case"platform":{let a=Object.keys(e).filter(i=>i!=="source"&&i!=="name");if(typeof e.name!="string"||!Ce.includes(e.name))throw new TypeError(`${t}: { source: 'platform', name } names one of the platform's tools: ${Ce.join(", ")}`);if(a.length>0)throw new TypeError(`${t}: the platform's ${e.name} is given by its name alone (not ${a.join(", ")})`);return{source:"platform",name:e.name}}default:throw new TypeError(`${t}: a tool's source is backend, client, https, mcp or platform (got ${JSON.stringify(e.source)})`)}}var Ee=1e4,Pe=["none","minimal","low","medium","high","xhigh","max"],At=1e8,vt=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/,Ie=1024;function Je(e,t){if(typeof e!="string"||e.trim()===""||e.length>Ie)throw new TypeError(`${t}: description says what the agent is for, in a sentence or two (${Ie} characters at most)`);return e}function _t(e,t){let o=e?.prepared;if(o!==void 0&&typeof o=="object"&&o!==null&&typeof o.json=="object")return o.json;if(typeof e!="object"||e===null||!("~standard"in e))throw new TypeError(`${t}: output is the shape of its one-shot answers \u2014 a zod (valibot, arktype) object schema, or ai.schema(name, schema)`);return M(e,"output").json}function ae(e,t){if(!Number.isInteger(e)||e<1||e>Ee)throw new TypeError(`${t}: maxToolCalls is a whole number, 1 to ${Ee} (got ${String(e)})`);return e}function $e(e,t){let o={};if(e.effort!==void 0){if(typeof e.effort!="string"||!Pe.includes(e.effort))throw new TypeError(`${t}: effort is one of ${Pe.join(", ")} \u2014 which a model takes is its catalogue entry's (ai.models())`);o.effort=e.effort}if(e.contextWindow!==void 0){if(!Number.isInteger(e.contextWindow)||e.contextWindow<1||e.contextWindow>At)throw new TypeError(`${t}: contextWindow is a number of tokens (got ${String(e.contextWindow)})`);o.context_window=e.contextWindow}if(e.thinking!==void 0){if(e.thinking!=="visible"&&e.thinking!=="hidden")throw new TypeError(`${t}: thinking is visible (the model's reasoning in the chat's stream) or hidden`);o.thinking=e.thinking}return o}function Z(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { description, instructions, model, tools, subagents, maxToolCalls, effort, contextWindow, thinking, language, output }`);let o={};if(e.description!==void 0&&(o.description=Je(e.description,t)),e.instructions!==void 0&&(o.instructions=e.instructions),e.model!==void 0&&(o.model=e.model),e.maxToolCalls!==void 0&&(o.max_tool_calls=ae(e.maxToolCalls,t)),Object.assign(o,$e(e,t)),e.language!==void 0){if(typeof e.language!="string"||e.language.length>35||!vt.test(e.language))throw new TypeError(`${t}: language is the language of the person the turn works for, as a BCP 47 tag (tr, en-GB)`);o.language=e.language}if(e.output!==void 0&&(o.output=_t(e.output,t)),e.tools!==void 0&&(o.tools=e.tools.map(a=>K(a,t))),e.subagents!==void 0){for(let a of e.subagents){let i=(a?.tools??[]).find(l=>l?.source==="platform");if(i)throw new TypeError(`${t} subagent ${a.name}: the platform's ${i.name} is the agent's tool \u2014 its subagents work with the agent's`)}o.subagents=e.subagents.map(a=>({name:a.name,description:a.description,...a.instructions!==void 0?{instructions:a.instructions}:{},...a.model!==void 0?{model:a.model}:{},...a.required!==void 0?{required:a.required}:{},...$e(a,`${t} subagent ${a.name}`),...a.tools!==void 0?{tools:a.tools.map(i=>K(i,`${t} subagent ${a.name}`))}:{}}))}return o}function B(e,t){if(typeof e!="string"||!v.test(e))throw new TypeError(`${t}: an agent's name is lowercase letters, digits, _ and -, starting with a letter, at most 64 (got ${JSON.stringify(e)})`);return e}function ze(e,t){if(!Number.isSafeInteger(e)||e<1)throw new TypeError(`${t}: revision is the draft's revision as it was read (Agent's revision), a whole number from 1 (got ${String(e)})`);return e}function Ve(e,t){let o={approve:e};return t.reason!==void 0&&(o.reason=t.reason),t.as!==void 0&&(o.as=t.as),o}var Rt=/^[a-z][a-z0-9-]{1,62}$/,qe=4,We=8;function Ct(e){let t={},o=(a,i)=>{if(typeof a?.bucket!="string"||!Rt.test(a.bucket))throw new TypeError(`chats.send: ${i}'s bucket is one of the project's buckets, by its name`);if(typeof a.path!="string"||a.path===""||a.path.length>1024)throw new TypeError(`chats.send: ${i}'s path is its path in the bucket (1024 characters at most)`);return{bucket:a.bucket,path:a.path}};if(e.images!==void 0){if(!Array.isArray(e.images)||e.images.length>qe)throw new TypeError(`chats.send: images are ${qe} at most \u2014 as many as the model is shown at once`);t.images=e.images.map((a,i)=>o(a,`images[${i}]`))}if(e.files!==void 0){if(!Array.isArray(e.files)||e.files.length>We)throw new TypeError(`chats.send: files are ${We} at most`);t.files=e.files.map((a,i)=>{let l=o(a,`files[${i}]`);if(a.filename!==void 0){if(typeof a.filename!="string"||a.filename===""||a.filename.length>255)throw new TypeError(`chats.send: files[${i}].filename is its name in the workspace (255 characters at most)`);l.filename=a.filename}if(a.contentType!==void 0){if(typeof a.contentType!="string"||a.contentType===""||a.contentType.length>128)throw new TypeError(`chats.send: files[${i}].contentType is a media type (application/pdf)`);l.content_type=a.contentType}return l})}return t}function H(e){return{id:e.id,chatId:e.chat_id,userId:e.user_id,delegation:e.delegation,status:e.status,seconds:e.seconds,startedAt:e.started_at,closedAt:e.closed_at,closeReason:e.close_reason??""}}var Et=["speak","tell","know","instruct"];function Fe(){return"cm_"+crypto.randomUUID()}async function Y(e,t,o=4){for(let a=1;;a++)try{return await e()}catch(i){if(a>=o||!(i instanceof $)||i.status===429||t?.aborted)throw i;let l=me(i,a,30);if(l===void 0)throw i;await new Promise((u,h)=>{let r=setTimeout(u,l*1e3);t?.addEventListener("abort",()=>(clearTimeout(r),h(t.reason)),{once:!0})})}}function oe(e){return{id:e.id,chatId:e.chat_id,objective:e.objective,rubric:e.rubric,status:e.status,stopCode:e.stop_code,stopReason:e.stop_reason,phase:e.phase,setBy:e.set_by,maxTurns:e.max_turns,budget:e.budget===null?null:{maxCostUsd:e.budget.max_cost_usd},usage:{turns:e.usage.turns,verifications:e.usage.verifications,costUsd:e.usage.cost_usd,costIsLowerBound:e.usage.cost_is_lower_bound,activeSeconds:e.usage.active_seconds},achievedAt:e.achieved_at,createdAt:e.created_at,updatedAt:e.updated_at}}var Ke=e=>({user_id:e.userId,...e.name!==void 0?{name:e.name}:{},...e.email!==void 0?{email:e.email}:{},...e.owner!==void 0?{owner:e.owner}:{}}),Pt=/^[A-Za-z0-9-]{1,64}$/,Xe=16;function It(e){if(!Array.isArray(e)||e.length>Xe)throw new TypeError(`chats.create: workspace.trailers are ${Xe} at most, each { key, value }`);return e.map((t,o)=>{if(typeof t?.key!="string"||!Pt.test(t.key))throw new TypeError(`chats.create: workspace.trailers[${o}].key is a git trailer's token: letters, digits and -, at most 64 (PalCore-Task, Co-authored-by)`);if(typeof t.value!="string"||t.value===""||/[\r\n]/.test(t.value)||new TextEncoder().encode(t.value).byteLength>512)throw new TypeError(`chats.create: workspace.trailers[${o}].value is one line of 512 bytes at most`);return{key:t.key,value:t.value}})}function $t(e){return{runId:e.run_id,responseId:e.response_id,parentRunId:e.parent_run_id??null,subagent:e.subagent,model:e.model,state:e.state,inputTokens:e.input_tokens,outputTokens:e.output_tokens,cacheReadTokens:e.cache_read_tokens,cacheWriteTokens:e.cache_write_tokens,costNanoUsd:e.cost_nano_usd,usd:e.usd,unpriced:e.unpriced}}function Ze(e){return{clients:e.clients,userMessagesPerMinute:e.user_messages_per_minute,historyLimitBytes:e.history_limit_bytes,historyBytes:e.history_bytes}}function Ot(e){return new Proxy(e,{get(t,o){let a=t[o];return typeof a=="function"?(...i)=>q(a.apply(t,i)):a}})}function He(e){let t=Ot(e),o={async create(r){let n=typeof r.agent=="string"||r.agent===void 0?r.agent:z(r.agent)?.name;if(r.agent!==void 0&&n===void 0)throw new TypeError("chats.create: agent is one of the project's agents by name (name@N for a version), or a backend's ai.agent");if(n===void 0&&r.definition===void 0)throw new TypeError("chats.create: an agent (one of the project's, by name) or a definition of the chat's own");let s={agent:n??"assistant"};return r.definition!==void 0&&(s.definition=Z(r.definition,"chats.create")),r.title!==void 0&&(s.title=r.title),r.metadata!==void 0&&(s.metadata=r.metadata),r.members!==void 0&&(s.members=r.members.map(Ke)),r.workspace!==void 0&&(s.workspace={repos:r.workspace.repos.map(d=>({repo:typeof d.repo=="string"?d.repo:d.repo.name,...d.branch!==void 0?{branch:d.branch}:{}})),...r.workspace.autoPush!==void 0?{auto_push:r.workspace.autoPush}:{},...r.workspace.trailers!==void 0?{trailers:It(r.workspace.trailers)}:{}}),(await t.createChat({body:s,signal:r.signal})).data},async get(r,n={}){return(await t.getChat({path:{chat_id:r},signal:n.signal})).data},async list(r={}){let n=r.metadata===void 0?void 0:Object.entries(r.metadata).map(([d,p])=>`${d}:${p}`),s=(await t.listChats({query:{member:r.member,limit:r.limit,cursor:r.cursor,metadata:n},signal:r.signal})).data;return s.next_cursor===void 0?{chats:s.chats}:{chats:s.chats,nextCursor:s.next_cursor}},async delete(r){await t.deleteChat({path:{chat_id:r}})},members:{async put(r,n,s){let d={};return s.name!==void 0&&(d.name=s.name),s.email!==void 0&&(d.email=s.email),s.owner!==void 0&&(d.owner=s.owner),(await t.putChatMember({path:{chat_id:r,user_id:n},body:d})).data},async delete(r,n){await t.deleteChatMember({path:{chat_id:r,user_id:n}})}},async send(r,n){let s={client_id:n.clientId??Fe(),text:n.text};return n.delivery!==void 0&&(s.delivery=n.delivery),n.as!==void 0&&(s.as=n.as),n.budget!==void 0&&(s.budget={max_cost_usd:n.budget.maxCostUsd}),n.metadata!==void 0&&(s.metadata=n.metadata),n.context!==void 0&&(s.context=n.context),Object.assign(s,Ct(n)),Y(async()=>(await t.sendChatMessage({path:{chat_id:r},body:s,signal:n.signal})).data,n.signal)},async turnCost(r,n,s={}){let d=(await t.getChatTurnCost({path:{chat_id:r,response_id:n},signal:s.signal})).data;return{chatId:d.chat_id,responseId:d.response_id,inputTokens:d.input_tokens,outputTokens:d.output_tokens,costNanoUsd:d.cost_nano_usd,usd:d.usd,unpriced:d.unpriced,final:d.final,runs:d.runs.map($t)}},async artifacts(r,n,s={}){return(await t.listChatTurnArtifacts({path:{chat_id:r,response_id:n},signal:s.signal})).data.artifacts.map(p=>({id:p.id,mediaType:p.media_type,...p.logical_type?{logicalType:p.logical_type}:{},sizeBytes:p.size_bytes,checksum:p.checksum,createdAt:p.created_at}))},async artifact(r,n,s,d={}){return(await t.getChatTurnArtifact({path:{chat_id:r,response_id:n,artifact_id:s},signal:d.signal})).data},async messages(r,n={}){let s=(await t.listChatMessages({path:{chat_id:r},query:{limit:n.limit,cursor:n.cursor},signal:n.signal})).data;return s.next_cursor===void 0?{messages:s.messages}:{messages:s.messages,nextCursor:s.next_cursor}},async parts(r,n={}){if(n.cursor!==void 0&&n.before!==void 0)throw new TypeError("chats.parts: cursor (where a page left off) or before (the oldest part the app's channel holds, by its id), not both");if(n.before!==void 0&&(!Number.isSafeInteger(n.before)||n.before<1))throw new TypeError(`chats.parts: before is a part's id \u2014 its journal sequence, a whole number from 1 (got ${String(n.before)})`);let s=(await t.listChatParts({path:{chat_id:r},query:{limit:n.limit,cursor:n.cursor,before:n.before},signal:n.signal})).data,d=s.parts.map(p=>({type:p.type,...p.id!==void 0?{id:p.id}:{},partId:p.part_id,data:p.data}));return s.next_cursor===void 0?{parts:d}:{parts:d,nextCursor:s.next_cursor}},async toolCall(r,n,s={}){let d=(await t.getChatToolCall({path:{chat_id:r,call_id:n},signal:s.signal})).data;return{callId:d.call_id,name:d.name,status:d.status,runId:d.run_id,responseId:d.response_id,input:d.input,output:d.output,outputBytes:d.output_bytes,imageCount:d.image_count,isError:d.is_error}},async toolCalls(r,n){if(typeof n?.turn!="string"||n.turn==="")throw new TypeError("chats.toolCalls: turn is the turn's responseId \u2014 a message's, or a turn's or an agent part's");let s=(await t.listTurnToolCalls({path:{chat_id:r},query:{turn:n.turn,limit:n.limit,cursor:n.cursor},signal:n.signal})).data,d=s.tool_calls.map(p=>({callId:p.call_id,name:p.name,state:p.state,createdAt:p.created_at,updatedAt:p.updated_at,arguments:p.arguments,...p.result!==void 0?{result:p.result}:{}}));return s.next_cursor===void 0?{toolCalls:d}:{toolCalls:d,nextCursor:s.next_cursor}},workspace:{async file(r,n,s={}){if(typeof n!="string"||n==="")throw new TypeError("chats.workspace.file: path is the file as the workspace's tree names it (repo/output/app/App.zip)");return(await t.getChatWorkspaceFile({path:{chat_id:r},query:{path:n,...s.manifest!==void 0?{manifest:s.manifest}:{}},signal:s.signal})).data},async addRepo(r,n){let s=typeof n?.repo=="string"?n.repo:n?.repo?.name;if(typeof s!="string"||!v.test(s))throw new TypeError("chats.workspace.addRepo: repo is the project's name for the repository (ai.repos.put), or its ai.repo");let d={repo:s};return n.branch!==void 0&&(d.branch=n.branch),(await t.addChatWorkspaceRepo({path:{chat_id:r},body:d,signal:n.signal})).data}},events(r){if(typeof r!="string"||!/^chat_[0-9a-f]{32}$/.test(r))throw new TypeError(`chats.events(id): a chat's id, chat_ and 32 hex digits (got ${JSON.stringify(r)})`);return Object.freeze({kind:"ai.chat",chatId:r,async pipe(n,s={}){await t.putChatPipe({path:{chat_id:r},body:{topic:n},signal:s.signal})},async unpipe(n={}){await t.deleteChatPipe({path:{chat_id:r},signal:n.signal})}})},async stop(r,n={}){return(await t.stopChat({path:{chat_id:r},...n.as!==void 0?{body:{as:n.as}}:{},signal:n.signal})).data.stopped},async approve(r,n,s={}){return(await t.decideChatApproval({path:{chat_id:r,approval_id:n},body:Ve(!0,s)})).data},async deny(r,n,s={}){return(await t.decideChatApproval({path:{chat_id:r,approval_id:n},body:Ve(!1,s)})).data},async answer(r,n,s,d={}){let p={output:F(s)};d.isError&&(p.is_error=!0),d.as!==void 0&&(p.as=d.as);try{return await Y(()=>t.answerChatToolCall({path:{chat_id:r,call_id:n},body:p})),!0}catch(_){if(_ instanceof $&&_.status===409)return!1;throw _}},async sendToSubagent(r,n,s,d={}){let p={client_id:d.clientId??Fe(),text:s};d.as!==void 0&&(p.as=d.as);let _=await Y(async()=>(await t.sendSubagentMessage({path:{chat_id:r,run_id:n},body:p})).data);return{runId:_.run_id,clientId:_.client_id}},async stopSubagent(r,n,s={}){return{runId:(await Y(async()=>(await t.stopSubagent({path:{chat_id:r,run_id:n},body:s.as!==void 0?{as:s.as}:{},signal:s.signal})).data,s.signal)).run_id}},async fork(r,n){if(typeof n?.beforeMessage!="string"||n.beforeMessage==="")throw new TypeError("chats.fork: beforeMessage is the id of the message the fork is cut before (a message's id, msg_\u2026)");let s={before_message:n.beforeMessage};return n.title!==void 0&&(s.title=n.title),n.members!==void 0&&(s.members=n.members.map(Ke)),(await t.forkChat({path:{chat_id:r},body:s,signal:n.signal})).data},goal:{async set(r,n){let s={objective:n.objective};return n.rubric!==void 0&&(s.rubric=n.rubric),n.maxTurns!==void 0&&(s.max_turns=n.maxTurns),n.budget!==void 0&&(s.budget={max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(s.as=n.as),oe((await t.setChatGoal({path:{chat_id:r},body:s,signal:n.signal})).data)},async get(r,n={}){return oe((await t.getChatGoal({path:{chat_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)},async update(r,n){let s={};return n.status!==void 0&&(s.status=n.status),n.reason!==void 0&&(s.reason=n.reason),n.objective!==void 0&&(s.objective=n.objective),n.rubric!==void 0&&(s.rubric=n.rubric),n.maxTurns!==void 0&&(s.max_turns=n.maxTurns),n.budget!==void 0&&(s.budget=n.budget===null?null:{max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(s.as=n.as),oe((await t.updateChatGoal({path:{chat_id:r},body:s,signal:n.signal})).data)},async clear(r,n={}){await t.clearChatGoal({path:{chat_id:r},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})}},voice:{async start(r,n){if(typeof n?.sdp!="string"||!n.sdp.startsWith("v="))throw new TypeError("chats.voice.start: sdp is the app's WebRTC offer (an SDP, v=0 \u2026): its peer connection's localDescription.sdp");if(n.delegation!==void 0&&n.delegation!=="chat"&&n.delegation!=="events")throw new TypeError("chats.voice.start: delegation is chat (a turn of the chat) or events (ai.voice.delegated)");let s={sdp:n.sdp};n.voice!==void 0&&(s.voice=n.voice),n.delegation!==void 0&&(s.delegation=n.delegation),n.as!==void 0&&(s.as=n.as),n.instructions!==void 0&&(s.instructions=n.instructions),n.context!==void 0&&(s.context=n.context);let d=(await t.startChatVoice({path:{chat_id:r},body:s,signal:n.signal})).data;if(typeof d.sdp!="string"||d.sdp==="")throw new $({op:"startChatVoice",status:502,code:"no_answer",message:"the voice was started but its WebRTC answer was not given"});return{...H(d),sdp:d.sdp}},async get(r,n,s={}){return H((await t.getChatVoice({path:{chat_id:r,voice_id:n},query:s.as!==void 0?{as:s.as}:void 0,signal:s.signal})).data)},async command(r,n,s){if(!Et.includes(s?.type))throw new TypeError("chats.voice.command: type is speak (say this exactly), tell (say it in your own words), know (keep it in mind) or instruct (behave so)");if(typeof s.text!="string"||s.text==="")throw new TypeError("chats.voice.command: text is what the voice is given");if(s.delegationId!==void 0&&s.type!=="speak"&&s.type!=="tell")throw new TypeError("chats.voice.command: delegationId names the request a speak or a tell answers");if(s.interrupt!==void 0&&(typeof s.interrupt!="boolean"||s.type!=="speak"))throw new TypeError("chats.voice.command: interrupt is a speak's: it cuts what the voice is saying");let d={type:s.type,text:s.text};return s.delegationId!==void 0&&(d.delegation_id=s.delegationId),s.interrupt===!0&&(d.interrupt=!0),s.as!==void 0&&(d.as=s.as),H((await t.commandChatVoice({path:{chat_id:r,voice_id:n},body:d,signal:s.signal})).data)},async close(r,n,s={}){return H((await t.closeChatVoice({path:{chat_id:r,voice_id:n},query:s.as!==void 0?{as:s.as}:void 0,signal:s.signal})).data)}}},a={async list(r={}){return(await t.listAgents({signal:r.signal})).data.agents},async get(r,n={}){return(await t.getAgent({path:{name:B(r,"agents.get")},signal:n.signal})).data},async saveDraft(r,n,s={}){let d=`agents.saveDraft(${JSON.stringify(r)})`;if(B(r,"agents.saveDraft"),z(n))throw new TypeError(`${d}: a backend's ai.agent is its code's \u2014 its build's contract names it, and its chats ask its machine; it has no draft to save`);if(n===void 0)throw new TypeError(`${d}: its definition \u2014 { instructions, model, tools, \u2026 }`);let p=Z(n,d);return(await t.putAgent({path:{name:r},...s.revision!==void 0?{query:{revision:ze(s.revision,d)}}:{},body:p,signal:s.signal})).data},async publish(r,n={}){let s=`agents.publish(${JSON.stringify(r)})`;B(r,"agents.publish");let d=n.revision!==void 0?{revision:ze(n.revision,s)}:{};return(await t.publishAgent({path:{name:r},body:d,signal:n.signal})).data},async rollback(r,n,s={}){if(B(r,"agents.rollback"),!Number.isSafeInteger(n)||n<1)throw new TypeError(`agents.rollback(${JSON.stringify(r)}): version is one it had \u2014 a whole number from 1 (got ${String(n)})`);return(await t.rollbackAgent({path:{name:r},body:{version:n},signal:s.signal})).data},async versions(r,n={}){B(r,"agents.versions");let s=(await t.listAgentVersions({path:{name:r},query:{limit:n.limit,cursor:n.cursor},signal:n.signal})).data;return s.next_cursor===void 0?{versions:s.versions,publishedVersion:s.published_version}:{versions:s.versions,publishedVersion:s.published_version,nextCursor:s.next_cursor}},async delete(r,n={}){await t.deleteAgent({path:{name:B(r,"agents.delete")},signal:n.signal})},async tools(r={}){return(await t.listTools({signal:r.signal})).data.tools}},i={async put(r,n){let s={kind:n.kind,url:n.url};return n.description!==void 0&&(s.description=n.description),n.parameters!==void 0&&(s.parameters=n.parameters),n.approval!==void 0&&(s.approval=n.approval),(await t.putEndpoint({path:{name:r},body:s})).data},async list(){return(await t.listEndpoints({})).data.endpoints},async delete(r){await t.deleteEndpoint({path:{name:r}})}},l={async get(){return Ze((await t.getSettings({})).data)},async put(r){let n={};return r.clients!==void 0&&(n.clients=r.clients),r.userMessagesPerMinute!==void 0&&(n.user_messages_per_minute=r.userMessagesPerMinute),r.historyLimitBytes!==void 0&&(n.history_limit_bytes=r.historyLimitBytes),Ze((await t.putSettings({body:n})).data)}},u=r=>({name:r.name,repository:r.repository,defaultBranch:r.default_branch,backend:r.backend,createdAt:r.created_at});return{chats:o,agents:a,endpoints:i,settings:l,repos:{async put(r,n){let s=typeof r=="string"?r:r.name;if(typeof s!="string"||!v.test(s))throw new TypeError("repos.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");let d=typeof r=="string"?{repository:n?.repository??"",...n?.defaultBranch?{default_branch:n.defaultBranch}:{},...n?.backend?{backend:n.backend}:{}}:{repository:r.repository,default_branch:r.defaultBranch,...r.machine?{backend:r.machine}:{}};return u((await t.putRepo({path:{name:s},body:d})).data)},async list(r={}){let n=(await t.listRepos({query:{limit:r.limit,cursor:r.cursor}})).data,s=n.repos.map(u);return n.next_cursor===void 0?{repos:s}:{repos:s,nextCursor:n.next_cursor}},async delete(r){await t.deleteRepo({path:{name:r}})}}}}var Mt=/^pb_[a-z0-9]+_s/;function Ye(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function ie(){return"ai_"+crypto.randomUUID()}function de(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:M(t,"answer")}}var Qe=4,jt=/^[a-z][a-z0-9-]{1,62}$/,et=["image/png","image/jpeg","image/webp","image/gif"],tt=5<<20,nt=6<<20;function ot(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}function Bt(e){return e.length%4!==0||!/^[A-Za-z0-9+/]*={0,2}$/.test(e)?-1:e.length/4*3-(e.endsWith("==")?2:e.endsWith("=")?1:0)}function Dt(e){if(!Array.isArray(e))throw new TypeError("images is a list of { bucket, path } (a file of the project's storage), { url } (an https address) or { mediaType, data } (its bytes)");if(e.length>Qe)throw new TypeError(`a question takes ${Qe} pictures at most (got ${e.length})`);let t=0;return e.map((o,a)=>{let i=o??{};if("bytes"in i||o instanceof Uint8Array)throw new TypeError(`images[${a}]: a picture's bytes are { mediaType, data } \u2014 or, in the project's storage, { bucket, path }`);if("data"in i||"mediaType"in i){if(i.bucket!==void 0||i.path!==void 0||i.url!==void 0)throw new TypeError(`images[${a}] is { bucket, path }, { url } or { mediaType, data }: one of them`);if(typeof i.mediaType!="string"||!et.includes(i.mediaType))throw new TypeError(`images[${a}].mediaType is the picture's type: ${et.join(", ")}`);let l=i.data instanceof Uint8Array?ot(i.data):i.data,u=typeof l=="string"?Bt(l):-1;if(u<0)throw new TypeError(`images[${a}].data is the picture's bytes: base64, or a Uint8Array`);if(u===0||u>tt)throw new TypeError(`images[${a}] is ${u} bytes: a picture given by its bytes is 1 byte to ${tt>>20} MiB`);if(t+=u,t>nt)throw new TypeError(`the pictures given by their bytes are ${nt>>20} MiB at most together: put a larger one in the project's storage and give { bucket, path }`);return{media_type:i.mediaType,data:l}}if(typeof i.url=="string"){if(i.bucket!==void 0||i.path!==void 0)throw new TypeError(`images[${a}] is { bucket, path } or { url }, not both`);let l;try{l=new URL(i.url)}catch{throw new TypeError(`images[${a}].url is not an address: ${JSON.stringify(i.url.slice(0,80))}`)}if(l.protocol!=="https:"||i.url.length>2048)throw new TypeError(`images[${a}].url is an https address of 2048 characters at most`);return{url:i.url}}if(typeof i.bucket!="string"||!jt.test(i.bucket)||typeof i.path!="string"||i.path==="")throw new TypeError(`images[${a}] is { bucket, path } \u2014 a file of the project's storage \u2014 { url } or { mediaType, data }`);return{bucket:i.bucket,path:i.path}})}var Nt=/^[a-z][a-z0-9_-]{0,63}(@[1-9][0-9]{0,8})?$/;function it(e){let t=typeof e=="string"?e:z(e)?.name;if(typeof t!="string"||!Nt.test(t))throw new TypeError(`agent is one of the project's agents by name (support), name@N for its version N (support@3), or a backend's ai.agent (got ${JSON.stringify(typeof e=="string"?e:typeof e)})`);return t}function V(e,t={},o){if(e.prompt===void 0&&e.messages===void 0)throw new TypeError("ask a model something: prompt, or messages");let a={...t};if(e.agent!==void 0&&(a.agent=it(e.agent)),e.prompt!==void 0&&(a.input=e.prompt),e.messages!==void 0&&(a.messages=e.messages),e.instructions!==void 0&&(a.instructions=e.instructions),e.model!==void 0&&(a.model=e.model),e.metadata!==void 0&&(a.metadata=e.metadata),e.images!==void 0&&(a.images=Dt(e.images)),e.tools!==void 0&&(a.tools=e.tools.map((i,l)=>{if(i?.source==="client")throw new TypeError(`tools[${l}]: ${i.name} is a client tool \u2014 an app answers it, in a chat; a one-shot answer has no app to wait for`);if(i?.source==="platform")throw new TypeError(`tools[${l}]: the platform's ${i.name} is a chat's agent's tool \u2014 a one-shot answer is given none`);let u=K(i,`tools[${l}]`);return u.source==="backend"&&u.machine===void 0&&o!==void 0&&(u.machine=o),u})),e.maxToolCalls!==void 0){if(!e.tools?.length)throw new TypeError("maxToolCalls bounds the calls of the tools given: give tools");a.max_tool_calls=ae(e.maxToolCalls,"ask")}return a}function rt(e,t){if(e.output===null||e.output===void 0)throw new w(t,"the answer is text, not a document: the agent has no output (the shape of its one-shot answers) \u2014 give it one, give generate a schema, or ask() it");return e.output}var E=class extends Error{code;response;constructor(t){super(t.error?.message??`the response ended ${t.status}`),this.name="AIResponseError",this.code=t.error?.code??t.status,this.response=t}};function Ut(e){let t=Uint8Array.from(atob(e),i=>i.charCodeAt(0)),o=new DataView(t.buffer,t.byteOffset,t.byteLength),a=new Array(t.byteLength/4);for(let i=0;i<a.length;i++)a[i]=o.getFloat32(i*4,!0);return a}async function st(e){let t,o;return e instanceof Uint8Array?(t=e,o=at(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),o=e.type||at(t)):(t=e.bytes,o=e.mediaType),{media_type:o,data:ot(t)}}function at(e){return e[0]===137&&e[1]===80?"image/png":e[0]===255&&e[1]===216?"image/jpeg":e[8]===87&&e[9]===69&&e[10]===66&&e[11]===80?"image/webp":"application/octet-stream"}function Gt(e){let t=e.url??Ye("PALBASE_URL"),o=e.secretKey??Ye("PALBASE_SECRET_KEY");if(typeof t!="string"||t==="")throw new TypeError("url is the project address (https://<ref>.<domain>) \u2014 or set PALBASE_URL");if(typeof o!="string"||!Mt.test(o))throw new TypeError("secretKey is the project secret key (pb_<ref>_s\u2026) \u2014 or set PALBASE_SECRET_KEY; a model call is billed to the project, so it is never made with a publishable key");let a=fe(ue({baseUrl:t,credentials:{secretKey:o},fetch:e.fetch}),e.retry??ge);return pe.client(a)}function Lt(e){return new Proxy({},{get:(t,o)=>e.ai[o]})}function Jt(e={}){if(be())throw new TypeError("palbase/ai runs on a server: it speaks with the project secret key, which never goes into a browser or a mobile app \u2014 call your backend, and let it ask the model");if(e.machine!==void 0&&!v.test(e.machine))throw new TypeError("machine is the name of one of the project's machines");let t=e.server?Lt(e.server):Gt(e),o=e.resumeFor??12e4;async function a(c,g,m=ie()){return q(t.createResponse({headers:{"Idempotency-Key":m},body:c,signal:g}))}async function i(c,g={}){return(await t.getResponse({path:{response_id:c},signal:g.signal})).data}async function l(c,g,m,S,y){let b=0,x=c,R=ie(),D=()=>Date.now()+o,N=D();for(let U=0;;U++)try{if(x||(g===null?x=(await a({...y,stream:!0},S,R)).data:x=(await t.followResponse({path:{response_id:g},query:{offset:b},signal:S})).data),!x.body)throw new Error("the stream has no body");for await(let k of ke(x.body)){let A=JSON.parse(k.data);switch(k.event){case"response":g===null&&(g=A.id,m.admitted(A));break;case"delta":{let O=A.offset+he(A.text);if(O>b){let Q=A.offset>=b?A.text:we(A.text,b-A.offset);m.delta(b,Q),b=O}N=D();break}case"reset":A.offset<b&&(b=A.offset,m.reset(b));break;case"terminal":return A}}throw new Error("the stream ended before its answer did")}catch(k){if(x=null,S?.aborted||k instanceof $&&k.status>0&&k.status<500&&k.status!==429||g===null&&!(k instanceof $)||Date.now()>N)throw k;await new Promise(A=>setTimeout(A,Math.min(250*2**Math.min(U,4),4e3)))}}function u(c){if(c.status!=="completed")throw new E(c);return c.text??""}function h(c,g){let m=V(c,g?{schema:g.prepared.json,schema_name:g.name}:{},e.machine),S=[],y=!1,b,x=null,R=()=>{let f=x;x=null,f?.()},D,N,U=new Promise((f,T)=>{D=f,N=T});U.catch(()=>{});let k="",A=l(null,null,{admitted:f=>D(f.id),delta:(f,T)=>{k+=T,S.push(T),R()},reset:f=>{let T=ye(k,f);k=k.slice(0,T),S.push("\0reset:"+T),R()}},c.signal,m).then(f=>{let T=f.status==="completed"?f.text??"":"";return T.length>k.length&&T.startsWith(k)&&(S.push(T.slice(k.length)),k=T),y=!0,R(),f},f=>{throw y=!0,b=f,N(f),R(),f});A.catch(()=>{});async function*O(){for(let f=0;;f++){for(;f>=S.length;){if(y){if(b)throw b;return}await new Promise(T=>x=T)}yield S[f]}}async function*Q(){for await(let f of O())f.startsWith("\0reset:")||(yield f)}async function*dt(){let f="",T="";for await(let L of O()){L.startsWith("\0reset:")?f=f.slice(0,Number(L.slice(7))):f+=L;let P=ne(f);if(P===void 0)continue;let I=JSON.stringify(P);I!==T&&(T=I,yield P)}}let G=A.then(f=>{if(f.status!=="completed")throw new E(f);return f});G.catch(()=>{});let ce=g?G.then(f=>g.prepared.check(f.output)):Promise.reject(new TypeError("object is a schema stream's"));ce.catch(()=>{});let le=G.then(f=>f.text??k);return le.catch(()=>{}),{id:U,response:G,text:le,get textStream(){return Q()},get partialObjectStream(){return dt()},object:ce,toResponse(f={}){let T=new TextEncoder,L=new ReadableStream({async start(I){try{for await(let J of O())J.startsWith("\0reset:")?I.enqueue(T.encode(`event: reset
8
- data: ${JSON.stringify({offset:Number(J.slice(7))})}
9
-
10
- `)):I.enqueue(T.encode(`data: ${JSON.stringify({text:J})}
11
-
12
- `));let C=await G;I.enqueue(T.encode(`event: done
13
- data: ${JSON.stringify({id:C.id,text:C.text,output:C.output,usage:C.usage})}
14
-
15
- `))}catch(C){let J=C instanceof E||C instanceof $?C.code:"stream_failed";I.enqueue(T.encode(`event: error
16
- data: ${JSON.stringify({code:J})}
17
-
18
- `))}finally{I.close()}}}),P=new Headers(f.headers);return P.set("content-type","text/event-stream"),P.set("cache-control","no-store"),P.set("x-accel-buffering","no"),new globalThis.Response(L,{...f,headers:P})}}}async function r(c,g){return l(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},c.signal,V(c,g,e.machine))}let{chats:n,agents:s,endpoints:d,settings:p,repos:_}=He(t);return{module:t,chats:n,agents:s,endpoints:d,settings:p,repos:_,tool:De,clientTool:Ne,deferred:Me,agent:Le,repo:Ue,repoTokens:Ge,async ask(c,g={}){let m=typeof c=="string"?{...g,prompt:c}:c;return u(await r(m,{}))},async generate(c){if(c.schema===void 0){if(c.agent===void 0)throw new TypeError("generate: a schema \u2014 the answer's shape \u2014 or an agent whose output is");if(c.background){let x=(await a(V(c,{background:!0},e.machine),c.signal)).data;return{id:x.id,status:x.status}}let y=await r(c,{});if(y.status!=="completed")throw new E(y);return rt(y,it(c.agent))}let g=de(c.schema),m={schema:g.prepared.json,schema_name:g.name};if(c.background){let b=(await a(V(c,{...m,background:!0},e.machine),c.signal)).data;return{id:b.id,status:b.status}}let S=await r(c,m);if(S.status!=="completed")throw new E(S);return g.prepared.check(S.output)},stream(c){return h(c,c.schema?de(c.schema):void 0)},async start(c){let g=(await a(V(c,{background:!0},e.machine),c.signal)).data;return{id:g.id,status:g.status}},schema(c,g){return{name:c,schema:g,prepared:M(g,c)}},response:i,async result(c,g){let m=await i(c);if(m.status!=="completed")throw new E(m);return g===void 0?rt(m,"the response"):de(g).prepared.check(m.output)},async cancel(c){return(await t.cancelResponse({path:{response_id:c}})).data},async embed(c,g={}){let m=Array.isArray(c)?c:[c],S=[];for(let y=0;y<m.length;y+=1024){let b=await t.createEmbeddings({body:{input:m.slice(y,y+1024),model:g.model,dimensions:g.dimensions},signal:g.signal});for(let x of b.data.vectors)S.push(Ut(x))}return Array.isArray(c)?S:S[0]},async image(c){let g={prompt:c.prompt};for(let y of["model","size","quality","background","format","count"])c[y]!==void 0&&(g[y]=c[y]);c.references?.length&&(g.references=await Promise.all(c.references.map(st))),c.mask&&(g.mask=await st(c.mask));let m=(await t.createImage({headers:{"Idempotency-Key":ie()},body:g,signal:c.signal})).data;for(let y=0;m.status==="running";y++){if(await new Promise(b=>setTimeout(b,Math.min(500+y*250,3e3))),c.signal?.aborted)throw c.signal.reason;m=(await t.getImage({path:{image_id:m.id},signal:c.signal})).data}if(m.status!=="completed")throw new Error(`the image failed: ${m.error?.code??"image_failed"}: ${m.error?.message??""}`);let S=await Promise.all(m.files.map(async y=>{let x=(await t.getImageFile({path:{image_id:m.id,position:y.position},signal:c.signal})).data;return{mediaType:y.media_type,bytes:new Uint8Array(await x.arrayBuffer())}}));return{id:m.id,model:m.model,pictures:S,costNanoUSD:m.usage?.cost_nano_usd??0,save(y,b,x=0){let R=S[x];if(!R)throw new RangeError(`the job made ${S.length} picture(s)`);return y.upload(b,R.bytes,{contentType:R.mediaType})}}},async models(){return(await t.listModels({})).data},async usage(c={}){let g=c.metadata===void 0?void 0:JSON.stringify(c.metadata),m=(await t.listUsage({query:{kind:c.kind,limit:c.limit,cursor:c.cursor,metadata:g}})).data;return{usage:m.usage,nextCursor:m.next_cursor}},async connectProvider(c,g){return(await t.connectProvider({path:{provider:c},body:{key:g}})).data},async disconnectProvider(c){await t.disconnectProvider({path:{provider:c}})}}}export{ne as a,w as b,M as c,se as d,E as e,Jt as f};