palbase 0.6.2 → 0.8.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 (81) hide show
  1. package/dist/ai/index.js +2 -14
  2. package/dist/backend/engine.js +2 -2
  3. package/dist/backend/env.js +1 -1
  4. package/dist/backend/index.js +9 -9
  5. package/dist/backend/stack.js +1 -1
  6. package/dist/backend/test.js +2 -2
  7. package/dist/chunks/5VTGMNPL.js +20 -0
  8. package/dist/chunks/{SXH5AIQX.js → BO5KR2EQ.js} +2 -2
  9. package/dist/chunks/{AYY4J3B2.js → BRBCWPR3.js} +1 -1
  10. package/dist/chunks/DB3SIBKB.js +2 -0
  11. package/dist/chunks/EGNEXFTZ.js +2 -0
  12. package/dist/chunks/{VP7V7YRH.js → FZ3MQOVA.js} +2 -2
  13. package/dist/chunks/{A3CDCPXX.js → JSJVV43D.js} +1 -1
  14. package/dist/chunks/K6RRNI23.js +4 -0
  15. package/dist/chunks/{SUX2BJG4.js → KDWDPSL2.js} +1 -1
  16. package/dist/chunks/P4Z5E6ZI.js +2 -0
  17. package/dist/chunks/PDOHT46N.js +2 -0
  18. package/dist/chunks/PGPQGKH2.js +18 -0
  19. package/dist/chunks/{DRTZ33XF.js → RBA6V3UO.js} +2 -2
  20. package/dist/chunks/{KLANM6M6.js → RO5Y5YU4.js} +1 -1
  21. package/dist/chunks/{53FS342F.js → TUGRIOFX.js} +2 -2
  22. package/dist/chunks/WEI32SAJ.js +13 -0
  23. package/dist/chunks/{GVFZM4BI.js → WINBISC2.js} +3 -3
  24. package/dist/chunks/Z5JVQNAZ.js +2 -0
  25. package/dist/cli.js +140 -139
  26. package/dist/refuse/ai.js +1 -1
  27. package/dist/refuse/backend.js +1 -1
  28. package/dist/refuse/server.js +1 -1
  29. package/dist/server/index.js +2 -2
  30. package/dist/server/testing.js +2 -2
  31. package/dist/web/index.js +2 -2
  32. package/dist/web/palbe.js +2 -2
  33. package/dist/web/paywall.js +2 -2
  34. package/dist/web/ssr.js +2 -2
  35. package/dist/web/vite.js +2 -2
  36. package/package.json +2 -2
  37. package/types/ai/src/ai.d.ts +46 -19
  38. package/types/ai/src/chats.d.ts +478 -18
  39. package/types/ai/src/index.d.ts +4 -4
  40. package/types/ai/src/tools.d.ts +161 -29
  41. package/types/backend/src/bootstrap.d.ts +8 -0
  42. package/types/backend/src/container.d.ts +11 -2
  43. package/types/backend/src/database.d.ts +17 -2
  44. package/types/backend/src/engine.d.ts +3 -4
  45. package/types/backend/src/gateways.d.ts +269 -0
  46. package/types/backend/src/index.d.ts +3 -2
  47. package/types/backend/src/openapi.d.ts +3 -6
  48. package/types/backend/src/runtime.d.ts +51 -2
  49. package/types/backend/src/testing/unit.d.ts +3 -1
  50. package/types/internal/src/chat.d.ts +168 -35
  51. package/types/internal/src/modules/ai.d.ts +1826 -545
  52. package/types/internal/src/modules/auth.d.ts +14 -2
  53. package/types/internal/src/modules/events.d.ts +2 -2
  54. package/types/internal/src/modules/machines.d.ts +57 -1
  55. package/types/internal/src/modules/notify.d.ts +6 -6
  56. package/types/internal/src/modules/purchases.d.ts +357 -13
  57. package/types/internal/src/modules/realtime.d.ts +45 -1
  58. package/types/internal/src/modules/stores.d.ts +259 -22
  59. package/types/internal/src/transport.d.ts +5 -0
  60. package/types/server/src/auth/jwt.d.ts +1 -6
  61. package/types/web/src/auth.d.ts +15 -4
  62. package/types/web/src/backends.d.ts +20 -13
  63. package/types/web/src/chat.d.ts +329 -0
  64. package/types/web/src/client.d.ts +28 -3
  65. package/types/web/src/gateways.d.ts +90 -0
  66. package/types/web/src/index.d.ts +5 -4
  67. package/types/web/src/session.d.ts +11 -1
  68. package/types/web/src/socket.d.ts +18 -2
  69. package/types/web/src/voice.d.ts +36 -0
  70. package/dist/chunks/2RG3I7LX.js +0 -6
  71. package/dist/chunks/A76UZBAF.js +0 -2
  72. package/dist/chunks/AD5LBZAB.js +0 -4
  73. package/dist/chunks/DRGYTL6T.js +0 -20
  74. package/dist/chunks/IVEAUFGE.js +0 -13
  75. package/dist/chunks/IYCW6PWG.js +0 -2
  76. package/dist/chunks/KL7FIRII.js +0 -2
  77. package/dist/chunks/U4OZ4HOF.js +0 -2
  78. package/types/backend/src/channels.d.ts +0 -81
  79. package/types/backend/src/rooms.d.ts +0 -178
  80. package/types/web/src/ai.d.ts +0 -224
  81. package/types/web/src/rooms.d.ts +0 -61
