@soba-so/sdk 0.0.27 → 0.0.28

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- var Fe="soba-e2e-wrap-v1",We="soba-e2e-request-v1",W="e1.",S=new TextEncoder,Ne=new TextDecoder;async function X(){let t=crypto.getRandomValues(new Uint8Array(32));return{raw:t,key:await he(t)}}var z="sobarunkey1.";async function ge(t){let e=await crypto.subtle.importKey("raw",S.encode(t),"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:S.encode("soba-e2e-run-key-wrap")},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Y(t,e){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:n},await ge(e),t.raw));return`${z}${P(n)}.${P(r)}`}async function N(t,e){if(!t.startsWith(z))throw new Error("not a run key");let[n,r]=t.slice(z.length).split(".");if(!n||!r)throw new Error("not a run key");let i=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:C(n)},await ge(e),C(r)));return{raw:i,key:await he(i)}}function Q(){return`th_${[...crypto.getRandomValues(new Uint8Array(9))].map(t=>t.toString(16).padStart(2,"0")).join("")}`}async function me(t,e){let n=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),r=P(new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey))),i=await crypto.subtle.importKey("raw",C(t),{name:"X25519"},!1,[]),u=await crypto.subtle.deriveBits({name:"X25519",public:i},n.privateKey,256),s=await crypto.subtle.importKey("raw",u,"HKDF",!1,["deriveKey"]),a=await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:S.encode(`${r}.${t}`),info:S.encode("soba-passport-seal-v1")},s,{name:"AES-GCM",length:256},!1,["encrypt"]),c=crypto.getRandomValues(new Uint8Array(12)),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:c},a,S.encode(e)));return JSON.stringify({v:1,epk:r,iv:P(c),ct:P(l.subarray(0,-16)),tag:P(l.subarray(-16))})}async function Z(t,e,n){let r=await Promise.all(n.map(async({publicKey:s})=>{let a=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),c=P(new Uint8Array(await crypto.subtle.exportKey("raw",a.publicKey))),l=await crypto.subtle.importKey("raw",C(s),{name:"X25519"},!1,[]),g=await crypto.subtle.deriveBits({name:"X25519",public:l},a.privateKey,256),o=await crypto.subtle.importKey("raw",g,"HKDF",!1,["deriveKey"]),d=await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:S.encode(`${c}.${s}`),info:S.encode(Fe)},o,{name:"AES-GCM",length:256},!1,["encrypt"]),p=crypto.getRandomValues(new Uint8Array(12)),f=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:p},d,t.raw));return{kid:s,epk:c,iv:P(p),ct:P(f)}})),i=crypto.getRandomValues(new Uint8Array(12)),u=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:S.encode(We)},t.key,S.encode(JSON.stringify(e))));return{v:1,keys:r,iv:P(i),ct:P(u)}}async function q(t,e){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:n,additionalData:S.encode("soba-e2e-down")},t.key,S.encode(JSON.stringify(e===void 0?null:e))));return`${W}${P(n)}.${P(r)}`}async function A(t,e){if(!e.startsWith(W))throw new Error("not a sealed frame");let[n,r]=e.slice(W.length).split(".");if(!n||!r)throw new Error("not a sealed frame");let i=await crypto.subtle.decrypt({name:"AES-GCM",iv:C(n),additionalData:S.encode("soba-e2e-up")},t.key,C(r));return JSON.parse(Ne.decode(i))}function M(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t.$sealed;return typeof e=="string"&&e.startsWith(W)?e:void 0}async function ee(t){let n=[...new Uint8Array(await crypto.subtle.digest("SHA-256",C(t))).subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return n.match(/.{4}/g)?.join(" ")??n}function fe(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.machine=="string"&&typeof e.publicKey=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e.publicKey)}function he(t){return crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}function P(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(t){let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}var m=class extends Error{code;type;status;retryable;retryAfterMs;runId;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="SobaError",this.code=e.code,this.type=e.type??e.code,this.status=e.status,this.retryable=e.retryable??je.has(e.code),this.retryAfterMs=e.retryAfterMs,this.runId=e.runId}},je=new Set(["rate_limited","server_error","connection","timeout","stream_truncated"]),Be={400:"invalid_request",401:"unauthorized",402:"payment_required",403:"forbidden",404:"not_found",409:"no_compute",422:"user_required",429:"rate_limited"};function Ge(t){let e=Be[t];return e||(t>=500?"server_error":t>=400?"invalid_request":"unknown")}var ye=new WeakSet;function we(t){return ye.has(t)}async function be(t){let e=t.status,n="";try{n=await t.text()}catch{}let r=He(n),i=new m({code:r?.code??Ge(e),type:r?.type,message:r?.message??Ve(e,t.statusText,n),status:e,retryAfterMs:ze(t.headers.get("retry-after")),runId:t.headers.get("soba-run-id")??void 0});return!r&&(e===502||e===503||e===504)&&ye.add(i),i}function He(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e.error;if(!n||typeof n!="object")return null;let r=n;return{message:typeof r.message=="string"&&r.message?r.message:void 0,type:typeof r.type=="string"&&r.type?r.type:void 0,code:Je.has(r.code)?r.code:void 0}}var Je=new Set(["invalid_request","user_required","unauthorized","payment_required","forbidden","not_found","no_compute","unknown_run","not_resumable","machine_gone","rate_limited","server_error","connection","timeout","stream_truncated","run_failed","canceled","not_allowed","outside_roots","busy","unknown"]);function Ve(t,e,n){let r=n.trim().slice(0,200),i=r?`: ${r}`:"";return`Soba returned ${t}${e?` ${e}`:""}${i}`}function ze(t){if(!t)return;let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.round(e*1e3);let n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,n-Date.now())}function v(t){if(t instanceof m)return t;let e=t;return e?.name==="AbortError"||e?.name==="TimeoutError"?new m({code:"canceled",message:e.message||"The request was aborted.",retryable:!1,cause:t}):new m({code:"connection",message:e?.message?`Could not reach Soba: ${e.message}`:"Could not reach Soba.",cause:t})}var te="0.0.27";var Xe=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]);function ne(t){if(t.code==="rate_limited")return!0;if(t.code!=="connection")return!1;let e=t.cause;for(let n=0;e&&n<4;n++){let r=e.code;if(typeof r=="string"&&Xe.has(r))return!0;e=e.cause}return!1}var Ye=8e3,Qe=3e4;async function x(t,e){let n=tt(t.baseURL,e.path,e.query),r=e.retry===!1?1:Math.max(0,t.maxRetries)+1,i,u=s=>s.retryable&&(e.retry!=="unsent"||ne(s));for(let s=0;s<r;s++){s>0&&await re(nt(s,i),e.signal);let a=new AbortController,c=D(e.signal,a),l=setTimeout(()=>{a.abort(new m({code:"timeout",message:`Soba did not answer within ${t.connectTimeoutMs}ms.`}))},t.connectTimeoutMs),g;try{g=await t.fetch(n,{method:e.method,headers:Ze(t,e),body:e.body===void 0?void 0:JSON.stringify(e.body),signal:a.signal})}catch(o){if(c(),i=v(a.signal.aborted?a.signal.reason??o:o),!u(i)||s===r-1)throw i;continue}finally{clearTimeout(l)}if(g.ok)return g;if(c(),i=await be(g),!u(i)||s===r-1)throw i}throw i??new m({code:"unknown",message:"The request failed with no error."})}async function b(t,e){let n=await x(t,{accept:"application/json",...e}),r=await n.text();if(r)try{return JSON.parse(r)}catch(i){throw new m({code:"server_error",message:`Soba returned a body that is not JSON: ${r.slice(0,200)}`,status:n.status,cause:i})}}function Ze(t,e){let n={authorization:`Bearer ${t.apiKey}`,accept:e.accept??"application/json","user-agent":et(),...t.headers};return e.body!==void 0&&(n["content-type"]="application/json"),n}function et(){let t=typeof process>"u"?"":` node/${process.versions?.node??"?"}`;return`soba-sdk/${te}${t}`}function tt(t,e,n){let r=t.replace(/\/+$/,""),i=new URL(`${r}${e.startsWith("/")?e:`/${e}`}`);for(let[u,s]of Object.entries(n??{}))s!==void 0&&i.searchParams.set(u,String(s));return i.toString()}function nt(t,e){if(e?.retryAfterMs!==void 0)return Math.min(e.retryAfterMs,Qe);let n=Math.min(Ye,500*2**(t-1));return Math.round(n*(.5+Math.random()/2))}function re(t,e){return new Promise((n,r)=>{if(e?.aborted)return r(v(e.reason));let i=setTimeout(()=>{e?.removeEventListener("abort",u),n()},t);function u(){clearTimeout(i),r(v(e?.reason))}e?.addEventListener("abort",u,{once:!0})})}function D(t,e){if(!t)return()=>{};if(t.aborted)return e.abort(t.reason),()=>{};let n=()=>e.abort(t.reason);return t.addEventListener("abort",n,{once:!0}),()=>t.removeEventListener("abort",n)}var rt=5*60*1e3,ke=25,st=1e3,ot=100,j=class{#t;#o;#s;#n=null;#i=0;#a=null;#e=[];#r=null;constructor(e){this.#t=e.http,this.#o=e.onWarning,this.#s=e.off}async prime(){if(!this.#s)return this.#u()}#u(){return this.#a??=b(this.#t,{method:"GET",path:"/fallback",retry:!1}).then(e=>{this.#n={enabled:e?.enabled===!0,providers:(e?.providers??[]).map(Te).filter(Pe)},this.#i=Date.now()}).catch(()=>{}).finally(()=>{this.#a=null}),this.#a}refreshSoon(){this.#s||Date.now()-this.#i<rt||this.prime()}get pending(){return this.#e.length}canServe(e,n){if(this.#s)return!1;let r=v(e);return!ne(r)&&!we(r)||r.code==="rate_limited"?!1:this.#l(n).length>0}serve(e,n,r){let i=new AbortController,u=D(n,i),s=i.signal,a=new Map,c=new Map,l=f=>{let h=a.get(f.callId);h?(a.delete(f.callId),h(f)):c.set(f.callId,f)},g=f=>new Promise((h,w)=>{let k=c.get(f);if(k)return c.delete(f),h(k);a.set(f,h),s.addEventListener("abort",()=>w(v(s.reason)),{once:!0})}),o=r??this.#l(e.route),d=new TextEncoder,p=new ReadableStream({start:f=>{let h=w=>{try{f.enqueue(d.encode(`data: ${JSON.stringify(w)}
1
+ var Fe="soba-e2e-wrap-v1",We="soba-e2e-request-v1",W="e1.",S=new TextEncoder,Ne=new TextDecoder;async function X(){let t=crypto.getRandomValues(new Uint8Array(32));return{raw:t,key:await he(t)}}var z="sobarunkey1.";async function ge(t){let e=await crypto.subtle.importKey("raw",S.encode(t),"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:S.encode("soba-e2e-run-key-wrap")},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function Y(t,e){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:n},await ge(e),t.raw));return`${z}${P(n)}.${P(r)}`}async function N(t,e){if(!t.startsWith(z))throw new Error("not a run key");let[n,r]=t.slice(z.length).split(".");if(!n||!r)throw new Error("not a run key");let i=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:C(n)},await ge(e),C(r)));return{raw:i,key:await he(i)}}function Q(){return`th_${[...crypto.getRandomValues(new Uint8Array(9))].map(t=>t.toString(16).padStart(2,"0")).join("")}`}async function me(t,e){let n=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),r=P(new Uint8Array(await crypto.subtle.exportKey("raw",n.publicKey))),i=await crypto.subtle.importKey("raw",C(t),{name:"X25519"},!1,[]),u=await crypto.subtle.deriveBits({name:"X25519",public:i},n.privateKey,256),s=await crypto.subtle.importKey("raw",u,"HKDF",!1,["deriveKey"]),a=await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:S.encode(`${r}.${t}`),info:S.encode("soba-passport-seal-v1")},s,{name:"AES-GCM",length:256},!1,["encrypt"]),c=crypto.getRandomValues(new Uint8Array(12)),l=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:c},a,S.encode(e)));return JSON.stringify({v:1,epk:r,iv:P(c),ct:P(l.subarray(0,-16)),tag:P(l.subarray(-16))})}async function Z(t,e,n){let r=await Promise.all(n.map(async({publicKey:s})=>{let a=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),c=P(new Uint8Array(await crypto.subtle.exportKey("raw",a.publicKey))),l=await crypto.subtle.importKey("raw",C(s),{name:"X25519"},!1,[]),g=await crypto.subtle.deriveBits({name:"X25519",public:l},a.privateKey,256),o=await crypto.subtle.importKey("raw",g,"HKDF",!1,["deriveKey"]),d=await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:S.encode(`${c}.${s}`),info:S.encode(Fe)},o,{name:"AES-GCM",length:256},!1,["encrypt"]),p=crypto.getRandomValues(new Uint8Array(12)),f=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:p},d,t.raw));return{kid:s,epk:c,iv:P(p),ct:P(f)}})),i=crypto.getRandomValues(new Uint8Array(12)),u=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:i,additionalData:S.encode(We)},t.key,S.encode(JSON.stringify(e))));return{v:1,keys:r,iv:P(i),ct:P(u)}}async function q(t,e){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:n,additionalData:S.encode("soba-e2e-down")},t.key,S.encode(JSON.stringify(e===void 0?null:e))));return`${W}${P(n)}.${P(r)}`}async function A(t,e){if(!e.startsWith(W))throw new Error("not a sealed frame");let[n,r]=e.slice(W.length).split(".");if(!n||!r)throw new Error("not a sealed frame");let i=await crypto.subtle.decrypt({name:"AES-GCM",iv:C(n),additionalData:S.encode("soba-e2e-up")},t.key,C(r));return JSON.parse(Ne.decode(i))}function M(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t.$sealed;return typeof e=="string"&&e.startsWith(W)?e:void 0}async function ee(t){let n=[...new Uint8Array(await crypto.subtle.digest("SHA-256",C(t))).subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return n.match(/.{4}/g)?.join(" ")??n}function fe(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.machine=="string"&&typeof e.publicKey=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e.publicKey)}function he(t){return crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}function P(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function C(t){let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),n=new Uint8Array(e.length);for(let r=0;r<e.length;r++)n[r]=e.charCodeAt(r);return n}var m=class extends Error{code;type;status;retryable;retryAfterMs;runId;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="SobaError",this.code=e.code,this.type=e.type??e.code,this.status=e.status,this.retryable=e.retryable??je.has(e.code),this.retryAfterMs=e.retryAfterMs,this.runId=e.runId}},je=new Set(["rate_limited","server_error","connection","timeout","stream_truncated"]),Be={400:"invalid_request",401:"unauthorized",402:"payment_required",403:"forbidden",404:"not_found",409:"no_compute",422:"user_required",429:"rate_limited"};function Ge(t){let e=Be[t];return e||(t>=500?"server_error":t>=400?"invalid_request":"unknown")}var ye=new WeakSet;function we(t){return ye.has(t)}async function be(t){let e=t.status,n="";try{n=await t.text()}catch{}let r=He(n),i=new m({code:r?.code??Ge(e),type:r?.type,message:r?.message??Ve(e,t.statusText,n),status:e,retryAfterMs:ze(t.headers.get("retry-after")),runId:t.headers.get("soba-run-id")??void 0});return!r&&(e===502||e===503||e===504)&&ye.add(i),i}function He(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let n=e.error;if(!n||typeof n!="object")return null;let r=n;return{message:typeof r.message=="string"&&r.message?r.message:void 0,type:typeof r.type=="string"&&r.type?r.type:void 0,code:Je.has(r.code)?r.code:void 0}}var Je=new Set(["invalid_request","user_required","unauthorized","payment_required","forbidden","not_found","no_compute","unknown_run","not_resumable","machine_gone","rate_limited","server_error","connection","timeout","stream_truncated","run_failed","canceled","not_allowed","outside_roots","busy","unknown"]);function Ve(t,e,n){let r=n.trim().slice(0,200),i=r?`: ${r}`:"";return`Soba returned ${t}${e?` ${e}`:""}${i}`}function ze(t){if(!t)return;let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.round(e*1e3);let n=Date.parse(t);if(!Number.isNaN(n))return Math.max(0,n-Date.now())}function v(t){if(t instanceof m)return t;let e=t;return e?.name==="AbortError"||e?.name==="TimeoutError"?new m({code:"canceled",message:e.message||"The request was aborted.",retryable:!1,cause:t}):new m({code:"connection",message:e?.message?`Could not reach Soba: ${e.message}`:"Could not reach Soba.",cause:t})}var te="0.0.28";var Xe=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]);function ne(t){if(t.code==="rate_limited")return!0;if(t.code!=="connection")return!1;let e=t.cause;for(let n=0;e&&n<4;n++){let r=e.code;if(typeof r=="string"&&Xe.has(r))return!0;e=e.cause}return!1}var Ye=8e3,Qe=3e4;async function x(t,e){let n=tt(t.baseURL,e.path,e.query),r=e.retry===!1?1:Math.max(0,t.maxRetries)+1,i,u=s=>s.retryable&&(e.retry!=="unsent"||ne(s));for(let s=0;s<r;s++){s>0&&await re(nt(s,i),e.signal);let a=new AbortController,c=D(e.signal,a),l=setTimeout(()=>{a.abort(new m({code:"timeout",message:`Soba did not answer within ${t.connectTimeoutMs}ms.`}))},t.connectTimeoutMs),g;try{g=await t.fetch(n,{method:e.method,headers:Ze(t,e),body:e.body===void 0?void 0:JSON.stringify(e.body),signal:a.signal})}catch(o){if(c(),i=v(a.signal.aborted?a.signal.reason??o:o),!u(i)||s===r-1)throw i;continue}finally{clearTimeout(l)}if(g.ok)return g;if(c(),i=await be(g),!u(i)||s===r-1)throw i}throw i??new m({code:"unknown",message:"The request failed with no error."})}async function b(t,e){let n=await x(t,{accept:"application/json",...e}),r=await n.text();if(r)try{return JSON.parse(r)}catch(i){throw new m({code:"server_error",message:`Soba returned a body that is not JSON: ${r.slice(0,200)}`,status:n.status,cause:i})}}function Ze(t,e){let n={authorization:`Bearer ${t.apiKey}`,accept:e.accept??"application/json","user-agent":et(),...t.headers};return e.body!==void 0&&(n["content-type"]="application/json"),n}function et(){let t=typeof process>"u"?"":` node/${process.versions?.node??"?"}`;return`soba-sdk/${te}${t}`}function tt(t,e,n){let r=t.replace(/\/+$/,""),i=new URL(`${r}${e.startsWith("/")?e:`/${e}`}`);for(let[u,s]of Object.entries(n??{}))s!==void 0&&i.searchParams.set(u,String(s));return i.toString()}function nt(t,e){if(e?.retryAfterMs!==void 0)return Math.min(e.retryAfterMs,Qe);let n=Math.min(Ye,500*2**(t-1));return Math.round(n*(.5+Math.random()/2))}function re(t,e){return new Promise((n,r)=>{if(e?.aborted)return r(v(e.reason));let i=setTimeout(()=>{e?.removeEventListener("abort",u),n()},t);function u(){clearTimeout(i),r(v(e?.reason))}e?.addEventListener("abort",u,{once:!0})})}function D(t,e){if(!t)return()=>{};if(t.aborted)return e.abort(t.reason),()=>{};let n=()=>e.abort(t.reason);return t.addEventListener("abort",n,{once:!0}),()=>t.removeEventListener("abort",n)}var rt=5*60*1e3,ke=25,st=1e3,ot=100,j=class{#t;#o;#s;#n=null;#i=0;#a=null;#e=[];#r=null;constructor(e){this.#t=e.http,this.#o=e.onWarning,this.#s=e.off}async prime(){if(!this.#s)return this.#u()}#u(){return this.#a??=b(this.#t,{method:"GET",path:"/fallback",retry:!1}).then(e=>{this.#n={enabled:e?.enabled===!0,providers:(e?.providers??[]).map(Te).filter(Pe)},this.#i=Date.now()}).catch(()=>{}).finally(()=>{this.#a=null}),this.#a}refreshSoon(){this.#s||Date.now()-this.#i<rt||this.prime()}get pending(){return this.#e.length}canServe(e,n){if(this.#s)return!1;let r=v(e);return!ne(r)&&!we(r)||r.code==="rate_limited"?!1:this.#l(n).length>0}serve(e,n,r){let i=new AbortController,u=D(n,i),s=i.signal,a=new Map,c=new Map,l=f=>{let h=a.get(f.callId);h?(a.delete(f.callId),h(f)):c.set(f.callId,f)},g=f=>new Promise((h,w)=>{let k=c.get(f);if(k)return c.delete(f),h(k);a.set(f,h),s.addEventListener("abort",()=>w(v(s.reason)),{once:!0})}),o=r??this.#l(e.route),d=new TextEncoder,p=new ReadableStream({start:f=>{let h=w=>{try{f.enqueue(d.encode(`data: ${JSON.stringify(w)}
2
2
 
3
3
  `))}catch{}};this.#p(e,o,h,g,s).catch(w=>h({type:"error",message:v(w).message})).finally(()=>{u();try{f.close()}catch{}})},cancel:f=>i.abort(f)});return{response:new Response(p,{status:200,headers:{"content-type":"text/event-stream","soba-run-id":e.runId}}),deliver:l,stop:f=>i.abort(f)}}async servePrivate(e,n){this.#n||await this.#u();let i=((this.#n?.providers.length?this.#n:ve()??this.#n)?.providers??[]).filter(u=>se(u));if(i.length===0)throw new m({code:"invalid_request",message:"A private tool is answered by your own provider, and none is set up with a key on this server. Add one on your app's Models page and set its key here."});return this.serve({...e,private:!0},n,i)}async flush(){return this.#r??=this.#d().finally(()=>{this.#r=null}),this.#r}flushSoon(){this.#e.length&&this.flush()}async#d(){for(;this.#e.length;){let e=this.#e.slice(0,ot),n;try{n=(await b(this.#t,{method:"POST",path:"/usage/backfill",body:{runs:e}}))?.results??[]}catch{return}let r=new Set(n.filter(u=>u.outcome==="failed").map(u=>u.id)),i=new Set(e.map(u=>u.id));for(let u of n)u.outcome==="rejected"&&this.#o("Soba would not record a run served while it was unreachable.",u);if(this.#e=[...e.filter(u=>r.has(u.id)),...this.#e.filter(u=>!i.has(u.id))],r.size===e.length)return}}#c(e){this.#e.push(e),this.#e.length>st&&(this.#e.shift(),this.#o("Dropped the oldest unreported fallback run: too many waiting for Soba."))}#l(e){let n=this.#n??ve();return n?.enabled?n.providers.filter(r=>se(r)&&(!e?.allow||e.allow.includes(r.costClass))):[]}async#p(e,n,r,i,u){let s=new Date,a="None of your providers could be reached.";for(let c of n){let l=it(c,e.model),g={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},o=!1,d=(p,f)=>this.#c({id:e.runId,user:e.user,...e.customer?{customer:e.customer}:{},supplier:c.id,model:l.model,input_tokens:g.inputTokens,output_tokens:g.outputTokens,cache_read_tokens:g.cacheReadTokens,cache_write_tokens:g.cacheWriteTokens,started_at:s.toISOString(),ended_at:new Date().toISOString(),status:p,...f?{error:f}:{},...e.task?{task:e.task}:{}});try{r({type:"status",tier:c.costClass,message:e.private?`${c.name} is answering.`:`Soba can't be reached, so ${c.name} is answering.`});let p=at(e);for(let h=0;;h++){if(h>=ke)throw new Error(`Stopped after ${ke} turns of tool calls.`);let w=await ut(this.#t.fetch,c,l,p,e.tools,u,k=>{o=!0,r({type:"delta",text:k})});if(g.inputTokens+=w.inputTokens,g.outputTokens+=w.outputTokens,g.cacheReadTokens+=w.cacheReadTokens,!w.toolCalls.length)break;o=!0,p.push({role:"assistant",content:w.text||null,tool_calls:w.toolCalls});for(let k of w.toolCalls)r({type:"tool_call",callId:k.id,name:k.function.name,input:dt(k.function.arguments)});for(let k of w.toolCalls){let T=await i(k.id);p.push({role:"tool",tool_call_id:k.id,content:typeof T.result=="string"?T.result:JSON.stringify(T.result)})}}let f={model:l.model,provider:c.id,costClass:c.costClass,...g,webSearches:0};r({type:"usage",usage:f}),r({type:"done",usage:f}),d("done");return}catch(p){if(u.aborted)throw d("error","cancelled"),v(u.reason);if(a=`${c.name}: ${v(p).message}`,o)throw d("error",a),new m({code:"run_failed",message:a,retryable:!1})}}throw new m({code:"no_compute",message:a,retryable:!1})}};function Te(t){if(!t?.id||!t.base_url||!t.key_env||!t.cost_class)return null;let e=(t.models??[]).filter(n=>typeof n?.model=="string"&&n.model).map(n=>({model:n.model,alias:n.alias??null,maxOutputTokens:n.max_output_tokens??null}));return e.length?{id:t.id,name:t.name??t.id,baseUrl:t.base_url,keyEnv:t.key_env,costClass:t.cost_class,...t.api_key?{apiKey:t.api_key}:{},models:e}:null}var Pe=t=>t!==null;function ve(){let t=Se("SOBA_FALLBACK");if(!t)return null;try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),r=(JSON.parse(e).providers??[]).map(Te).filter(Pe);return r.length?{enabled:!0,providers:r}:null}catch{return null}}function se(t){return Se(t.keyEnv)??t.apiKey}function it(t,e){let n=t.models,r=e?.startsWith(`@${t.id}/`)?e.slice(t.id.length+2):e,i=n.find(u=>u.model===r||u.alias===r);return i||(e==="large"||e==="best"?n[n.length-1]:n[0])}function at(t){let e=[];t.system&&e.push({role:"system",content:t.system});for(let n of t.messages)n.role==="user"&&n.images?.length?e.push({role:"user",content:[{type:"text",text:n.content},...n.images.map(r=>({type:"image_url",image_url:{url:`data:${r.mediaType};base64,${r.data}`}}))]}):n.role==="user"?e.push({role:"user",content:n.content}):e.push({role:"assistant",content:n.content});return e}async function ut(t,e,n,r,i,u,s){let a=await t(`${e.baseUrl.replace(/\/+$/,"")}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${se(e)}`,"content-type":"application/json",accept:"text/event-stream"},body:JSON.stringify({model:n.model,messages:r,stream:!0,stream_options:{include_usage:!0},...n.maxOutputTokens?{max_tokens:n.maxOutputTokens}:{},...i.length?{tools:i.map(d=>({type:"function",function:{name:d.name,description:d.description,parameters:d.inputSchema}}))}:{}}),signal:u});if(!a.ok||!a.body){let d=await a.text().catch(()=>"");throw new Error(`${a.status} ${d.slice(0,300)}`.trim())}let c={text:"",toolCalls:[],inputTokens:0,outputTokens:0,cacheReadTokens:0},l=a.body.getReader(),g=new TextDecoder,o="";try{for(;;){let d=await l.read();if(d.done)break;for(o+=g.decode(d.value,{stream:!0});;){let p=o.indexOf(`
4
4
  `);if(p===-1)break;let f=o.slice(0,p).trim();if(o=o.slice(p+1),!f.startsWith("data:"))continue;let h=f.slice(5).trim();if(!h||h==="[DONE]")continue;let w;try{w=JSON.parse(h)}catch{continue}w.usage&&(c.inputTokens=w.usage.prompt_tokens??0,c.outputTokens=w.usage.completion_tokens??0,c.cacheReadTokens=w.usage.prompt_tokens_details?.cached_tokens??0,c.inputTokens-=c.cacheReadTokens);let k=w.choices?.[0]?.delta;k?.content&&(c.text+=k.content,s(k.content));for(let T of k?.tool_calls??[]){let $=T.index??c.toolCalls.length;c.toolCalls[$]??={id:T.id??`call_${$}`,type:"function",function:{name:"",arguments:""}};let V=c.toolCalls[$];T.id&&(V.id=T.id),T.function?.name&&(V.function.name+=T.function.name),T.function?.arguments&&(V.function.arguments+=T.function.arguments)}}}}finally{l.cancel().catch(()=>{})}return c.toolCalls=c.toolCalls.filter(d=>d?.function.name),c}function dt(t){if(!t)return{};try{return JSON.parse(t)}catch{return{}}}function Se(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}var Re=["open-weights","frontier"];function ct(t){return Re.includes(t)}function lt(t){return t==="user-hardware"||t==="user-subscription"||t==="user-api-key"||t==="open-weights"||t==="frontier"}function oe(t){return t.type==="done"||t.type==="error"}var pt=["search","fetch","read","write","edit","bash","files","agent","todo","think","sources","tool"];var Ee=new Set(["delta","thinking","status","done","error"]);function ie(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object"||Array.isArray(e))return null;let n=e,r=y(n.runId);if(typeof n.type=="string"&&Ee.has(n.type)){let i=B(n);return i?{kind:"event",runId:r,event:i,..._e(n)}:null}switch(n.type){case"event":{if(!n.event||typeof n.event!="object")return null;let i=B(n.event);return i?{kind:"event",runId:r,event:i,..._e(n.event)}:null}case"usage":{let i=Ie(n.usage);return i?{kind:"usage",runId:r,usage:i}:null}case"tool_call":{let i=y(n.callId),u=y(n.name);return!i||!u?null:{kind:"tool_call",runId:r,callId:i,name:u,input:n.input,...n.answered===!0?{answered:!0}:{}}}case"approval_request":{let i=y(n.approvalId),u=y(n.tool);return!i||!u?null:{kind:"approval",runId:r,approvalId:i,tool:u,input:n.input,cwd:y(n.cwd),...n.answered===!0?{answered:!0}:{}}}default:return null}}function _e(t){let e=t.sealed;return typeof e=="string"&&e.length>0?{sealed:e}:{}}function B(t){let e=typeof t.type=="string"&&Ee.has(t.type)?t.type:null;if(!e)return null;let n={type:e},r=y(t.text);r!==void 0&&(n.text=r);let i=y(t.message);i!==void 0&&(n.message=i);let u=y(t.tool);u!==void 0&&(n.tool=u);let s=y(t.tier);s!==void 0&&(n.tier=s);let a=Ie(t.usage);a&&(n.usage=a);let c=y(t.reason);c!==void 0&&(n.reason=c),typeof t.retryable=="boolean"&&(n.retryable=t.retryable);let l=t.turn&&typeof t.turn=="object"?y(t.turn.text):void 0;l!==void 0&&(n.turn={text:l});let g=y(t.session);g!==void 0&&(n.session=g);let o=y(t.thread);o!==void 0&&(n.thread=o),(t.continued==="resumed"||t.continued==="rebuilt"||t.continued==="new")&&(n.continued=t.continued);let d=y(t.callId);d!==void 0&&(n.callId=d),(t.callEnded==="ok"||t.callEnded==="failed")&&(n.callEnded=t.callEnded);let p=y(t.toolInput);p!==void 0&&(n.toolInput=p);let f=y(t.toolOutput);f!==void 0&&(n.toolOutput=f);let h=gt(t.git);return h&&(n.git=h),(t.state==="interrupted"||t.state==="resumed")&&(n.state=t.state),n}function gt(t){if(!t||typeof t!="object")return null;let e=t,n=y(e.branch);return!n||!Array.isArray(e.files)||!Array.isArray(e.commits)?null:{branch:n,base:y(e.base)??"",head:y(e.head)??"",ahead:R(e.ahead),behind:R(e.behind),files:e.files.filter(r=>!!r&&typeof r=="object"&&typeof r.path=="string").map(r=>({path:r.path,status:r.status==="A"||r.status==="D"||r.status==="R"?r.status:"M",added:R(r.added),removed:R(r.removed)})),commits:e.commits.filter(r=>!!r&&typeof r=="object").map(r=>({sha:y(r.sha)??"",subject:y(r.subject)??""})),dirty:e.dirty===!0}}function Ie(t){if(!t||typeof t!="object")return null;let e=t,n={model:y(e.model)??"unknown",inputTokens:R(e.inputTokens),outputTokens:R(e.outputTokens),cacheReadTokens:R(e.cacheReadTokens),cacheWriteTokens:R(e.cacheWriteTokens),webSearches:R(e.webSearches)},r=y(e.costClass);r!==void 0&&(n.costClass=r);let i=y(e.provider);return i!==void 0&&(n.provider=i),typeof e.costMicros=="number"&&Number.isFinite(e.costMicros)&&(n.costMicros=e.costMicros),n}function y(t){return typeof t=="string"&&t.length>0?t:void 0}function R(t){return typeof t=="number"&&Number.isFinite(t)?t:0}async function*Ce(t){let e=t.body;if(!e)throw new m({code:"connection",message:"The run response arrived with no body to stream.",status:t.status});let n=t.headers.get("content-type")??"",r=n.includes("ndjson")||n.includes("jsonlines"),i=e.getReader(),u=new TextDecoder,s="",a=[],c,l=g=>c===void 0?g:{...g,seq:c};try{for(;;){let o=await i.read();if(o.done)break;for(s+=u.decode(o.value,{stream:!0});;){let d=s.indexOf(`
@@ -0,0 +1,49 @@
1
+ /**
2
+ * THE SESSION ROUTE, SO NO APP HAS TO WRITE IT.
3
+ *
4
+ * `<SobaProvider sessionEndpoint="/api/soba/session">` needs one route in the
5
+ * app that trades the secret key for a ten-minute credential for the person
6
+ * signed in. Written by hand it went wrong the same ways every time: the wrong
7
+ * host, which answers 404 and leaves nobody able to connect, and an id made up
8
+ * for a visitor who was not signed in, which creates a new "person" per browser.
9
+ *
10
+ * So the app answers one question, who is signed in, and the rest is here.
11
+ *
12
+ * // app/api/soba/session/route.ts
13
+ * import { sobaUserId } from "@soba-so/sdk/identity"
14
+ * import { sessionRoute } from "@soba-so/sdk/server"
15
+ *
16
+ * export const POST = sessionRoute({
17
+ * user: async () => {
18
+ * const session = await auth()
19
+ * return session ? sobaUserId(session.user.id) : null
20
+ * },
21
+ * })
22
+ */
23
+ /** Who the session is for. */
24
+ export interface SessionUser {
25
+ /** The same `user` your runs send. */
26
+ user: string;
27
+ /** A label for your Users page. Never an identifier. */
28
+ email?: string;
29
+ /** The team whose plan this page shows and sells, when it is not the person. */
30
+ customer?: string;
31
+ }
32
+ export interface SessionRouteOptions {
33
+ /**
34
+ * WHO IS SIGNED IN, read from your own session on the server. Return `null`
35
+ * (or nothing) for a signed-out visitor, who gets a 401 and no Soba user.
36
+ * Never take it from the request body: whoever this names can run on that
37
+ * person's computer. Never make one up for a visitor.
38
+ */
39
+ user: (request: Request) => Answer | Promise<Answer>;
40
+ /** Defaults to `SOBA_KEY`, then `SOBA_API_KEY`. */
41
+ apiKey?: string;
42
+ /** Defaults to `SOBA_WEB_URL`, then https://soba.so/v1. */
43
+ webBaseURL?: string;
44
+ fetch?: typeof globalThis.fetch;
45
+ }
46
+ type Answer = string | SessionUser | null | undefined;
47
+ /** A handler for `POST`, in anything that speaks `Request` and `Response`. */
48
+ export declare function sessionRoute(options: SessionRouteOptions): (request: Request) => Promise<Response>;
49
+ export {};
@@ -0,0 +1 @@
1
+ var p="https://soba.so/v1";function o(e,n,s){return new Response(JSON.stringify({error:{type:n,code:n,message:s}}),{status:e,headers:{"content-type":"application/json","cache-control":"no-store"}})}var i=e=>typeof process>"u"?void 0:process.env[e];function f(e){if(typeof e?.user!="function")throw new TypeError("sessionRoute needs `user`: a function returning who is signed in, or null.");return async n=>{if(n.method!=="POST")return o(405,"method_not_allowed","Send a POST.");let s=await e.user(n),t=typeof s=="string"?{user:s}:s;if(!t?.user?.trim())return o(401,"unauthorized","Sign in first.");let a=e.apiKey??i("SOBA_KEY")??i("SOBA_API_KEY");if(!a)return o(501,"not_configured","Set SOBA_KEY on the server.");let c=(e.webBaseURL??i("SOBA_WEB_URL")??p).replace(/\/+$/,""),r,u;try{r=await(e.fetch??fetch)(`${c}/end_users/session`,{method:"POST",headers:{authorization:`Bearer ${a}`,"content-type":"application/json"},body:JSON.stringify({user:t.user,...t.email?{email:t.email}:{},...t.customer?{customer:t.customer}:{}}),signal:AbortSignal.timeout(15e3)}),u=await r.text()}catch{return o(502,"upstream_error","Soba could not be reached. Try again.")}return new Response(u,{status:r.status,headers:{"content-type":r.headers.get("content-type")??"application/json","cache-control":"no-store"}})}}export{f as sessionRoute};
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.0.27";
1
+ export declare const VERSION = "0.0.28";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soba-so/sdk",
3
- "version": "0.0.27",
3
+ "version": "0.0.28",
4
4
  "description": "One request that comes back finished, executed on compute the end user owns.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://soba.so/docs/runs",
@@ -16,6 +16,10 @@
16
16
  "types": "./dist/identity.d.ts",
17
17
  "default": "./dist/identity.mjs"
18
18
  },
19
+ "./server": {
20
+ "types": "./dist/server.d.ts",
21
+ "default": "./dist/server.mjs"
22
+ },
19
23
  "./local": {
20
24
  "types": "./dist/local.d.ts",
21
25
  "default": "./dist/local.mjs"