@@ -0,0 +1,2 @@
1
+ /*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as g,b}from"./RO5Y5YU4.js";var A=Symbol.for("palbase.data"),T=globalThis,m=T[A]??=new WeakSet;function S(t){return t instanceof Date||ArrayBuffer.isView(t)||t instanceof ArrayBuffer}function k(t){let e=[t];for(;e.length>0;){let n=e.pop();if(!(typeof n!="object"||n===null||m.has(n)||S(n))){m.add(n);for(let a of Array.isArray(n)?n:Object.values(n))e.push(a)}}return t}var l=class extends Error{status;code;requestId;retryAfter;body;op;get isNetworkError(){return this.code==="network_error"}constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="PalbaseError",this.op=e.op,this.status=e.status,this.code=e.code,this.requestId=e.requestId,this.retryAfter=e.retryAfter,this.body=e.body}};function C(t,e,n){let a=String(n);if(a===""||a==="."||a==="..")throw new l({op:t,status:0,code:"invalid_path_parameter",message:`${t}: ${e} cannot be ${a===""?"empty":JSON.stringify(a)}`});return encodeURIComponent(a)}var x=new Set(["apikey","authorization"]),q=64*1024;function W(t){let e=E(t.baseUrl),n=t.fetch??globalThis.fetch,a=t.solveProofOfWork??!0,u=async(r,o)=>{let d=v(e,r),s=new Headers;for(let[h,y]of Object.entries(r.headers??{}))y!=null&&!x.has(h.toLowerCase())&&s.set(h,String(y));for(let[h,y]of Object.entries(o))s.set(h,y);await j(r,t.credentials,s),s.has("accept")||s.set("accept","application/json");let f={method:r.method,headers:s,redirect:"manual",signal:r.signal,...r.keepalive?{keepalive:!0}:{}};r.body&&r.body.value!==void 0&&(s.set("content-type",r.body.contentType),f.body=L(r.body.kind,r.body.value),R(f.body)||(f.duplex="half"));let i;try{i=r.onUploadProgress&&t.xmlHttpRequest?await U(t.xmlHttpRequest,r.op,d,f,r.onUploadProgress):await n(d,f)}catch(h){throw r.signal?.aborted||h instanceof l?h:new l({op:r.op,status:0,code:"network_error",message:`${r.op}: the request did not reach ${e.origin}`,cause:h})}let c=r.answers[i.status];if(c===void 0)throw i.status>=200&&i.status<300?(await i.body?.cancel(),new l({op:r.op,status:i.status,code:"undeclared_answer",message:`${r.op}: the server answered ${i.status}, which its contract does not declare; the request may have taken effect`})):await P(r.op,i);let p;switch(c){case"json":try{p=k(await i.json())}catch(h){throw new l({op:r.op,status:i.status,code:"invalid_json",message:`${r.op}: the answer is not JSON`,cause:h})}break;case"raw":p=i;break;default:await i.body?.cancel(),p=void 0}return{status:i.status,data:p,headers:i.headers}};return{async send(r){try{return await u(r,{})}catch(o){let d=a&&o instanceof l&&o.status===403?g(o.body):null,s=r.body?.value;if(!d||r.body?.kind==="raw"&&!R(s))throw o;let f=o,i;try{i=await b(d,{signal:r.signal})}catch(c){throw r.signal?.aborted?c:new l({op:r.op,status:403,code:"pow_unsolved",message:`${r.op}: ${c instanceof Error?c.message:String(c)}`,requestId:f.requestId,body:f.body,cause:c})}return u(r,i)}}}}function U(t,e,n,a,u){return new Promise((r,o)=>{let d=a.signal;if(d?.aborted)return o(d.reason);let s=new t,f=()=>s.abort();d?.addEventListener("abort",f,{once:!0});let i=c=>{d?.removeEventListener("abort",f),c()};s.open(a.method??"GET",n.href),s.responseType="arraybuffer",new Headers(a.headers).forEach((c,p)=>s.setRequestHeader(p,c)),s.upload&&(s.upload.onprogress=c=>{c.lengthComputable&&u(c.loaded,c.total)}),s.onload=()=>i(()=>{if(s.responseURL!==""&&s.responseURL!==n.href){o(new l({op:e,status:0,code:"undeclared_redirect",message:`${e}: the server redirected; the answer is another address's, and was not read`}));return}if(s.status<200||s.status>599)return o(new TypeError(`${e}: answered ${s.status}`));let c=s.status===204||s.status===205||s.status===304;r(new Response(c?null:s.response,{status:s.status,statusText:s.statusText,headers:$(s.getAllResponseHeaders())}))}),s.onerror=()=>i(()=>o(new TypeError(`${e}: the request failed`))),s.onabort=()=>i(()=>o(d?.reason??new DOMException("The request was aborted","AbortError"))),s.send(a.body)})}function $(t){let e=new Headers;for(let n of t.split(/\r?\n/)){let a=n.indexOf(":");if(!(a<=0))try{e.append(n.slice(0,a).trim(),n.slice(a+1).trim())}catch{}}return e}function E(t){let e;try{e=new URL(t)}catch{throw new TypeError(`baseUrl ${JSON.stringify(t)} is not an absolute URL`)}let n=e.hostname==="localhost"||e.hostname.endsWith(".localhost")||e.hostname==="127.0.0.1"||e.hostname==="[::1]";if(e.protocol!=="https:"&&!(e.protocol==="http:"&&n))throw new TypeError(`baseUrl must be https (http only for a loopback address): ${e.origin}`);if(e.username||e.password||e.search||e.hash)throw new TypeError("baseUrl carries no user, query or fragment");if(e.pathname!=="/"&&e.pathname!=="")throw new TypeError("baseUrl is the project origin alone, with no path");return e}function v(t,e){if(!e.path.startsWith("/")||e.path.startsWith("//"))throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path ${JSON.stringify(e.path)} is not absolute`});let n=new URL(e.path+O(e.query),t);if(n.origin!==t.origin)throw new l({op:e.op,status:0,code:"invalid_path",message:`${e.op}: path leaves the project's origin`});return n}async function j(t,e,n){if(t.auth.length===0)return;let a=t.auth.some(o=>o.includes("userJWT"))?await e.accessToken?.():void 0,u=o=>{switch(o){case"ApiKeyAuth":return!!(e.publishableKey??e.secretKey);case"SecretKeyAuth":case"AdminAuth":return!!e.secretKey;case"userJWT":return!!a;default:return!1}},r=t.auth.filter(o=>o.every(u)).reduce((o,d)=>o===void 0||d.length>o.length?d:o,void 0);if(!r)throw new l({op:t.op,status:0,code:"missing_credential",message:`${t.op} needs one of: ${t.auth.map(o=>o.length===0?"nothing":o.join(" + ")).join(" | ")}`});for(let o of r)o==="ApiKeyAuth"?n.set("apikey",e.publishableKey??e.secretKey):o==="SecretKeyAuth"||o==="AdminAuth"?n.set("apikey",e.secretKey):o==="userJWT"&&n.set("authorization",`Bearer ${a}`)}function L(t,e){switch(t){case"json":return JSON.stringify(e);case"form":{let n=new URLSearchParams;for(let[a,u]of Object.entries(e))w(n,a,u);return n}case"raw":return e}}function R(t){return!!(t==null||typeof t=="string"||t instanceof URLSearchParams||t instanceof Blob||t instanceof FormData||t instanceof ArrayBuffer||ArrayBuffer.isView(t))}function O(t){if(!t)return"";let e=new URLSearchParams;for(let[a,u]of Object.entries(t))w(e,a,u);let n=e.toString();return n===""?"":`?${n}`}function w(t,e,n){if(n!=null){if(Array.isArray(n)){for(let a of n)w(t,e,a);return}if(n instanceof Date){t.append(e,n.toISOString());return}t.append(e,typeof n=="object"?JSON.stringify(n):String(n))}}async function P(t,e){let n=await _(e,q).catch(()=>""),a;try{a=n===""?void 0:JSON.parse(n)}catch{a=n}let u=B(a)?a:void 0,r=Number(e.headers.get("retry-after")),o=e.status>=300&&e.status<400;return new l({op:t,status:e.status,code:u?.error??(o?"undeclared_redirect":`http_${e.status}`),message:u?.error_description??(o?`${t}: the server redirected (${e.status}); the request was not followed, its credentials stay here`:`${t}: ${e.status} ${e.statusText}`.trim()),requestId:u?.request_id??e.headers.get("x-request-id")??void 0,retryAfter:u?.retry_after??(Number.isFinite(r)&&r>0?r:void 0),body:a})}async function _(t,e){if(!t.body)return"";let n=t.body.getReader(),a=[],u=0;for(;u<e;){let{done:d,value:s}=await n.read();if(d)break;a.push(s),u+=s.byteLength}await n.cancel().catch(()=>{});let r=new Uint8Array(Math.min(u,e)),o=0;for(let d of a){let s=Math.min(d.byteLength,r.byteLength-o);if(r.set(d.subarray(0,s),o),o+=s,o>=r.byteLength)break}return new TextDecoder().decode(r)}function B(t){return typeof t=="object"&&t!==null&&typeof t.error=="string"}export{k as a,l as b,C as c,W as d,E as e,R as f};
@@ -0,0 +1,18 @@
1
+ /*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as L,c as me,d as he,e as ye}from"./P4Z5E6ZI.js";import{a as we}from"./KDWDPSL2.js";import{a as ue}from"./EGNEXFTZ.js";import{a as pe,b as ge,c as fe}from"./BO5KR2EQ.js";import{b as I,d as le}from"./PDOHT46N.js";async function*be(e,t={}){let o=e.getReader(),a=new TextDecoder,i="",u="",l=[],m,s=()=>{o.cancel().catch(()=>{})};t.signal?.addEventListener("abort",s,{once:!0});try{if(t.signal?.aborted)return;for(;;){let{done:n,value:r}=await o.read();if(n||t.signal?.aborted)return;t.onBytes?.(),i+=a.decode(r,{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===""?(u!==""&&(yield m===void 0?{event:u,data:l.join(`
5
+ `)}:{event:u,data:l.join(`
6
+ `),id:m}),u="",l=[],m=void 0):p.startsWith("event:")?u=Y(p,6):p.startsWith("data:")?l.push(Y(p,5)):p.startsWith("id:")&&(m=Y(p,3))}}}finally{t.signal?.removeEventListener("abort",s);try{await o.cancel()}catch{}}}function Y(e,t){let o=e.slice(t);return o.startsWith(" ")?o.slice(1):o}var rt=/\s/;function q(e,t){for(;t<e.length&&rt.test(e[t]);)t++;return t}function ke(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 u=e[a+1];if(u===void 0)break;if(u==="u"){let l=e.slice(a+2,a+6);if(l.length<4)break;o+=String.fromCharCode(Number.parseInt(l,16)),a+=5;continue}o+={n:`
7
+ `,t:" ",r:"\r",b:"\b",f:"\f"}[u]??u,a++}return{value:o,complete:!1,empty:!1,at:e.length}}function Q(e,t){t=q(e,t);let o=e[t];if(o===void 0)return{value:void 0,complete:!1,empty:!0,at:t};if(o==='"')return ke(e,t);if(o==="{")return at(e,t);if(o==="[")return st(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 at(e,t){let o={},a=t+1;for(;;){if(a=q(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=ke(e,a);if(!i.complete)return{value:o,complete:!1,empty:!1,at:e.length};if(a=q(e,i.at),e[a]!==":")return{value:o,complete:!1,empty:!1,at:e.length};let u=Q(e,a+1);if(u.empty||Object.defineProperty(o,i.value,{value:u.value,enumerable:!0,writable:!0,configurable:!0}),!u.complete)return{value:o,complete:!1,empty:!1,at:e.length};a=u.at}}function st(e,t){let o=[],a=t+1;for(;;){if(a=q(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=Q(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 ee(e){let t=Q(e,0);return t.empty?void 0:t.value}var b=class extends Error{path;constructor(t,o){super(`${t}: ${o}`),this.name="AISchemaError",this.path=t}},ot=new Set(["type","properties","required","additionalProperties","items","enum","description","title","minimum","maximum","minLength","maxLength","minItems","maxItems"]),it=new Set(["format","pattern","exclusiveMinimum","exclusiveMaximum","multipleOf","uniqueItems","contentEncoding","contentMediaType","default","examples","readOnly","writeOnly","deprecated","$comment"]),dt=new Set(["object","array","string","integer","number","boolean"]),Te=12,Se=512,ct=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/;function z(e,t="answer"){if(!ct.test(t))throw new b(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 b(t,"not a Standard Schema: pass a zod (4.2+), valibot or arktype schema");if(!o.jsonSchema||typeof o.jsonSchema.output!="function")throw new b(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(l){throw new b(t,`the schema has a part JSON Schema cannot say (${l.message}): a function, a transform, a date \u2014 give the model a string and convert it after`)}if(a.type!=="object")throw new b(t,"the answer is an object: wrap the value in z.object({ \u2026 })");let u=te(a,t,0,{properties:0});return{name:t,json:u,async check(l){let m=await o.validate(l);if(m.issues){let s=m.issues[0],n=(s?.path??[]).map(r=>String(typeof r=="object"?r.key:r)).join(".");throw new b(n?`${t}.${n}`:t,`the model's answer does not match the schema: ${s?.message??"invalid"}`)}return m.value}}}function te(e,t,o,a){if(o>Te)throw new b(t,`nests deeper than ${Te} levels, the most the provider takes`);for(let l of["anyOf","oneOf","allOf"])if(l in e)throw new b(t,lt(e[l])??"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 l of["$ref","$defs","definitions","$dynamicRef"])if(l in e)throw new b(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 b(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 l of["prefixItems","patternProperties","propertyNames","not","if","then","else","dependentRequired","dependentSchemas","const","minProperties","maxProperties","contains","unevaluatedProperties","unevaluatedItems"])if(l in e)throw new b(t,`uses ${l}, which the provider cannot hold a model to`);if(Array.isArray(e.type))throw new b(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 b(t,"has no type: the provider holds a model only to a typed value");if(typeof i=="string"&&!dt.has(i))throw new b(t,`is of type ${i}, which the provider does not take`);let u={};for(let[l,m]of Object.entries(e))if(!(l==="$schema"||l==="id"||l==="$id")&&!it.has(l)){if(!ot.has(l))throw new b(t,`uses ${l}, which the provider cannot hold a model to`);u[l]=m}if("enum"in e&&typeof i!="string"){let l=e.enum,m=new Set(l.map(s=>s===null?"null":typeof s));if(m.size!==1||m.has("null"))throw new b(t,"an enum of values of several types (or with null): one type per field");u.type=m.has("string")?"string":m.has("boolean")?"boolean":"number"}if(i==="object"){let l=e.properties??{},m=Object.keys(l);if(m.length===0)throw new b(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 b(t,"accepts fields it does not name (passthrough, catchall, record): the provider holds a model only to the fields named");if(a.properties+=m.length,a.properties>Se)throw new b(t,`the schema has more than ${Se} fields in all, the most the provider takes`);let s=new Set(e.required??[]),n={};for(let r of m){if(!s.has(r))throw new b(`${t}.${r}`,'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[r]=te(l[r],`${t}.${r}`,o+1,a)}u.properties=n,u.required=m,u.additionalProperties=!1}if(i==="array"){let l=e.items;if(!l||typeof l!="object"||Array.isArray(l))throw new b(t,"is a list with no one shape for its items: the provider takes a list of one shape");u.items=te(l,`${t}[]`,o+1,a)}return u}function lt(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 ut=new Set(["image/png","image/jpeg","image/webp","image/gif"]);function W(e){return Array.isArray(e)&&e.length>0&&e.every(xe)?e.map(Ae):xe(e)?[Ae(e)]:e==null?[{type:"text",text:""}]:typeof e=="string"?[{type:"text",text:e}]:[{type:"text",text:JSON.stringify(e)??String(e)}]}function xe(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 Ae(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(!ut.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:pt(o)}}function pt(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}var Ie=Symbol.for("palbase.ai.deferred"),ve=60,_e=86400;function $e(e={}){let t=e?.expiresInSeconds;if(t!==void 0&&(!Number.isInteger(t)||t<ve||t>_e))throw new TypeError(`ai.deferred: expiresInSeconds is how long the call waits for its answer, ${ve} to ${_e} seconds (got ${String(t)})`);return Object.freeze({[Ie]:!0,...t!==void 0?{expiresInSeconds:t}:{}})}function gt(e){return typeof e=="object"&&e!==null&&e[Ie]===!0}var ft=Symbol.for("palbase.ai.declared"),mt=Symbol.for("palbase.ai.tool_error"),ne=class extends Error{constructor(t){super(t),this.name="ToolError",Object.defineProperty(this,mt,{value:!0})}};function G(){let e=globalThis,t=e[ft]??={tools:new Map,agents:new Map,repos:new Map,twice:new Set};return t.repos??=new Map,t}function re(e,t,o,a){let i=e.get(o);i===void 0?e.set(o,a):i!==a&&G().twice.add(`${t}:${o}`)}var Me=/^[A-Za-z][A-Za-z0-9_-]{0,63}$/,_=/^[a-z][a-z0-9_-]{0,63}$/;function Oe(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(m){throw new TypeError(`${t}: the input has a part JSON Schema cannot say (${m.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:u,...l}=a;return l}function je(e){let t=`ai.tool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!Me.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&&!_.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=Oe(e.input,t),a=e.input["~standard"],i=e.run,u={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(l,m){let s=await a.validate(l);if(s.issues){let r=s.issues[0],d=(r?.path??[]).map(p=>String(typeof p=="object"?p.key:p)).join(".");return{output:[{type:"text",text:`the input does not match ${e.name}'s schema${d?` at ${d}`:""}: ${r?.message??"invalid"}`}],is_error:!0}}let n=await i(s.value,m);return gt(n)?m.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,...n.expiresInSeconds!==void 0?{expires_in_seconds:n.expiresInSeconds}:{}}:{output:W(n),is_error:!1}}};return Object.freeze(u),re(G().tools,"tool",u.name,u),u}function Be(e){let t=`ai.clientTool(${JSON.stringify(e?.name??null)})`;if(typeof e?.name!="string"||!Me.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`);return Object.freeze({source:"client",name:e.name,description:e.description,parameters:Oe(e.input,t),approval:e.approval===!0})}var ht=/^[A-Za-z0-9_.-]{1,100}\/[A-Za-z0-9_.-]{1,100}$/;function De(e){let t=e??{};if(typeof t.name!="string"||!_.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"||!ht.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&&!_.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 re(G().repos,"repo",t.name,a),a}function Ne(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=G();t.repoTokens===void 0?t.repoTokens=e:t.repoTokens!==e&&t.twice.add("repoTokens")}function Ue(e,t,o={}){let a=`ai.agent(${JSON.stringify(e??null)})`;if(typeof e!="string"||!_.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`);if(o.machine!==void 0&&!_.test(o.machine))throw new TypeError(`${a}: machine is the name of one of the project's machines`);let i={kind:"agent",name:e,...o.machine!==void 0?{machine:o.machine}:{},async resolve(u){let l=await t(u),m=V(l,`${a} for chat ${u.chatId}`);if(m.backend!==void 0)throw new TypeError(`${a}: a backend's agent is its definition \u2014 it names no other backend`);return{definition:m,tools:yt(l)}}};return Object.freeze(i),re(G().agents,"agent",e,i),i}function F(e){return typeof e=="object"&&e!==null&&e.kind==="agent"?e:void 0}function yt(e){return[...e.tools??[],...(e.subagents??[]).flatMap(o=>o.tools??[])].filter(o=>o.source==="backend")}var Re=["web.search","web.fetch","workspace.fetch_archive"];function J(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"||!_.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"||!_.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"||!Re.includes(e.name))throw new TypeError(`${t}: { source: 'platform', name } names one of the platform's tools: ${Re.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 Ce=1e4,Ee=["none","minimal","low","medium","high","xhigh","max"],wt=1e8,bt=/^[A-Za-z]{2,8}(-[A-Za-z0-9]{1,8})*$/;function ae(e,t){if(!Number.isInteger(e)||e<1||e>Ce)throw new TypeError(`${t}: maxToolCalls is a whole number, 1 to ${Ce} (got ${String(e)})`);return e}function Pe(e,t){let o={};if(e.effort!==void 0){if(typeof e.effort!="string"||!Ee.includes(e.effort))throw new TypeError(`${t}: effort is one of ${Ee.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>wt)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 V(e,t){if(typeof e!="object"||e===null)throw new TypeError(`${t}: a definition is { instructions, model, tools, subagents, maxToolCalls, effort, contextWindow, thinking, language }`);let o={};if(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,Pe(e,t)),e.language!==void 0){if(typeof e.language!="string"||e.language.length>35||!bt.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.tools!==void 0&&(o.tools=e.tools.map(a=>J(a,t))),e.subagents!==void 0){for(let a of e.subagents){let i=(a?.tools??[]).find(u=>u?.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}:{},...Pe(a,`${t} subagent ${a.name}`),...a.tools!==void 0?{tools:a.tools.map(i=>J(i,`${t} subagent ${a.name}`))}:{}}))}return o}function Ge(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 kt=/^[a-z][a-z0-9-]{1,62}$/,Le=4,qe=8;function Tt(e){let t={},o=(a,i)=>{if(typeof a?.bucket!="string"||!kt.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>Le)throw new TypeError(`chats.send: images are ${Le} 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>qe)throw new TypeError(`chats.send: files are ${qe} at most`);t.files=e.files.map((a,i)=>{let u=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)`);u.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)`);u.content_type=a.contentType}return u})}return t}function K(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 St=["speak","tell","know","instruct"];function ze(){return"cm_"+crypto.randomUUID()}async function X(e,t,o=4){for(let a=1;;a++)try{return await e()}catch(i){if(a>=o||!(i instanceof I)||i.status===429||t?.aborted)throw i;let u=fe(i,a,30);if(u===void 0)throw i;await new Promise((l,m)=>{let s=setTimeout(l,u*1e3);t?.addEventListener("abort",()=>(clearTimeout(s),m(t.reason)),{once:!0})})}}function se(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 We=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}:{}}),xt=/^[A-Za-z0-9-]{1,64}$/,Je=16;function At(e){if(!Array.isArray(e)||e.length>Je)throw new TypeError(`chats.create: workspace.trailers are ${Je} at most, each { key, value }`);return e.map((t,o)=>{if(typeof t?.key!="string"||!xt.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 vt(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 Fe(e){return{clients:e.clients,userMessagesPerMinute:e.user_messages_per_minute,historyLimitBytes:e.history_limit_bytes,historyBytes:e.history_bytes}}function _t(e){return new Proxy(e,{get(t,o){let a=t[o];return typeof a=="function"?(...i)=>L(a.apply(t,i)):a}})}function Ve(e){let t=_t(e),o={async create(s){let n=typeof s.agent=="string"||s.agent===void 0?s.agent:F(s.agent)?.name;if(s.agent!==void 0&&n===void 0)throw new TypeError("chats.create: agent is a named agent of the project, or a backend's ai.agent");if(n===void 0&&s.definition===void 0)throw new TypeError("chats.create: an agent (a named agent of the project) or a definition of the chat's own");let r={agent:n??"assistant"};return s.definition!==void 0&&(r.definition=V(s.definition,"chats.create")),s.title!==void 0&&(r.title=s.title),s.metadata!==void 0&&(r.metadata=s.metadata),s.members!==void 0&&(r.members=s.members.map(We)),s.workspace!==void 0&&(r.workspace={repos:s.workspace.repos.map(d=>({repo:typeof d.repo=="string"?d.repo:d.repo.name,...d.branch!==void 0?{branch:d.branch}:{}})),...s.workspace.autoPush!==void 0?{auto_push:s.workspace.autoPush}:{},...s.workspace.trailers!==void 0?{trailers:At(s.workspace.trailers)}:{}}),(await t.createChat({body:r,signal:s.signal})).data},async get(s,n={}){return(await t.getChat({path:{chat_id:s},signal:n.signal})).data},async list(s={}){let n=s.metadata===void 0?void 0:Object.entries(s.metadata).map(([d,p])=>`${d}:${p}`),r=(await t.listChats({query:{member:s.member,limit:s.limit,cursor:s.cursor,metadata:n},signal:s.signal})).data;return r.next_cursor===void 0?{chats:r.chats}:{chats:r.chats,nextCursor:r.next_cursor}},async delete(s){await t.deleteChat({path:{chat_id:s}})},members:{async put(s,n,r){let d={};return r.name!==void 0&&(d.name=r.name),r.email!==void 0&&(d.email=r.email),r.owner!==void 0&&(d.owner=r.owner),(await t.putChatMember({path:{chat_id:s,user_id:n},body:d})).data},async delete(s,n){await t.deleteChatMember({path:{chat_id:s,user_id:n}})}},async send(s,n){let r={client_id:n.clientId??ze(),text:n.text};return n.delivery!==void 0&&(r.delivery=n.delivery),n.as!==void 0&&(r.as=n.as),n.budget!==void 0&&(r.budget={max_cost_usd:n.budget.maxCostUsd}),n.metadata!==void 0&&(r.metadata=n.metadata),n.context!==void 0&&(r.context=n.context),Object.assign(r,Tt(n)),X(async()=>(await t.sendChatMessage({path:{chat_id:s},body:r,signal:n.signal})).data,n.signal)},async turnCost(s,n,r={}){let d=(await t.getChatTurnCost({path:{chat_id:s,response_id:n},signal:r.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(vt)}},async artifacts(s,n,r={}){return(await t.listChatTurnArtifacts({path:{chat_id:s,response_id:n},signal:r.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(s,n,r,d={}){return(await t.getChatTurnArtifact({path:{chat_id:s,response_id:n,artifact_id:r},signal:d.signal})).data},async messages(s,n={}){let r=(await t.listChatMessages({path:{chat_id:s},query:{limit:n.limit,cursor:n.cursor},signal:n.signal})).data;return r.next_cursor===void 0?{messages:r.messages}:{messages:r.messages,nextCursor:r.next_cursor}},async parts(s,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 r=(await t.listChatParts({path:{chat_id:s},query:{limit:n.limit,cursor:n.cursor,before:n.before},signal:n.signal})).data,d=r.parts.map(p=>({type:p.type,...p.id!==void 0?{id:p.id}:{},partId:p.part_id,data:p.data}));return r.next_cursor===void 0?{parts:d}:{parts:d,nextCursor:r.next_cursor}},async toolCall(s,n,r={}){let d=(await t.getChatToolCall({path:{chat_id:s,call_id:n},signal:r.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(s,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 r=(await t.listTurnToolCalls({path:{chat_id:s},query:{turn:n.turn,limit:n.limit,cursor:n.cursor},signal:n.signal})).data,d=r.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 r.next_cursor===void 0?{toolCalls:d}:{toolCalls:d,nextCursor:r.next_cursor}},workspace:{async file(s,n,r={}){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:s},query:{path:n,...r.manifest!==void 0?{manifest:r.manifest}:{}},signal:r.signal})).data},async addRepo(s,n){let r=typeof n?.repo=="string"?n.repo:n?.repo?.name;if(typeof r!="string"||!_.test(r))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:r};return n.branch!==void 0&&(d.branch=n.branch),(await t.addChatWorkspaceRepo({path:{chat_id:s},body:d,signal:n.signal})).data}},events(s){if(typeof s!="string"||!/^chat_[0-9a-f]{32}$/.test(s))throw new TypeError(`chats.events(id): a chat's id, chat_ and 32 hex digits (got ${JSON.stringify(s)})`);return Object.freeze({kind:"ai.chat",chatId:s,async pipe(n,r={}){await t.putChatPipe({path:{chat_id:s},body:{topic:n},signal:r.signal})},async unpipe(n={}){await t.deleteChatPipe({path:{chat_id:s},signal:n.signal})}})},async stop(s,n={}){return(await t.stopChat({path:{chat_id:s},...n.as!==void 0?{body:{as:n.as}}:{},signal:n.signal})).data.stopped},async approve(s,n,r={}){return(await t.decideChatApproval({path:{chat_id:s,approval_id:n},body:Ge(!0,r)})).data},async deny(s,n,r={}){return(await t.decideChatApproval({path:{chat_id:s,approval_id:n},body:Ge(!1,r)})).data},async answer(s,n,r,d={}){let p={output:W(r)};d.isError&&(p.is_error=!0),d.as!==void 0&&(p.as=d.as);try{return await X(()=>t.answerChatToolCall({path:{chat_id:s,call_id:n},body:p})),!0}catch(v){if(v instanceof I&&v.status===409)return!1;throw v}},async sendToSubagent(s,n,r,d={}){let p={client_id:d.clientId??ze(),text:r};d.as!==void 0&&(p.as=d.as);let v=await X(async()=>(await t.sendSubagentMessage({path:{chat_id:s,run_id:n},body:p})).data);return{runId:v.run_id,clientId:v.client_id}},async stopSubagent(s,n,r={}){return{runId:(await X(async()=>(await t.stopSubagent({path:{chat_id:s,run_id:n},body:r.as!==void 0?{as:r.as}:{},signal:r.signal})).data,r.signal)).run_id}},async fork(s,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 r={before_message:n.beforeMessage};return n.title!==void 0&&(r.title=n.title),n.members!==void 0&&(r.members=n.members.map(We)),(await t.forkChat({path:{chat_id:s},body:r,signal:n.signal})).data},goal:{async set(s,n){let r={objective:n.objective};return n.rubric!==void 0&&(r.rubric=n.rubric),n.maxTurns!==void 0&&(r.max_turns=n.maxTurns),n.budget!==void 0&&(r.budget={max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(r.as=n.as),se((await t.setChatGoal({path:{chat_id:s},body:r,signal:n.signal})).data)},async get(s,n={}){return se((await t.getChatGoal({path:{chat_id:s},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})).data)},async update(s,n){let r={};return n.status!==void 0&&(r.status=n.status),n.reason!==void 0&&(r.reason=n.reason),n.objective!==void 0&&(r.objective=n.objective),n.rubric!==void 0&&(r.rubric=n.rubric),n.maxTurns!==void 0&&(r.max_turns=n.maxTurns),n.budget!==void 0&&(r.budget=n.budget===null?null:{max_cost_usd:n.budget.maxCostUsd}),n.as!==void 0&&(r.as=n.as),se((await t.updateChatGoal({path:{chat_id:s},body:r,signal:n.signal})).data)},async clear(s,n={}){await t.clearChatGoal({path:{chat_id:s},query:n.as!==void 0?{as:n.as}:void 0,signal:n.signal})}},voice:{async start(s,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 r={sdp:n.sdp};n.voice!==void 0&&(r.voice=n.voice),n.delegation!==void 0&&(r.delegation=n.delegation),n.as!==void 0&&(r.as=n.as);let d=(await t.startChatVoice({path:{chat_id:s},body:r,signal:n.signal})).data;if(typeof d.sdp!="string"||d.sdp==="")throw new I({op:"startChatVoice",status:502,code:"no_answer",message:"the voice was started but its WebRTC answer was not given"});return{...K(d),sdp:d.sdp}},async get(s,n,r={}){return K((await t.getChatVoice({path:{chat_id:s,voice_id:n},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})).data)},async command(s,n,r){if(!St.includes(r?.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 r.text!="string"||r.text==="")throw new TypeError("chats.voice.command: text is what the voice is given");if(r.delegationId!==void 0&&r.type!=="speak"&&r.type!=="tell")throw new TypeError("chats.voice.command: delegationId names the request a speak or a tell answers");if(r.interrupt!==void 0&&(typeof r.interrupt!="boolean"||r.type!=="speak"))throw new TypeError("chats.voice.command: interrupt is a speak's: it cuts what the voice is saying");let d={type:r.type,text:r.text};return r.delegationId!==void 0&&(d.delegation_id=r.delegationId),r.interrupt===!0&&(d.interrupt=!0),r.as!==void 0&&(d.as=r.as),K((await t.commandChatVoice({path:{chat_id:s,voice_id:n},body:d,signal:r.signal})).data)},async close(s,n,r={}){return K((await t.closeChatVoice({path:{chat_id:s,voice_id:n},query:r.as!==void 0?{as:r.as}:void 0,signal:r.signal})).data)}}},a={async put(s,n){let r=typeof s=="string"?s:F(s)?.name,d=typeof s=="string"?n:s;if(typeof r!="string"||!_.test(r))throw new TypeError("agents.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64 \u2014 or a backend's ai.agent");if(d===void 0)throw new TypeError(`agents.put(${JSON.stringify(r)}): its definition, or a backend's ai.agent`);let p,v=F(d);if(v){if(v.name!==r)throw new TypeError(`agents.put(${JSON.stringify(r)}): the backend's agent is named ${JSON.stringify(v.name)} \u2014 its machine is asked for it by that name`);p={backend:v.machine??"backend"}}else p=V(d,`agents.put(${JSON.stringify(r)})`);return(await t.putAgent({path:{name:r},body:p})).data},async list(){return(await t.listAgents({})).data.agents},async delete(s){await t.deleteAgent({path:{name:s}})}},i={async put(s,n){let r={kind:n.kind,url:n.url};return n.description!==void 0&&(r.description=n.description),n.parameters!==void 0&&(r.parameters=n.parameters),n.approval!==void 0&&(r.approval=n.approval),(await t.putEndpoint({path:{name:s},body:r})).data},async list(){return(await t.listEndpoints({})).data.endpoints},async delete(s){await t.deleteEndpoint({path:{name:s}})}},u={async get(){return Fe((await t.getSettings({})).data)},async put(s){let n={};return s.clients!==void 0&&(n.clients=s.clients),s.userMessagesPerMinute!==void 0&&(n.user_messages_per_minute=s.userMessagesPerMinute),s.historyLimitBytes!==void 0&&(n.history_limit_bytes=s.historyLimitBytes),Fe((await t.putSettings({body:n})).data)}},l=s=>({name:s.name,repository:s.repository,defaultBranch:s.default_branch,backend:s.backend,createdAt:s.created_at});return{chats:o,agents:a,endpoints:i,settings:u,repos:{async put(s,n){let r=typeof s=="string"?s:s.name;if(typeof r!="string"||!_.test(r))throw new TypeError("repos.put: name is lowercase letters, digits, _ and -, starting with a letter, at most 64");let d=typeof s=="string"?{repository:n?.repository??"",...n?.defaultBranch?{default_branch:n.defaultBranch}:{},...n?.backend?{backend:n.backend}:{}}:{repository:s.repository,default_branch:s.defaultBranch,...s.machine?{backend:s.machine}:{}};return l((await t.putRepo({path:{name:r},body:d})).data)},async list(s={}){let n=(await t.listRepos({query:{limit:s.limit,cursor:s.cursor}})).data,r=n.repos.map(l);return n.next_cursor===void 0?{repos:r}:{repos:r,nextCursor:n.next_cursor}},async delete(s){await t.deleteRepo({path:{name:s}})}}}}var Rt=/^pb_[a-z0-9]+_s/;function Ke(e){let t=globalThis;return t.process?.env?.[e]??t.Deno?.env?.get(e)}function oe(){return"ai_"+crypto.randomUUID()}function ie(e){if(e.prepared)return e;let t=e;return{name:"answer",schema:t,prepared:z(t,"answer")}}var Xe=4,Ct=/^[a-z][a-z0-9-]{1,62}$/,Ze=["image/png","image/jpeg","image/webp","image/gif"],He=5<<20,Ye=6<<20;function tt(e){let t="";for(let o=0;o<e.length;o+=32768)t+=String.fromCharCode(...e.subarray(o,o+32768));return btoa(t)}function Et(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 Pt(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>Xe)throw new TypeError(`a question takes ${Xe} 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"||!Ze.includes(i.mediaType))throw new TypeError(`images[${a}].mediaType is the picture's type: ${Ze.join(", ")}`);let u=i.data instanceof Uint8Array?tt(i.data):i.data,l=typeof u=="string"?Et(u):-1;if(l<0)throw new TypeError(`images[${a}].data is the picture's bytes: base64, or a Uint8Array`);if(l===0||l>He)throw new TypeError(`images[${a}] is ${l} bytes: a picture given by its bytes is 1 byte to ${He>>20} MiB`);if(t+=l,t>Ye)throw new TypeError(`the pictures given by their bytes are ${Ye>>20} MiB at most together: put a larger one in the project's storage and give { bucket, path }`);return{media_type:i.mediaType,data:u}}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 u;try{u=new URL(i.url)}catch{throw new TypeError(`images[${a}].url is not an address: ${JSON.stringify(i.url.slice(0,80))}`)}if(u.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"||!Ct.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}})}function Z(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.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=Pt(e.images)),e.tools!==void 0&&(a.tools=e.tools.map((i,u)=>{if(i?.source==="client")throw new TypeError(`tools[${u}]: ${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[${u}]: the platform's ${i.name} is a chat's agent's tool \u2014 a one-shot answer is given none`);let l=J(i,`tools[${u}]`);return l.source==="backend"&&l.machine===void 0&&o!==void 0&&(l.machine=o),l})),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}var $=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 It(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 Qe(e){let t,o;return e instanceof Uint8Array?(t=e,o=et(t)):typeof Blob<"u"&&e instanceof Blob?(t=new Uint8Array(await e.arrayBuffer()),o=e.type||et(t)):(t=e.bytes,o=e.mediaType),{media_type:o,data:tt(t)}}function et(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 $t(e){let t=e.url??Ke("PALBASE_URL"),o=e.secretKey??Ke("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"||!Rt.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=ge(le({baseUrl:t,credentials:{secretKey:o},fetch:e.fetch}),e.retry??pe);return ue.client(a)}function Mt(e){return new Proxy({},{get:(t,o)=>e.ai[o]})}function Ot(e={}){if(we())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&&!_.test(e.machine))throw new TypeError("machine is the name of one of the project's machines");let t=e.server?Mt(e.server):$t(e),o=e.resumeFor??12e4;async function a(c,g,h=oe()){return L(t.createResponse({headers:{"Idempotency-Key":h},body:c,signal:g}))}async function i(c,g={}){return(await t.getResponse({path:{response_id:c},signal:g.signal})).data}async function u(c,g,h,y,k){let T=0,x=c,R=oe(),O=()=>Date.now()+o,j=O();for(let B=0;;B++)try{if(x||(g===null?x=(await a({...k,stream:!0},y,R)).data:x=(await t.followResponse({path:{response_id:g},query:{offset:T},signal:y})).data),!x.body)throw new Error("the stream has no body");for await(let w of be(x.body)){let A=JSON.parse(w.data);switch(w.event){case"response":g===null&&(g=A.id,h.admitted(A));break;case"delta":{let M=A.offset+me(A.text);if(M>T){let H=A.offset>=T?A.text:ye(A.text,T-A.offset);h.delta(T,H),T=M}j=O();break}case"reset":A.offset<T&&(T=A.offset,h.reset(T));break;case"terminal":return A}}throw new Error("the stream ended before its answer did")}catch(w){if(x=null,y?.aborted||w instanceof I&&w.status>0&&w.status<500&&w.status!==429||g===null&&!(w instanceof I)||Date.now()>j)throw w;await new Promise(A=>setTimeout(A,Math.min(250*2**Math.min(B,4),4e3)))}}function l(c){if(c.status!=="completed")throw new $(c);return c.text??""}function m(c,g){let h=Z(c,g?{schema:g.prepared.json,schema_name:g.name}:{},e.machine),y=[],k=!1,T,x=null,R=()=>{let f=x;x=null,f?.()},O,j,B=new Promise((f,S)=>{O=f,j=S});B.catch(()=>{});let w="",A=u(null,null,{admitted:f=>O(f.id),delta:(f,S)=>{w+=S,y.push(S),R()},reset:f=>{let S=he(w,f);w=w.slice(0,S),y.push("\0reset:"+S),R()}},c.signal,h).then(f=>{let S=f.status==="completed"?f.text??"":"";return S.length>w.length&&S.startsWith(w)&&(y.push(S.slice(w.length)),w=S),k=!0,R(),f},f=>{throw k=!0,T=f,j(f),R(),f});A.catch(()=>{});async function*M(){for(let f=0;;f++){for(;f>=y.length;){if(k){if(T)throw T;return}await new Promise(S=>x=S)}yield y[f]}}async function*H(){for await(let f of M())f.startsWith("\0reset:")||(yield f)}async function*nt(){let f="",S="";for await(let N of M()){N.startsWith("\0reset:")?f=f.slice(0,Number(N.slice(7))):f+=N;let E=ee(f);if(E===void 0)continue;let P=JSON.stringify(E);P!==S&&(S=P,yield E)}}let D=A.then(f=>{if(f.status!=="completed")throw new $(f);return f});D.catch(()=>{});let de=g?D.then(f=>g.prepared.check(f.output)):Promise.reject(new TypeError("object is a schema stream's"));de.catch(()=>{});let ce=D.then(f=>f.text??w);return ce.catch(()=>{}),{id:B,response:D,text:ce,get textStream(){return H()},get partialObjectStream(){return nt()},object:de,toResponse(f={}){let S=new TextEncoder,N=new ReadableStream({async start(P){try{for await(let U of M())U.startsWith("\0reset:")?P.enqueue(S.encode(`event: reset
8
+ data: ${JSON.stringify({offset:Number(U.slice(7))})}
9
+
10
+ `)):P.enqueue(S.encode(`data: ${JSON.stringify({text:U})}
11
+
12
+ `));let C=await D;P.enqueue(S.encode(`event: done
13
+ data: ${JSON.stringify({id:C.id,text:C.text,output:C.output,usage:C.usage})}
14
+
15
+ `))}catch(C){let U=C instanceof $||C instanceof I?C.code:"stream_failed";P.enqueue(S.encode(`event: error
16
+ data: ${JSON.stringify({code:U})}
17
+
18
+ `))}finally{P.close()}}}),E=new Headers(f.headers);return E.set("content-type","text/event-stream"),E.set("cache-control","no-store"),E.set("x-accel-buffering","no"),new globalThis.Response(N,{...f,headers:E})}}}async function s(c,g){return u(null,null,{admitted:()=>{},delta:()=>{},reset:()=>{}},c.signal,Z(c,g,e.machine))}let{chats:n,agents:r,endpoints:d,settings:p,repos:v}=Ve(t);return{module:t,chats:n,agents:r,endpoints:d,settings:p,repos:v,tool:je,clientTool:Be,deferred:$e,agent:Ue,repo:De,repoTokens:Ne,async ask(c,g={}){let h=typeof c=="string"?{...g,prompt:c}:c;return l(await s(h,{}))},async generate(c){let g=ie(c.schema),h={schema:g.prepared.json,schema_name:g.name};if(c.background){let T=(await a(Z(c,{...h,background:!0},e.machine),c.signal)).data;return{id:T.id,status:T.status}}let y=await s(c,h);if(y.status!=="completed")throw new $(y);return g.prepared.check(y.output)},stream(c){return m(c,c.schema?ie(c.schema):void 0)},async start(c){let g=(await a(Z(c,{background:!0},e.machine),c.signal)).data;return{id:g.id,status:g.status}},schema(c,g){return{name:c,schema:g,prepared:z(g,c)}},response:i,async result(c,g){let h=ie(g),y=await i(c);if(y.status!=="completed")throw new $(y);return h.prepared.check(y.output)},async cancel(c){return(await t.cancelResponse({path:{response_id:c}})).data},async embed(c,g={}){let h=Array.isArray(c)?c:[c],y=[];for(let k=0;k<h.length;k+=1024){let T=await t.createEmbeddings({body:{input:h.slice(k,k+1024),model:g.model,dimensions:g.dimensions},signal:g.signal});for(let x of T.data.vectors)y.push(It(x))}return Array.isArray(c)?y:y[0]},async image(c){let g={prompt:c.prompt};for(let k of["model","size","quality","background","format","count"])c[k]!==void 0&&(g[k]=c[k]);c.references?.length&&(g.references=await Promise.all(c.references.map(Qe))),c.mask&&(g.mask=await Qe(c.mask));let h=(await t.createImage({headers:{"Idempotency-Key":oe()},body:g,signal:c.signal})).data;for(let k=0;h.status==="running";k++){if(await new Promise(T=>setTimeout(T,Math.min(500+k*250,3e3))),c.signal?.aborted)throw c.signal.reason;h=(await t.getImage({path:{image_id:h.id},signal:c.signal})).data}if(h.status!=="completed")throw new Error(`the image failed: ${h.error?.code??"image_failed"}: ${h.error?.message??""}`);let y=await Promise.all(h.files.map(async k=>{let x=(await t.getImageFile({path:{image_id:h.id,position:k.position},signal:c.signal})).data;return{mediaType:k.media_type,bytes:new Uint8Array(await x.arrayBuffer())}}));return{id:h.id,model:h.model,pictures:y,costNanoUSD:h.usage?.cost_nano_usd??0,save(k,T,x=0){let R=y[x];if(!R)throw new RangeError(`the job made ${y.length} picture(s)`);return k.upload(T,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),h=(await t.listUsage({query:{kind:c.kind,limit:c.limit,cursor:c.cursor,metadata:g}})).data;return{usage:h.usage,nextCursor:h.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{ee as a,b,z as c,ne as d,$ as e,Ot as f};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
- import{a as k,b as S}from"./KLANM6M6.js";var T=class extends Error{status;error;data;body;constructor(t,a,l,d){let u=d!==null&&typeof d=="object"?d:{},i=u.error??String(l);super(`${t} ${a} \u2192 ${l} ${i}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=i,this.data=u.data,this.body=u}};function I(n,t){if(!n)throw new Error(`${t} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function R(n){let t=n.split(".")[1];if(!t)return null;try{let a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function x(n){try{return JSON.parse(n)}catch{return n}}function L(n){let t=I(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??t).replace(/\/+$/,""),d=n.fetch??fetch,u=[],i=null;async function c(r,e,s,o,f={},_=!0){let g={...f.headers},m=h=>Object.keys(g).some(O=>O.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),i&&_&&!m("authorization")&&(g.authorization=`Bearer ${i}`),o!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let P=Date.now(),p=await d(`${r}${s}`,{method:e,headers:g,body:o===void 0?void 0:JSON.stringify(o)}),E=await p.text(),A=E?x(E):void 0;if(u.push({method:e,path:s,status:p.status,ms:Date.now()-P}),!p.ok){let h=p.status===401&&i?R(i):null;throw h!==null&&h<=0?new T(e,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new T(e,s,p.status,A)}return A}let y={requests:u,get:(r,e)=>c(t,"GET",r,void 0,e),post:(r,e,s)=>c(t,"POST",r,e,s),patch:(r,e,s)=>c(t,"PATCH",r,e,s),put:(r,e,s)=>c(t,"PUT",r,e,s),delete:(r,e)=>c(t,"DELETE",r,void 0,e),query:(r,e,s)=>c(t,"QUERY",r,e,s),async signInAs(r){let e=n.identities?.[r];if(!e){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return e.accessToken?(i=e.accessToken,{id:e.id??"",email:e.email}):y.signIn(e)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let e=o=>c(l,"POST","/auth/login",r,o?{headers:o}:{},!1),s;try{s=await e()}catch(o){let f=o instanceof T&&o.status===403?k(o.body):null;if(!f)throw o;s=await e(await S(f))}return i=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),i=null},asAnonymous(){i=null}};return y}function b(n){if(!n)return{};let t;try{t=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return t}var $={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(b(process.env.PALBASE_TEST_IDENTITIES),n)}},w,U=new Proxy({},{get(n,t){return w??=L({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:b(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,t,w)}});export{T as a,L as b,$ as c,U as d};
1
+ /*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
2
+ import{a as k,b as S}from"./RO5Y5YU4.js";var T=class extends Error{status;error;data;body;constructor(t,a,l,d){let u=d!==null&&typeof d=="object"?d:{},i=u.error??String(l);super(`${t} ${a} \u2192 ${l} ${i}${u.error_description?`: ${u.error_description}`:""}`),this.name="TestApiError",this.status=l,this.error=i,this.data=u.data,this.body=u}};function I(n,t){if(!n)throw new Error(`${t} is not set: the test client has nowhere to send its requests \u2014 \`palbase test\` sets it, as the platform's test run does`);return n}function R(n){let t=n.split(".")[1];if(!t)return null;try{let a=JSON.parse(Buffer.from(t,"base64url").toString("utf8"));return typeof a.exp=="number"?a.exp-Math.floor(Date.now()/1e3):null}catch{return null}}function x(n){try{return JSON.parse(n)}catch{return n}}function L(n){let t=I(n.baseUrl,"PALBASE_TEST_BASE_URL").replace(/\/+$/,""),a=n.apiKey||void 0,l=(n.authUrl??t).replace(/\/+$/,""),d=n.fetch??fetch,u=[],i=null;async function c(r,e,s,o,f={},_=!0){let g={...f.headers},m=h=>Object.keys(g).some(O=>O.toLowerCase()===h);a!==void 0&&!m("apikey")&&(g.apikey=a),i&&_&&!m("authorization")&&(g.authorization=`Bearer ${i}`),o!==void 0&&!m("content-type")&&(g["content-type"]="application/json");let P=Date.now(),p=await d(`${r}${s}`,{method:e,headers:g,body:o===void 0?void 0:JSON.stringify(o)}),E=await p.text(),A=E?x(E):void 0;if(u.push({method:e,path:s,status:p.status,ms:Date.now()-P}),!p.ok){let h=p.status===401&&i?R(i):null;throw h!==null&&h<=0?new T(e,s,p.status,{error:"access_token_expired",error_description:`this run's access token expired ${-h}s ago: a test user's token is made for one run \u2014 run the tests again (\`palbase test\` makes new ones)`}):new T(e,s,p.status,A)}return A}let y={requests:u,get:(r,e)=>c(t,"GET",r,void 0,e),post:(r,e,s)=>c(t,"POST",r,e,s),patch:(r,e,s)=>c(t,"PATCH",r,e,s),put:(r,e,s)=>c(t,"PUT",r,e,s),delete:(r,e)=>c(t,"DELETE",r,void 0,e),query:(r,e,s)=>c(t,"QUERY",r,e,s),async signInAs(r){let e=n.identities?.[r];if(!e){let s=Object.keys(n.identities??{});throw s.length===0?new Error(`no test user named ${JSON.stringify(r)}: this run has no test users \u2014 none were named (the machine's test users, or \`palbase test --users <names>\`), or they could not be made: the run's log says which`):new Error(`no test user named ${JSON.stringify(r)} \u2014 this run has: ${s.join(", ")}. A run makes the test users its machine names (palbase machines:update <machine> --test-users <names>) or \`palbase test --users <names>\` names`)}return e.accessToken?(i=e.accessToken,{id:e.id??"",email:e.email}):y.signIn(e)},async signIn(r){if(a===void 0)throw new Error("PALBASE_TEST_API_KEY is not set: a sign-in at the project's auth is made with a publishable key of the project's (palbase apps:sdkconfig shows one) \u2014 a run's test users come with their tokens: api.signInAs(name)");let e=o=>c(l,"POST","/auth/login",r,o?{headers:o}:{},!1),s;try{s=await e()}catch(o){let f=o instanceof T&&o.status===403?k(o.body):null;if(!f)throw o;s=await e(await S(f))}return i=s.access_token,s.user??{id:""}},async signOut(){await c(l,"POST","/auth/logout",void 0),i=null},asAnonymous(){i=null}};return y}function b(n){if(!n)return{};let t;try{t=JSON.parse(n)}catch{throw new Error("PALBASE_TEST_IDENTITIES is set but is not JSON: the run that started these tests handed over a broken set of test users")}if(t===null||typeof t!="object"||Array.isArray(t))throw new Error("PALBASE_TEST_IDENTITIES is not an object of test users by name");return t}var $={get stack(){return!!process.env.PALBASE_TEST_BASE_URL},minted(n){return Object.prototype.hasOwnProperty.call(b(process.env.PALBASE_TEST_IDENTITIES),n)}},w,U=new Proxy({},{get(n,t){return w??=L({baseUrl:process.env.PALBASE_TEST_BASE_URL??"",apiKey:process.env.PALBASE_TEST_API_KEY??"",authUrl:process.env.PALBASE_TEST_AUTH_URL,identities:b(process.env.PALBASE_TEST_IDENTITIES)}),Reflect.get(w,t,w)}});export{T as a,L as b,$ as c,U as d};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
1
+ /*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
2
2
  var u="X-PoW-Challenge-ID",c="X-PoW-Nonce";function m(e){if(typeof e!="object"||e===null)return null;let t=e;if(t.error!=="pow_required"||typeof t.challenge!="object"||t.challenge===null)return null;let{id:n,prefix:r,difficulty:o}=t.challenge;return typeof n!="string"||typeof r!="string"||typeof o!="number"||!Number.isInteger(o)||o<0?null:{id:n,prefix:r,difficulty:o}}function d(e){return 8*2**e}var s;async function l(){if(s)return s;let e=globalThis;if(e.process?.versions?.node!==void 0||e.process?.versions?.bun!==void 0)try{let r=(await import("node:crypto")).createHash;if(typeof r=="function")return s=o=>new Uint8Array(r("sha256").update(o).digest()),s}catch{}let t=new TextEncoder;return s=async n=>new Uint8Array(await crypto.subtle.digest("SHA-256",t.encode(n))),s}function p(e){let t=0;for(let n of e){if(n===0){t+=8;continue}return t+Math.clz32(n)-24}return t}var w=4096,g=typeof globalThis.setImmediate=="function"?()=>new Promise(e=>globalThis.setImmediate(e)):()=>new Promise(e=>setTimeout(e,0));async function y(e,t={}){if(e.difficulty>24)throw new Error(`proof-of-work: difficulty ${e.difficulty} is above auth's ceiling of 24`);let n=await l(),r=d(e.difficulty),o=Date.now()+(t.timeLimitMs??12e4);for(let i=0;i<r;i++){if(i%w===0&&i>0){if(await g(),t.signal?.aborted)throw t.signal.reason??new DOMException("proof-of-work aborted","AbortError");if(Date.now()>o)throw new Error(`proof-of-work: gave up on difficulty ${e.difficulty} after ${i} attempts`)}let f=n(e.prefix+i),a=f instanceof Uint8Array?f:await f;if(p(a)>=e.difficulty)return{[u]:e.id,[c]:String(i)}}throw new Error(`proof-of-work: no nonce for difficulty ${e.difficulty} within ${r} attempts`)}export{m as a,y as b};
@@ -1,2 +1,2 @@
1
- /*! palbase 0.6.2 — Palbase SDK License (see LICENSE) */
2
- import"./A3CDCPXX.js";import{pathToFileURL as i}from"node:url";import{z as c}from"zod";async function f(e){let n=new Map,t=new Map;for(let r of e){let a=`${r.className}.${r.method}`,o=t.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(r.className,r.file),n.set(a,{returns:await u(r),throws:r.throws})}return r=>n.get(`${r.controller.name}.${r.fn}`)}async function u(e){let n=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(i(e.returns.file).href))[e.returns.exportName];if(!s(r))throw new Error(`${n}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);return{kind:"json",schema:r,array:e.returns.array}}case"expression":{let t=new Function("z",`return (${e.returns.expression});`)(c);if(!s(t))throw new Error(`${n}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function s(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{f as routeContracts};
1
+ /*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
2
+ import"./JSJVV43D.js";import{pathToFileURL as i}from"node:url";import{z as c}from"zod";async function f(e){let n=new Map,t=new Map;for(let r of e){let a=`${r.className}.${r.method}`,o=t.get(r.className);if(o!==void 0&&o!==r.file)throw new Error(`two controllers are named ${r.className} (${o}, ${r.file}): the contract tells routes apart by their class's name \u2014 rename one`);t.set(r.className,r.file),n.set(a,{returns:await u(r),throws:r.throws})}return r=>n.get(`${r.controller.name}.${r.fn}`)}async function u(e){let n=`${e.file} \u2014 ${e.className}.${e.method}`;switch(e.returns.kind){case"void":return{kind:"void"};case"raw":return{kind:"raw"};case"schema":{let r=(await import(i(e.returns.file).href))[e.returns.exportName];if(!s(r))throw new Error(`${n}: its return type names ${e.returns.exportName}, which ${e.returns.file} exports as no schema (a zod, valibot or arktype schema)`);return{kind:"json",schema:r,array:e.returns.array}}case"expression":{let t=new Function("z",`return (${e.returns.expression});`)(c);if(!s(t))throw new Error(`${n}: the schema made of its return type is not one`);return{kind:"json",schema:t,array:!1}}}}function s(e){return typeof e=="object"&&e!==null&&typeof e["~standard"]?.validate=="function"}export{f as routeContracts};
@@ -0,0 +1,13 @@
1
+ /*! palbase 0.8.0 — Palbase SDK License (see LICENSE) */
2
+ import{b as j,c as A,d as R}from"./P4Z5E6ZI.js";import{d as G}from"./BO5KR2EQ.js";import{a as k,b as L,c as _,e as $}from"./PDOHT46N.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 K(t){return t instanceof l||typeof t=="object"&&t!==null&&t.name==="BackendError"&&typeof t.kind=="string"}function N(t){let e=t.body,n={code:t.code,message:t.message,status:t.status,requestId:t.requestId??ke(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:be(e)??t.retryAfter});let s=ve(e);return t.status===400&&s?new l("validation",{...n,fields:s}):new l("server",n)}function T(t){return t instanceof L||t instanceof Error&&t.name==="PalbaseError"}function F(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 ve(t){let e=E(E(t,"data"),"fields");if(F(e))return e;let n=E(t,"fields");return F(n)?n:void 0}function be(t){return W(t,"retry_after")??W(E(t,"data"),"retryAfter")}function E(t,e){if(typeof t=="object"&&t!==null)return t[e]}function W(t,e){let n=E(t,e);return typeof n=="number"?n:void 0}function ke(t,e){let n=E(t,e);return typeof n=="string"?n:void 0}var _e=/^[A-Za-z_$][A-Za-z0-9_$]*$/,Ee=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__"]),xe=new Set(Ee),Ce=new Set(["constructor","hasOwnProperty","isPrototypeOf","propertyIsEnumerable","toLocaleString","toString","valueOf","__proto__","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"]);function P(t){return t==="then"||t==="toJSON"||Ce.has(t)}function H(t){return t==="call"||t==="join"||P(t)}function U(t){return typeof t=="string"&&_e.test(t)&&!xe.has(t)&&!P(t)}function V(t){return typeof t=="string"&&/^[a-z][a-z0-9-]{0,62}$/.test(t)}function z(t){$(t)}function Q(t){return $(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 o=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(o,s)}if(this.ended)return!1;let a=(r?.parts??[]).map(o=>j(o)).filter(o=>o!==void 0);return this.older=[...a,...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 a=this.state;if(a!==n){n=a,yield a;continue}if(this.ended)return;await new Promise(o=>e=o)}}finally{s(),this.enders.delete(r)}}end(){if(!this.ended){this.ended=!0;for(let e of[...this.enders])e()}}takePayload(e){let n=j(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:A(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:A(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,R(n.text,e.offset))+e.text;break}case"reset":{let n=this.response(e.response_id);n.text=n.text.slice(0,R(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=Re(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?Y(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,a=s!==null&&![...this.messages.entries()].some(([o,d])=>o!==n&&d.responseId===s)?this.order.findIndex(o=>o.type==="response"&&o.key===s):-1;a>=0?this.order.splice(a,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=i=>e!==void 0&&i.startedBy===e,s=new Map;for(let i of this.responses.values()){let c=i.parentId!==null?this.responses.get(i.parentId)??i:i;s.set(i.id,Te(i,c.startedBy??null,n(c),i.goal??c.goal))}let r=new Map([...this.messages].map(([i,c])=>[i,e!==void 0&&c.author===e?{...c,mine:!0}:c])),a=[...this.history.entries()].sort(([i],[c])=>i-c).flatMap(([i,c])=>c.map((b,w)=>Pe(b,`${i}:${w}`,e))),o=[...a];for(let i of this.order)i.type==="goal"?o.push({type:"goal",goal:i.event}):i.type==="voice"?o.push({type:"voice",voice:i.event}):i.type==="message"?o.push({type:"message",message:r.get(i.key)}):this.responses.get(i.key).parentId===null&&o.push({type:"response",response:s.get(i.key)});let d=a.flatMap(i=>i.type==="message"?[i.message]:[]),u=a.flatMap(i=>i.type==="response"?[i.response]:[]),p=[...this.calls.values()].filter(i=>s.get(i.response_id)?.mine===!0);return{items:o,messages:[...d,...r.values()],responses:[...u,...s.values()],turn:this.turn,waiting:{approvals:p.filter(i=>i.status==="awaiting_approval"),outputs:p.filter(i=>i.status==="awaiting_output")},goal:this.goal,forkedFrom:this.forkedFrom,voice:this.voice?Se(this.voice,e):null}}};function Se(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 Y(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 Re(t){return`${t.author??""}\0${t.client_id}`}function Te(t,e,n,s){let r=[...t.marks.values()].map((u,p)=>({m:u,i:p,at:R(t.text,Math.max(0,Number(u.text_offset)||0))}));r.sort((u,p)=>u.at-p.at||u.i-p.i);let a=[],o=[],d=0;for(let{m:u,at:p}of r)p>d&&a.push({type:"text",text:t.text.slice(d,p)}),d=Math.max(d,p),u.type==="thinking"?(a.push({type:"thinking",thinking:u.thinking}),o.push(u.thinking)):a.push(u.type==="tool"?{type:"tool",tool:u}:{type:"agent",agent:u});return d<t.text.length&&a.push({type:"text",text:t.text.slice(d)}),{id:t.id,status:t.status,waiting:t.waiting,end:t.end,error:t.error,text:t.text,parts:a,runId:t.runId,agent:t.agent,parentId:t.parentId,startedBy:e,mine:n,thinking:o,goal:s,history:!1,truncated:!1}}function Pe(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:Y(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 M=[["ApiKeyAuth","userJWT"]];function Z(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:M,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:M,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 a={path:n};return s!==void 0&&(a.manifest=s),(await t.send({op:"GetChatWorkspaceFile",method:"GET",path:`/ai/chats/${_("GetChatWorkspaceFile","chat_id",e)}/workspace/files`,auth:M,answers:{200:"raw"},query:a,signal:r})).data.blob()}}}var O=class extends Error{reason;constructor(e,n){super(e),this.name="GatewayError",this.reason=n}},X=new WeakMap;async function te(t,e,n,s={},r=()=>{},a){let{pattern:o,events:d,messages:u,durable:p,chat:i}=Ie(e),c=Oe(o,n),b=X.get(t);b||X.set(t,b=new Map);let w=b,g=w.get(c)??{count:0};w.set(c,g),g.count++;let f=t.channel(c,p&&s.history!==!1?{after:0}:{});if(i&&!g.chat){let h=n.chatId,v=new I(r,a,typeof h=="string"&&h!==""?h:void 0);g.chat=v,g.unchat=f.on("broadcast",y=>{y.event==="chat"&&v.takePayload(y.payload)})}let x=()=>{--g.count>0||(w.delete(c),g.unchat?.(),g.chat?.end(),f.leave())};try{await f.join()}catch{let h=f.state==="refused"?ee(f.refusal,"unavailable"):"socket closed";throw x(),new O(`gateway ${JSON.stringify(c)} was not joined: ${h}`,h)}let C=!1,S=new Set,B=()=>{if(!C){C=!0,we();for(let h of[...S])h();x()}},we=f.onClosed(B),q=h=>{if(C)return()=>{};let v=f.on("broadcast",m=>{typeof m.event=="string"&&d.has(m.event)&&h(m.event,k(m.payload))}),y=()=>{S.delete(y),v()};return S.add(y),y},J={topic:c,get seq(){return f.logSeq},on(h,v){if(typeof h=="function")return q((y,m)=>h({event:y,payload:m}));if(!d.has(h))throw new TypeError(`gateway ${JSON.stringify(o)} declares no event ${JSON.stringify(String(h))}`);if(typeof v!="function")throw new TypeError(`gateway ${JSON.stringify(o)}: on(${JSON.stringify(h)}, \u2026) takes the function the event is handed to`);return q((y,m)=>{y===h&&v(m)})},off(h){S.has(h)&&h()},async send(h,v){if(!u.has(h))throw new TypeError(`gateway ${JSON.stringify(o)} declares no message ${JSON.stringify(String(h))}`);let y=C?{status:"error",response:{reason:"not joined"}}:await f.push("broadcast",{type:"broadcast",event:h,payload:v});if(y.status==="ok")return k(y.response.reply);let m=ee(y.response,"unavailable");throw new O(`gateway ${JSON.stringify(c)} did not take ${JSON.stringify(h)}: ${m}`,m)},leave:B};return i&&Object.defineProperty(J,"chat",{value:g.chat,enumerable:!0}),J}function Ie(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 Oe(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),a=Object.hasOwn(n,r)?n[r]:void 0;if(typeof a!="string"||a==="")throw new TypeError(`gateway ${JSON.stringify(t)} needs a value for ${JSON.stringify(r)}`);if(a.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 a}).join(":")}function ee(t,e){let n=t?.reason;return typeof n=="string"&&n!==""?n:e}var D=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 a=r.endsWith("\r")?r.slice(0,-1):r;if(a==="")this.dataLines.length>0&&n.push({event:this.eventName,payload:this.dataLines.join(`
5
+ `)}),this.dataLines=[],this.eventName=void 0;else if(!a.startsWith(":")){if(a.startsWith("data:")){let o=a.slice(5);this.dataLines.push(o.startsWith(" ")?o.slice(1):o)}else if(a.startsWith("event:")){let o=a.slice(6);this.eventName=o.startsWith(" ")?o.slice(1):o}}s=this.pending.indexOf(`
6
+ `)}return n}};async function*ne(t,e){let n=t.getReader(),s=new TextDecoder,r=new D;try{for(;;){let{done:a,value:o}=await n.read();if(a)break;for(let d of r.consume(s.decode(o,{stream:!0}))){if(d.event==="error")throw new l("network",{code:"stream_failed",message:`stream failed: ${d.payload}`});let u;try{u=JSON.parse(d.payload)}catch{throw new l("decode",{code:"invalid_frame",message:`stream frame is not valid JSON: ${d.payload.slice(0,120)}`})}yield k(u)}}}finally{e.abort();try{await n.cancel()}catch{}}}var $e={},re=new WeakMap;function pt(t,e,n,s,r,a=()=>{}){re.set(t,{project:e,machine:n,storage:s,socket:r,me:a})}var ae=new Map,se=new WeakMap;function ht(t,e,n,s,r){if(!U(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=Q(t);if(!V(n))throw new TypeError(`${JSON.stringify(String(n))} is not a machine's name: a lowercase letter, then lowercase letters, digits and -`);z(s),de(r);for(let o of Object.keys(r))if(H(o))throw oe(o);(ae.get(e)??Ge(e)).set(a,{machine:n,url:s,tree:r})}function Ge(t){let e=new Map;return ae.set(t,e),Object.defineProperty($e,t,{configurable:!0,get(){return je(this,t,e)}}),e}function je(t,e,n){let s=re.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 a=se.get(t);a||se.set(t,a=new Map);let o=a.get(e);if(o?.registration===r)return o.ns;let d={machine:()=>s.machine(r.url),storage:s.storage,name:r.machine},u=Object.assign({call:(p,i,c)=>qe(d.machine,p,i,c),join:(p,i,c)=>te(s.socket,p,i,c,s.me,Z(s.storage))},le(r.tree,d));return a.set(e,{registration:r,ns:u}),u}function oe(t){return new l("validation",{code:"reserved_namespace",message:`Cannot register endpoint namespace ${JSON.stringify(t)}: the name is reserved.`})}function ie(t){return typeof t.path=="string"&&typeof t.method=="string"}function Ae(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.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 de(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 oe(n);typeof s=="object"&&s!==null&&ie(s)?(s.method=s.method.toUpperCase(),Ae(s,s.path)):de(s)}}function le(t,e){if(ie(t))return t.upload===!0?async(...s)=>De(e,t,s):async(...s)=>he(e.machine(),t,s);let n={};for(let[s,r]of Object.entries(t))n[s]=le(r,e);return n}function ue(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 ce(t,e,n){try{return _(t.path,e,n)}catch(s){if(!T(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 pe(t,e){let n=t.pathParams??[],s=t.path;for(let r=0;r<n.length;r++){let a=e[r];if(typeof a!="string"&&typeof a!="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]}}`,ce(t,`path parameter '${n[r]}'`,a))}return s}var Ne=new Set(["POST","PUT","PATCH","DELETE"]);async function he(t,e,n){let s=e.pathParams??[],r=pe(e,n);if(e.input==="none"&&n.length>s.length+1)throw new l("validation",{code:"unexpected_argument",message:`${e.path}: endpoint takes no input \u2014 pass only path params and options`});let a=e.input==="none"?void 0:n[s.length],o=e.input==="none"?s.length:s.length+1,d=n[o],u;if(e.input==="query")r+=ue(a);else if(e.input!=="none")if(e.method==="GET"){if(a!==void 0)throw new l("validation",{code:"unsupported_get_input",message:`${e.path}: GET endpoints take no body input`})}else u=a;let p={...d?.headers};Ne.has(e.method)&&!Object.keys(p).some(i=>i.toLowerCase()==="idempotency-key")&&(p["Idempotency-Key"]=G());try{return e.sse===!0?await Fe(t,e,r,u,p,d?.signal):await Le(t,e,r,u,p,d?.signal)}catch(i){throw ge(e,i)}}function ge(t,e){return t.errors&&K(e)&&Object.hasOwn(t.errors,e.code)?t.errors[e.code](e):e}var Me=[["ApiKeyAuth","userJWT"],["ApiKeyAuth"]];async function De(t,e,n){let s=e.pathParams??[],r=pe(e,n),a=e.input==="none"?s.length:s.length+1;if(n.length>a+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 o=e.input==="none"?void 0:n[s.length],d=n[a],u=n[a+1];if(!(d 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}/${ce(e,"the route",r.slice(1))}`;e.input==="query"&&(p+=ue(o));let i=Be(e.input==="query"?void 0:o,d),c=i.body.size,b=0,w=g=>{b=g;try{u?.onProgress?.({loaded:g,total:c})}catch{}};u?.onProgress&&w(0);try{let g;try{let f={op:`Upload ${e.path}`,method:"POST",path:p,auth:Me,answers:fe,body:{kind:"raw",contentType:i.type,value:i.body},signal:u?.signal,...u?.onProgress?{onUploadProgress:x=>w(x)}:{}};g=(await t.storage.send(f)).data}catch(f){throw T(f)?N(f):f}return u?.onProgress&&b<c&&w(c),await me(e,g,u?.signal)}catch(g){throw ge(e,g)}}function Be(t,e){let n=`Palbase-${G()}`,s=d=>d.replaceAll('"',"_").replace(/[\r\n]/g,""),r=typeof e.name=="string"?e.name:"blob",a=(d,u)=>`--${n}\r
7
+ Content-Disposition: form-data; ${d}\r
8
+ Content-Type: ${u}\r
9
+ \r
10
+ `,o=[];return t!==void 0&&o.push(a('name="body"',"application/json"),JSON.stringify(t),`\r
11
+ `),o.push(a(`name="file"; filename="${s(r)}"`,s(e.type)||"application/octet-stream"),e,`\r
12
+ --${n}--\r
13
+ `),{body:new Blob(o),type:`multipart/form-data; boundary=${n}`}}async function qe(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 he(t(),{method:"POST",path:r},[n,s])}var fe=Object.fromEntries(Array.from({length:100},(t,e)=>[200+e,"raw"])),Je=[["userJWT"],[]];async function ye(t,e,n,s,r,a){let o={op:`${e.method} ${e.path}`,method:e.method,path:n,auth:Je,answers:fe,headers:r,...s===void 0?{}:{body:{kind:"json",contentType:"application/json",value:s}},idempotent:e.idempotent===!0,signal:a};try{return(await t.send(o)).data}catch(d){throw T(d)?N(d):d}}async function Le(t,e,n,s,r,a){return me(e,await ye(t,e,n,s,r,a),a)}async function me(t,e,n){let s=e.headers.get("x-request-id")??void 0,r;try{r=await e.text()}catch(a){throw n?.aborted?a:new l("network",{code:"network_error",message:`${t.method} ${t.path}: the answer did not arrive whole`,status:e.status,requestId:s,cause:a})}if(r!=="")try{return k(JSON.parse(r))}catch(a){throw new l("decode",{code:"invalid_json",message:`${t.method} ${t.path}: the answer is not JSON`,status:e.status,requestId:s,cause:a})}}async function Fe(t,e,n,s,r,a){let o=new AbortController;a&&(a.aborted?o.abort():a.addEventListener("abort",()=>o.abort(),{once:!0}));let d=await ye(t,e,n,s,{accept:"text/event-stream",...r},o.signal);if(!d.body)throw new l("network",{code:"empty_stream",message:"the server answered a streaming route with no body",status:d.status});return ne(d.body,o)}export{l as a,K as b,Ee as c,U as d,Z as e,O as f,$e as g,pt as h,ht as i};