@soba-so/sdk 0.0.13 → 0.0.15

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/client.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type MachineKey } from "./e2e.js";
1
2
  import type { Message, RouteRequest, RunPolicy } from "./protocol.js";
2
3
  import type { ConnectContextResponse, FeatureCheckResult, MachineListItem, PlanListResponse, QuantityResult, SobaUser, TrackResult, UsagePage, UsageQuery } from "./resources.js";
3
4
  import { type Approver, Run } from "./run.js";
@@ -47,6 +48,52 @@ export interface SobaOptions {
47
48
  * whatever the dashboard says. See `soba.fallback`.
48
49
  */
49
50
  fallback?: boolean;
51
+ /**
52
+ * END-TO-END ENCRYPTION. Every `soba.run()` is sealed here, on your server,
53
+ * to the person's own machines, and everything it sends back is sealed to
54
+ * you. Soba routes and bills on what stays outside (model, route, policy,
55
+ * token counts) and never sees a prompt, a tool result or an answer.
56
+ *
57
+ * A run nobody can open (the person has no machine connected that holds a
58
+ * key) is never sent: `soba.run()` throws `no_compute` at once, the same
59
+ * handback as a run with nowhere to go, so your own provider answers it.
60
+ * Bought supply and the connected-plan channel are never used for an
61
+ * encrypted run, because Soba would have to read it to serve it.
62
+ *
63
+ * Keys come from Soba, so a Soba that handed over its own key could read
64
+ * the run. Two ways to guard against that, which can be combined:
65
+ *
66
+ * - `{ pin: true }` (or `{ pin: { store, onNewKey } }`): trust on first use.
67
+ * The first time a person is seen, every key Soba hands over is pinned to
68
+ * them. After that a pinned key is used, and a key not seen before is
69
+ * refused unless `onNewKey` says yes: a new laptop and a swapped key look
70
+ * the same from here, so it is your call, for example after showing the
71
+ * person the fingerprint their Soba app shows under Settings › Machine.
72
+ * The default store is this process's memory; on serverless pass one
73
+ * backed by your database, or every cold start is a first use.
74
+ * - `{ trust }`: shown each key with its fingerprint, for any rule of your
75
+ * own. A machine it says no to is never sealed to.
76
+ */
77
+ encrypt?: boolean | EncryptOptions;
78
+ }
79
+ /** A machine's key as a pin or a trust rule sees it. */
80
+ export type OfferedKey = MachineKey & {
81
+ fingerprint: string;
82
+ /** The `user` the run is for: whose machine this says it is. */
83
+ user: string;
84
+ };
85
+ /** Where pinned keys are kept: the public keys pinned to each user. */
86
+ export interface PinStore {
87
+ get(user: string): string[] | null | undefined | Promise<string[] | null | undefined>;
88
+ set(user: string, publicKeys: string[]): void | Promise<void>;
89
+ }
90
+ export interface EncryptOptions {
91
+ trust?: (key: OfferedKey) => boolean | Promise<boolean>;
92
+ pin?: true | {
93
+ store?: PinStore;
94
+ /** A key this user has not had before. Refused unless this says yes. */
95
+ onNewKey?: (key: OfferedKey) => boolean | Promise<boolean>;
96
+ };
50
97
  }
51
98
  /** Your own provider answering while Soba cannot be reached. See `fallback.ts`. */
52
99
  export interface FallbackControl {
package/dist/e2e.d.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * END-TO-END RUNS, the app's half.
3
+ *
4
+ * With `encrypt: true`, a run's content (prompt, messages, system, tool
5
+ * schemas) is sealed here, on your server, to the public keys of the person's
6
+ * machines. Everything the run sends back (text, tool calls, approvals) is
7
+ * sealed to the same per-run key, and so is every answer you send it. Soba
8
+ * routes and bills on what stays outside (model, route, policy, token counts)
9
+ * and only ever carries ciphertext.
10
+ *
11
+ * The scheme matches packages/worker/src/e2e.ts byte for byte, and a test
12
+ * opens each half with the other:
13
+ *
14
+ * - A random 32-byte run key K.
15
+ * - For each machine: a fresh X25519 key, HKDF-SHA256 over the shared secret
16
+ * (salt `epk.kid`, info `soba-e2e-wrap-v1`), and K sealed with AES-256-GCM.
17
+ * - The content: AES-256-GCM under K, AAD `soba-e2e-request-v1`.
18
+ * - Frames: AES-256-GCM under K, AAD `soba-e2e-up` from the machine and
19
+ * `soba-e2e-down` from the app.
20
+ *
21
+ * WebCrypto rather than `node:crypto`, so the SDK runs wherever `fetch` does.
22
+ */
23
+ type CryptoKey = Awaited<ReturnType<typeof crypto.subtle.importKey>>;
24
+ /** One of the person's machines that can open a run: its public key, as Soba handed it over. */
25
+ export interface MachineKey {
26
+ /** The machine's id on Soba. */
27
+ machine: string;
28
+ /** base64url, 32 bytes, X25519. */
29
+ publicKey: string;
30
+ }
31
+ export interface SealedRequest {
32
+ v: 1;
33
+ keys: {
34
+ kid: string;
35
+ epk: string;
36
+ iv: string;
37
+ ct: string;
38
+ }[];
39
+ iv: string;
40
+ ct: string;
41
+ }
42
+ /** A run's key, held in memory for as long as the run is read. Never sent to Soba. */
43
+ export interface RunKey {
44
+ raw: Uint8Array;
45
+ key: CryptoKey;
46
+ }
47
+ export declare function newRunKey(): Promise<RunKey>;
48
+ /** Seal `payload` so that only the machines in `recipients` can open it. */
49
+ export declare function sealRequest(runKey: RunKey, payload: Record<string, unknown>, recipients: MachineKey[]): Promise<SealedRequest>;
50
+ /** One frame from the app to the machine: a tool result. */
51
+ export declare function sealDown(runKey: RunKey, value: unknown): Promise<string>;
52
+ /** One frame from the machine. Throws if it was not sealed to this run, or was altered. */
53
+ export declare function openUp(runKey: RunKey, frame: string): Promise<unknown>;
54
+ /** `{ $sealed: "e1…" }`, the shape a sealed tool input or result travels in. */
55
+ export declare function sealedValue(v: unknown): string | undefined;
56
+ /**
57
+ * A key's fingerprint, for pinning: the first 16 bytes of its SHA-256, hex,
58
+ * in groups of four, short enough to read aloud and compare.
59
+ */
60
+ export declare function fingerprint(publicKey: string): Promise<string>;
61
+ export declare function isMachineKey(v: unknown): v is MachineKey;
62
+ export {};
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export { type AttachParams, DEFAULT_BASE_URL, DEFAULT_WEB_BASE_URL, type DetachedRunParams, type FallbackControl, type OpKind, type OpParams, type OpResult, type RunParams, Soba, type SobaOptions, type StartedRun, type TerminalBooking, type TerminalParams, } from "./client.js";
1
+ export { type AttachParams, DEFAULT_BASE_URL, DEFAULT_WEB_BASE_URL, type DetachedRunParams, type EncryptOptions, type OfferedKey, type PinStore, type FallbackControl, type OpKind, type OpParams, type OpResult, type RunParams, Soba, type SobaOptions, type StartedRun, type TerminalBooking, type TerminalParams, } from "./client.js";
2
+ export { fingerprint, type MachineKey } from "./e2e.js";
2
3
  export { SobaError, type SobaErrorCode } from "./errors.js";
3
4
  export { type AgentEvent, type AgentEventType, type CostClass, type GitSnapshot, type ImageInput, isCostClass, isMetered, isTerminal, METERED_CLASSES, type Message, type PermissionMode, type RouteRequest, type RunPolicy, type RunUsage, TOOL_SLUGS, type ToolSchema, type ToolSlug, } from "./protocol.js";
4
5
  export type { Allowance, ConnectContextResponse, ConnectedMachine, CurrentPlanItem, FeatureCheckResult, FeatureDenial, MachineListItem, MachineListState, MachineRuntime, PlanFeatureWire, PlanListItem, PlanListResponse, PlanSummary, QuantityResult, RuntimeListItem, SobaUser, TrackResult, UsagePage, UsageQuery, UsageRow, } from "./resources.js";
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- var u=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??oe.has(e.code),this.retryAfterMs=e.retryAfterMs,this.runId=e.runId}},oe=new Set(["rate_limited","server_error","connection","timeout","stream_truncated"]),se={400:"invalid_request",401:"unauthorized",402:"payment_required",403:"forbidden",404:"not_found",409:"no_compute",422:"user_required",429:"rate_limited"};function ie(t){let e=se[t];return e||(t>=500?"server_error":t>=400?"invalid_request":"unknown")}var W=new WeakSet;function j(t){return W.has(t)}async function B(t){let e=t.status,n="";try{n=await t.text()}catch{}let r=ae(n),o=new u({code:r?.code??ie(e),type:r?.type,message:r?.message??le(e,t.statusText,n),status:e,retryAfterMs:ce(t.headers.get("retry-after")),runId:t.headers.get("soba-run-id")??void 0});return!r&&(e===502||e===503||e===504)&&W.add(o),o}function ae(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:ue.has(r.code)?r.code:void 0}}var ue=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","unknown"]);function le(t,e,n){let r=n.trim().slice(0,200),o=r?`: ${r}`:"";return`Soba returned ${t}${e?` ${e}`:""}${o}`}function ce(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 w(t){if(t instanceof u)return t;let e=t;return e?.name==="AbortError"||e?.name==="TimeoutError"?new u({code:"canceled",message:e.message||"The request was aborted.",retryable:!1,cause:t}):new u({code:"connection",message:e?.message?`Could not reach Soba: ${e.message}`:"Could not reach Soba.",cause:t})}var q="0.0.13";var de=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]);function F(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"&&de.has(r))return!0;e=e.cause}return!1}var pe=8e3,fe=3e4;async function R(t,e){let n=he(t.baseURL,e.path,e.query),r=e.retry===!1?1:Math.max(0,t.maxRetries)+1,o,s=i=>i.retryable&&(e.retry!=="unsent"||F(i));for(let i=0;i<r;i++){i>0&&await D(be(i,o),e.signal);let a=new AbortController,c=A(e.signal,a),m=setTimeout(()=>{a.abort(new u({code:"timeout",message:`Soba did not answer within ${t.connectTimeoutMs}ms.`}))},t.connectTimeoutMs),p;try{p=await t.fetch(n,{method:e.method,headers:ge(t,e),body:e.body===void 0?void 0:JSON.stringify(e.body),signal:a.signal})}catch(g){if(c(),o=w(a.signal.aborted?a.signal.reason??g:g),!s(o)||i===r-1)throw o;continue}finally{clearTimeout(m)}if(p.ok)return p;if(c(),o=await B(p),!s(o)||i===r-1)throw o}throw o??new u({code:"unknown",message:"The request failed with no error."})}async function S(t,e){let n=await R(t,{accept:"application/json",...e}),r=await n.text();if(r)try{return JSON.parse(r)}catch(o){throw new u({code:"server_error",message:`Soba returned a body that is not JSON: ${r.slice(0,200)}`,status:n.status,cause:o})}}function ge(t,e){let n={authorization:`Bearer ${t.apiKey}`,accept:e.accept??"application/json","user-agent":me(),...t.headers};return e.body!==void 0&&(n["content-type"]="application/json"),n}function me(){let t=typeof process>"u"?"":` node/${process.versions?.node??"?"}`;return`soba-sdk/${q}${t}`}function he(t,e,n){let r=t.replace(/\/+$/,""),o=new URL(`${r}${e.startsWith("/")?e:`/${e}`}`);for(let[s,i]of Object.entries(n??{}))i!==void 0&&o.searchParams.set(s,String(i));return o.toString()}function be(t,e){if(e?.retryAfterMs!==void 0)return Math.min(e.retryAfterMs,fe);let n=Math.min(pe,500*2**(t-1));return Math.round(n*(.5+Math.random()/2))}function D(t,e){return new Promise((n,r)=>{if(e?.aborted)return r(w(e.reason));let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t);function s(){clearTimeout(o),r(w(e?.reason))}e?.addEventListener("abort",s,{once:!0})})}function A(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 ye=5*60*1e3,G=25,we=1e3,ke=100,P=class{#e;#o;#r;#s=null;#i=0;#t=null;#n=[];#a=null;constructor(e){this.#e=e.http,this.#o=e.onWarning,this.#r=e.off}async prime(){if(!this.#r)return this.#t??=S(this.#e,{method:"GET",path:"/fallback",retry:!1}).then(e=>{this.#s={enabled:e?.enabled===!0,providers:(e?.providers??[]).map(K).filter(J)},this.#i=Date.now()}).catch(()=>{}).finally(()=>{this.#t=null}),this.#t}refreshSoon(){this.#r||Date.now()-this.#i<ye||this.prime()}get pending(){return this.#n.length}canServe(e,n){if(this.#r)return!1;let r=w(e);return!F(r)&&!j(r)||r.code==="rate_limited"?!1:this.#c(n).length>0}serve(e,n){let r=new AbortController,o=A(n,r),s=r.signal,i=new Map,a=new Map,c=l=>{let d=i.get(l.callId);d?(i.delete(l.callId),d(l)):a.set(l.callId,l)},m=l=>new Promise((d,y)=>{let b=a.get(l);if(b)return a.delete(l),d(b);i.set(l,d),s.addEventListener("abort",()=>y(w(s.reason)),{once:!0})}),p=this.#c(e.route),g=new TextEncoder,f=new ReadableStream({start:l=>{let d=y=>{try{l.enqueue(g.encode(`data: ${JSON.stringify(y)}
1
+ var he="soba-e2e-wrap-v1",ye="soba-e2e-request-v1",O="e1.",x=new TextEncoder,be=new TextDecoder;async function Q(){let t=crypto.getRandomValues(new Uint8Array(32));return{raw:t,key:await we(t)}}async function V(t,e,n){let r=await Promise.all(n.map(async({publicKey:i})=>{let a=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),u=_(new Uint8Array(await crypto.subtle.exportKey("raw",a.publicKey))),d=await crypto.subtle.importKey("raw",U(i),{name:"X25519"},!1,[]),f=await crypto.subtle.deriveBits({name:"X25519",public:d},a.privateKey,256),m=await crypto.subtle.importKey("raw",f,"HKDF",!1,["deriveKey"]),g=await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:x.encode(`${u}.${i}`),info:x.encode(he)},m,{name:"AES-GCM",length:256},!1,["encrypt"]),l=crypto.getRandomValues(new Uint8Array(12)),p=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:l},g,t.raw));return{kid:i,epk:u,iv:_(l),ct:_(p)}})),o=crypto.getRandomValues(new Uint8Array(12)),s=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:x.encode(ye)},t.key,x.encode(JSON.stringify(e))));return{v:1,keys:r,iv:_(o),ct:_(s)}}async function N(t,e){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:n,additionalData:x.encode("soba-e2e-down")},t.key,x.encode(JSON.stringify(e===void 0?null:e))));return`${O}${_(n)}.${_(r)}`}async function L(t,e){if(!e.startsWith(O))throw new Error("not a sealed frame");let[n,r]=e.slice(O.length).split(".");if(!n||!r)throw new Error("not a sealed frame");let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:U(n),additionalData:x.encode("soba-e2e-up")},t.key,U(r));return JSON.parse(be.decode(o))}function X(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t.$sealed;return typeof e=="string"&&e.startsWith(O)?e:void 0}async function W(t){let n=[...new Uint8Array(await crypto.subtle.digest("SHA-256",U(t))).subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return n.match(/.{4}/g)?.join(" ")??n}function Y(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 we(t){return crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}function _(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function U(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 c=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??ke.has(e.code),this.retryAfterMs=e.retryAfterMs,this.runId=e.runId}},ke=new Set(["rate_limited","server_error","connection","timeout","stream_truncated"]),ve={400:"invalid_request",401:"unauthorized",402:"payment_required",403:"forbidden",404:"not_found",409:"no_compute",422:"user_required",429:"rate_limited"};function Se(t){let e=ve[t];return e||(t>=500?"server_error":t>=400?"invalid_request":"unknown")}var Z=new WeakSet;function ee(t){return Z.has(t)}async function te(t){let e=t.status,n="";try{n=await t.text()}catch{}let r=Re(n),o=new c({code:r?.code??Se(e),type:r?.type,message:r?.message??_e(e,t.statusText,n),status:e,retryAfterMs:xe(t.headers.get("retry-after")),runId:t.headers.get("soba-run-id")??void 0});return!r&&(e===502||e===503||e===504)&&Z.add(o),o}function Re(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:Te.has(r.code)?r.code:void 0}}var Te=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","unknown"]);function _e(t,e,n){let r=n.trim().slice(0,200),o=r?`: ${r}`:"";return`Soba returned ${t}${e?` ${e}`:""}${o}`}function xe(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 w(t){if(t instanceof c)return t;let e=t;return e?.name==="AbortError"||e?.name==="TimeoutError"?new c({code:"canceled",message:e.message||"The request was aborted.",retryable:!1,cause:t}):new c({code:"connection",message:e?.message?`Could not reach Soba: ${e.message}`:"Could not reach Soba.",cause:t})}var j="0.0.15";var Ae=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]);function B(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"&&Ae.has(r))return!0;e=e.cause}return!1}var Ee=8e3,Ce=3e4;async function T(t,e){let n=Oe(t.baseURL,e.path,e.query),r=e.retry===!1?1:Math.max(0,t.maxRetries)+1,o,s=i=>i.retryable&&(e.retry!=="unsent"||B(i));for(let i=0;i<r;i++){i>0&&await G(Ue(i,o),e.signal);let a=new AbortController,u=C(e.signal,a),d=setTimeout(()=>{a.abort(new c({code:"timeout",message:`Soba did not answer within ${t.connectTimeoutMs}ms.`}))},t.connectTimeoutMs),f;try{f=await t.fetch(n,{method:e.method,headers:Pe(t,e),body:e.body===void 0?void 0:JSON.stringify(e.body),signal:a.signal})}catch(m){if(u(),o=w(a.signal.aborted?a.signal.reason??m:m),!s(o)||i===r-1)throw o;continue}finally{clearTimeout(d)}if(f.ok)return f;if(u(),o=await te(f),!s(o)||i===r-1)throw o}throw o??new c({code:"unknown",message:"The request failed with no error."})}async function S(t,e){let n=await T(t,{accept:"application/json",...e}),r=await n.text();if(r)try{return JSON.parse(r)}catch(o){throw new c({code:"server_error",message:`Soba returned a body that is not JSON: ${r.slice(0,200)}`,status:n.status,cause:o})}}function Pe(t,e){let n={authorization:`Bearer ${t.apiKey}`,accept:e.accept??"application/json","user-agent":Ie(),...t.headers};return e.body!==void 0&&(n["content-type"]="application/json"),n}function Ie(){let t=typeof process>"u"?"":` node/${process.versions?.node??"?"}`;return`soba-sdk/${j}${t}`}function Oe(t,e,n){let r=t.replace(/\/+$/,""),o=new URL(`${r}${e.startsWith("/")?e:`/${e}`}`);for(let[s,i]of Object.entries(n??{}))i!==void 0&&o.searchParams.set(s,String(i));return o.toString()}function Ue(t,e){if(e?.retryAfterMs!==void 0)return Math.min(e.retryAfterMs,Ce);let n=Math.min(Ee,500*2**(t-1));return Math.round(n*(.5+Math.random()/2))}function G(t,e){return new Promise((n,r)=>{if(e?.aborted)return r(w(e.reason));let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t);function s(){clearTimeout(o),r(w(e?.reason))}e?.addEventListener("abort",s,{once:!0})})}function C(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 Me=5*60*1e3,ne=25,Ke=1e3,qe=100,M=class{#t;#o;#r;#s=null;#i=0;#e=null;#n=[];#a=null;constructor(e){this.#t=e.http,this.#o=e.onWarning,this.#r=e.off}async prime(){if(!this.#r)return this.#e??=S(this.#t,{method:"GET",path:"/fallback",retry:!1}).then(e=>{this.#s={enabled:e?.enabled===!0,providers:(e?.providers??[]).map(re).filter(oe)},this.#i=Date.now()}).catch(()=>{}).finally(()=>{this.#e=null}),this.#e}refreshSoon(){this.#r||Date.now()-this.#i<Me||this.prime()}get pending(){return this.#n.length}canServe(e,n){if(this.#r)return!1;let r=w(e);return!B(r)&&!ee(r)||r.code==="rate_limited"?!1:this.#c(n).length>0}serve(e,n){let r=new AbortController,o=C(n,r),s=r.signal,i=new Map,a=new Map,u=l=>{let p=i.get(l.callId);p?(i.delete(l.callId),p(l)):a.set(l.callId,l)},d=l=>new Promise((p,b)=>{let y=a.get(l);if(y)return a.delete(l),p(y);i.set(l,p),s.addEventListener("abort",()=>b(w(s.reason)),{once:!0})}),f=this.#c(e.route),m=new TextEncoder,g=new ReadableStream({start:l=>{let p=b=>{try{l.enqueue(m.encode(`data: ${JSON.stringify(b)}
2
2
 
3
- `))}catch{}};this.#d(e,p,d,m,s).catch(y=>d({type:"error",message:w(y).message})).finally(()=>{o();try{l.close()}catch{}})},cancel:l=>r.abort(l)});return{response:new Response(f,{status:200,headers:{"content-type":"text/event-stream","soba-run-id":e.runId}}),deliver:c,stop:l=>r.abort(l)}}async flush(){return this.#a??=this.#u().finally(()=>{this.#a=null}),this.#a}flushSoon(){this.#n.length&&this.flush()}async#u(){for(;this.#n.length;){let e=this.#n.slice(0,ke),n;try{n=(await S(this.#e,{method:"POST",path:"/usage/backfill",body:{runs:e}}))?.results??[]}catch{return}let r=new Set(n.filter(s=>s.outcome==="failed").map(s=>s.id)),o=new Set(e.map(s=>s.id));for(let s of n)s.outcome==="rejected"&&this.#o("Soba would not record a run served while it was unreachable.",s);if(this.#n=[...e.filter(s=>r.has(s.id)),...this.#n.filter(s=>!o.has(s.id))],r.size===e.length)return}}#l(e){this.#n.push(e),this.#n.length>we&&(this.#n.shift(),this.#o("Dropped the oldest unreported fallback run: too many waiting for Soba."))}#c(e){let n=this.#s??ve();return n?.enabled?n.providers.filter(r=>H(r)&&(!e?.allow||e.allow.includes(r.costClass))):[]}async#d(e,n,r,o,s){let i=new Date,a="None of your providers could be reached.";for(let c of n){let m=Se(c,e.model),p={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},g=!1,f=(l,d)=>this.#l({id:e.runId,user:e.user,supplier:c.id,model:m.model,input_tokens:p.inputTokens,output_tokens:p.outputTokens,cache_read_tokens:p.cacheReadTokens,cache_write_tokens:p.cacheWriteTokens,started_at:i.toISOString(),ended_at:new Date().toISOString(),status:l,...d?{error:d}:{},...e.task?{task:e.task}:{}});try{r({type:"status",tier:c.costClass,message:`Soba can't be reached, so ${c.name} is answering.`});let l=Te(e);for(let y=0;;y++){if(y>=G)throw new Error(`Stopped after ${G} turns of tool calls.`);let b=await Re(this.#e.fetch,c,m,l,e.tools,s,k=>{g=!0,r({type:"delta",text:k})});if(p.inputTokens+=b.inputTokens,p.outputTokens+=b.outputTokens,p.cacheReadTokens+=b.cacheReadTokens,!b.toolCalls.length)break;g=!0,l.push({role:"assistant",content:b.text||null,tool_calls:b.toolCalls});for(let k of b.toolCalls)r({type:"tool_call",callId:k.id,name:k.function.name,input:_e(k.function.arguments)});for(let k of b.toolCalls){let v=await o(k.id);l.push({role:"tool",tool_call_id:k.id,content:typeof v.result=="string"?v.result:JSON.stringify(v.result)})}}let d={model:m.model,provider:c.id,costClass:c.costClass,...p,webSearches:0};r({type:"usage",usage:d}),r({type:"done",usage:d}),f("done");return}catch(l){if(s.aborted)throw f("error","cancelled"),w(s.reason);if(a=`${c.name}: ${w(l).message}`,g)throw f("error",a),new u({code:"run_failed",message:a,retryable:!1})}}throw new u({code:"no_compute",message:a,retryable:!1})}};function K(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 J=t=>t!==null;function ve(){let t=z("SOBA_FALLBACK");if(!t)return null;try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),r=(JSON.parse(e).providers??[]).map(K).filter(J);return r.length?{enabled:!0,providers:r}:null}catch{return null}}function H(t){return z(t.keyEnv)??t.apiKey}function Se(t,e){let n=t.models,r=e?.startsWith(`@${t.id}/`)?e.slice(t.id.length+2):e,o=n.find(s=>s.model===r||s.alias===r);return o||(e==="large"||e==="best"?n[n.length-1]:n[0])}function Te(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 Re(t,e,n,r,o,s,i){let a=await t(`${e.baseUrl.replace(/\/+$/,"")}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${H(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}:{},...o.length?{tools:o.map(f=>({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema}}))}:{}}),signal:s});if(!a.ok||!a.body){let f=await a.text().catch(()=>"");throw new Error(`${a.status} ${f.slice(0,300)}`.trim())}let c={text:"",toolCalls:[],inputTokens:0,outputTokens:0,cacheReadTokens:0},m=a.body.getReader(),p=new TextDecoder,g="";try{for(;;){let f=await m.read();if(f.done)break;for(g+=p.decode(f.value,{stream:!0});;){let l=g.indexOf(`
4
- `);if(l===-1)break;let d=g.slice(0,l).trim();if(g=g.slice(l+1),!d.startsWith("data:"))continue;let y=d.slice(5).trim();if(!y||y==="[DONE]")continue;let b;try{b=JSON.parse(y)}catch{continue}b.usage&&(c.inputTokens=b.usage.prompt_tokens??0,c.outputTokens=b.usage.completion_tokens??0,c.cacheReadTokens=b.usage.prompt_tokens_details?.cached_tokens??0,c.inputTokens-=c.cacheReadTokens);let k=b.choices?.[0]?.delta;k?.content&&(c.text+=k.content,i(k.content));for(let v of k?.tool_calls??[]){let U=v.index??c.toolCalls.length;c.toolCalls[U]??={id:v.id??`call_${U}`,type:"function",function:{name:"",arguments:""}};let M=c.toolCalls[U];v.id&&(M.id=v.id),v.function?.name&&(M.function.name+=v.function.name),v.function?.arguments&&(M.function.arguments+=v.function.arguments)}}}}finally{m.cancel().catch(()=>{})}return c.toolCalls=c.toolCalls.filter(f=>f?.function.name),c}function _e(t){if(!t)return{};try{return JSON.parse(t)}catch{return{}}}function z(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}var Q=["open-weights","frontier"];function xe(t){return Q.includes(t)}function Ae(t){return t==="user-hardware"||t==="user-subscription"||t==="user-api-key"||t==="open-weights"||t==="frontier"}function L(t){return t.type==="done"||t.type==="error"}var Ee=["search","fetch","read","write","edit","bash","files","agent","todo","think","sources","tool"];var Z=new Set(["delta","thinking","status","done","error"]);function N(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=h(n.runId);if(typeof n.type=="string"&&Z.has(n.type)){let o=Y(n);return o?{kind:"event",runId:r,event:o}:null}switch(n.type){case"event":{if(!n.event||typeof n.event!="object")return null;let o=Y(n.event);return o?{kind:"event",runId:r,event:o}:null}case"usage":{let o=ee(n.usage);return o?{kind:"usage",runId:r,usage:o}:null}case"tool_call":{let o=h(n.callId),s=h(n.name);return!o||!s?null:{kind:"tool_call",runId:r,callId:o,name:s,input:n.input,...n.answered===!0?{answered:!0}:{}}}case"approval_request":{let o=h(n.approvalId),s=h(n.tool);return!o||!s?null:{kind:"approval",runId:r,approvalId:o,tool:s,input:n.input,cwd:h(n.cwd),...n.answered===!0?{answered:!0}:{}}}default:return null}}function Y(t){let e=typeof t.type=="string"&&Z.has(t.type)?t.type:null;if(!e)return null;let n={type:e},r=h(t.text);r!==void 0&&(n.text=r);let o=h(t.message);o!==void 0&&(n.message=o);let s=h(t.tool);s!==void 0&&(n.tool=s);let i=h(t.tier);i!==void 0&&(n.tier=i);let a=ee(t.usage);a&&(n.usage=a);let c=h(t.reason);c!==void 0&&(n.reason=c),typeof t.retryable=="boolean"&&(n.retryable=t.retryable);let m=t.turn&&typeof t.turn=="object"?h(t.turn.text):void 0;m!==void 0&&(n.turn={text:m});let p=h(t.session);p!==void 0&&(n.session=p);let g=h(t.toolInput);g!==void 0&&(n.toolInput=g);let f=Ce(t.git);return f&&(n.git=f),(t.state==="interrupted"||t.state==="resumed")&&(n.state=t.state),n}function Ce(t){if(!t||typeof t!="object")return null;let e=t,n=h(e.branch);return!n||!Array.isArray(e.files)||!Array.isArray(e.commits)?null:{branch:n,base:h(e.base)??"",head:h(e.head)??"",ahead:T(e.ahead),behind:T(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:T(r.added),removed:T(r.removed)})),commits:e.commits.filter(r=>!!r&&typeof r=="object").map(r=>({sha:h(r.sha)??"",subject:h(r.subject)??""})),dirty:e.dirty===!0}}function ee(t){if(!t||typeof t!="object")return null;let e=t,n={model:h(e.model)??"unknown",inputTokens:T(e.inputTokens),outputTokens:T(e.outputTokens),cacheReadTokens:T(e.cacheReadTokens),cacheWriteTokens:T(e.cacheWriteTokens),webSearches:T(e.webSearches)},r=h(e.costClass);r!==void 0&&(n.costClass=r);let o=h(e.provider);return o!==void 0&&(n.provider=o),typeof e.costMicros=="number"&&Number.isFinite(e.costMicros)&&(n.costMicros=e.costMicros),n}function h(t){return typeof t=="string"&&t.length>0?t:void 0}function T(t){return typeof t=="number"&&Number.isFinite(t)?t:0}async function*te(t){let e=t.body;if(!e)throw new u({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"),o=e.getReader(),s=new TextDecoder,i="",a=[],c,m=p=>c===void 0?p:{...p,seq:c};try{for(;;){let g=await o.read();if(g.done)break;for(i+=s.decode(g.value,{stream:!0});;){let f=i.indexOf(`
5
- `);if(f===-1)break;let l=V(i.slice(0,f));if(i=i.slice(f+1),r){let d=l.trim()?N(l):null;d&&(yield d);continue}if(l===""){let d=a.join(`
6
- `);if(a=[],d==="[DONE]")return;let y=d?N(d):null;y&&(yield m(y)),c=void 0;continue}if(l.startsWith("id:")){let d=Number(l.slice(3).trim());c=Number.isInteger(d)&&d>0?d:void 0;continue}X(l,a)}}!r&&i&&X(V(i),a);let p=r?i.trim():a.join(`
7
- `);if(p&&p!=="[DONE]"){let g=N(p);g&&(yield r?g:m(g))}}finally{o.cancel().catch(()=>{})}}function X(t,e){if(t.startsWith(":"))return;let n=t.indexOf(":");if(n===-1||t.slice(0,n)!=="data")return;let r=t.slice(n+1);e.push(r.startsWith(" ")?r.slice(1):r)}function V(t){return t.endsWith("\r")?t.slice(0,-1):t}function Pe(t){return t}function x(t){let e=new Map;for(let n of t??[]){if(!n?.name)throw new u({code:"invalid_request",message:"Every tool needs a name."});if(typeof n.execute!="function")throw new u({code:"invalid_request",message:`Tool "${n.name}" has no execute function. A tool Soba cannot call is not a tool.`});if(e.has(n.name))throw new u({code:"invalid_request",message:`Two tools are named "${n.name}". Tool names must be unique within a run.`});e.set(n.name,n)}return e}function I(t){return[...t.values()].map(e=>({name:e.name,description:e.description??"",inputSchema:e.inputSchema??{type:"object"}}))}function E(t){if(t===void 0)return null;if(typeof t=="string")return t;try{return JSON.parse(JSON.stringify(t))}catch{return String(t)}}function C(t){return t instanceof Error?t.message||t.name:typeof t=="string"?t:String(t)}var Ie=9e4,_=class{#e;#o;#r;#s=!1;#i;#t;#n=new AbortController;#a=new AbortController;#u=new Set;#l;constructor(e){this.#t=e,this.#e=e.response.headers.get("soba-run-id")??"",this.#i=e.after??0,this.#l=A(e.signal,this.#n)}get cursor(){return this.#i}get servedWithoutSoba(){return this.#t.local!==void 0}get resumable(){return this.#t.response.headers.get("soba-resumable")==="1"}get runId(){return this.#e}get tier(){return this.#o}get usage(){return this.#r}[Symbol.asyncIterator](){return this.#d()}async text(){let e="";for await(let n of this)if(n.type==="delta"&&n.text&&(e+=n.text),n.type==="error")throw new u({code:"run_failed",message:n.message??"The run ended with an error.",runId:this.#e,retryable:!1});return e}async cancel(){if(this.#n.abort(new u({code:"canceled",message:"The run was cancelled."})),this.#a.abort(new u({code:"canceled",message:"The run was cancelled."})),this.#t.local)return this.#t.local.cancel(this.#n.signal.reason);if(this.#e)try{await R(this.#t.config,{method:"POST",path:`/runs/${encodeURIComponent(this.#e)}/cancel`,retry:!1})}catch(e){this.#t.onWarning("Could not tell Soba the run was cancelled.",e)}}async#c(e){let n=Date.now()+Ie,r=e;for(let o=0;Date.now()<n;o++){if(this.#n.signal.aborted)throw w(this.#n.signal.reason);o>0&&await D(Math.min(1e3*o,5e3),this.#n.signal);try{return await R(this.#t.config,{method:"GET",path:`/runs/${encodeURIComponent(this.#e)}/stream`,query:{after:this.#i},accept:"text/event-stream",signal:this.#n.signal,retry:!1})}catch(s){if(r=w(s),!["server_error","connection","timeout","rate_limited"].includes(r.code))break}}throw new u({code:"stream_truncated",message:`The run stream ended without a \`done\` or \`error\` event, and reading on failed: ${r.message}`,runId:this.#e,cause:r})}async*#d(){if(this.#s)throw new u({code:"invalid_request",message:"This run has already been consumed. A run's events can only be read once.",runId:this.#e});this.#s=!0;let e=!1;try{let n=this.#t.response;for(;;){for await(let o of te(n)){if(o.runId&&!this.#e&&(this.#e=o.runId),o.seq!==void 0&&(this.#i=o.seq),o.kind==="event"){let s=o.event;if(s.tier&&(this.#o=s.tier),s.usage&&(this.#r=s.usage),e=L(s),yield s,e)return;continue}if(o.kind==="usage"){this.#r=o.usage;continue}this.#f(this.#g(o))}let r=new u({code:"stream_truncated",message:"The run stream ended without a `done` or `error` event.",runId:this.#e});if(!this.resumable||!this.#e||this.#t.local)throw r;n=await this.#c(r)}}finally{e||this.#a.abort(new u({code:"canceled",message:"The run ended before this tool finished."})),await Promise.allSettled([...this.#u]),this.#n.abort(),this.#l()}}#f(e){this.#u.add(e),e.finally(()=>this.#u.delete(e)).catch(()=>{})}async#g(e){if(!((e.kind==="tool_call"||e.kind==="approval")&&e.answered)){if(e.kind==="tool_call")return this.#m(e);if(e.kind==="approval")return this.#h(e)}}async#m(e){let n=this.#t.tools.get(e.name),r,o=!1;if(!n)r=`No tool named "${e.name}" is registered by this app.`,o=!0;else{let s={runId:this.#e,user:this.#t.user,callId:e.callId,signal:this.#a.signal};try{r=await n.execute(e.input,s)}catch(i){r=C(i),o=!0}}if(this.#t.local){this.#t.local.deliver({callId:e.callId,result:E(r),isError:o});return}await this.#p(`/runs/${encodeURIComponent(this.#e)}/tool_result`,{callId:e.callId,result:E(r),isError:o})}async#h(e){let n="deny",r;if(!this.#t.approve)r="This app did not supply an approver, so escalations are denied.";else try{let o={runId:this.#e,approvalId:e.approvalId,tool:e.tool,input:e.input};e.cwd&&(o.cwd=e.cwd),n=await this.#t.approve(o)==="allow"?"allow":"deny"}catch(o){r=C(o)}await this.#p(`/runs/${encodeURIComponent(this.#e)}/approval`,{approvalId:e.approvalId,decision:n,...r?{reason:r}:{}})}async#p(e,n){if(!this.#e){this.#t.onWarning("Soba sent a frame before the run had an id, so it could not be answered.",n);return}try{await(await R(this.#t.config,{method:"POST",path:e,body:n})).text()}catch(r){this.#t.onWarning(`Could not deliver an answer to ${e}.`,w(r))}}};var ne="https://api.soba.so/v1",re="https://soba.so/v1",Oe=3e4,Ue=2,$=class{#e;#o;#r;#s;fallback;users;usage;connect;plans;runs;ops;terminals;constructor(e={}){let n=e.apiKey??O("SOBA_KEY")??O("SOBA_API_KEY");if(!n)throw new u({code:"unauthorized",message:"No Soba API key. Pass `apiKey`, or set SOBA_KEY. Keys are shaped sk_soba_<id>.<secret> and come from your dashboard."});if(Me()&&!e.dangerouslyAllowBrowser)throw new u({code:"invalid_request",message:"A Soba app key is a server credential and this looks like a browser. Call Soba from your server, or pass dangerouslyAllowBrowser if you are certain."});if(this.#r=e.onWarning??(()=>{}),this.#e={apiKey:n,baseURL:e.baseURL??O("SOBA_BASE_URL")??ne,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??Oe,maxRetries:e.maxRetries??Ue},this.#o={...this.#e,baseURL:e.webBaseURL??O("SOBA_WEB_URL")??re},typeof this.#e.fetch!="function")throw new u({code:"invalid_request",message:"No global fetch. Run on Node 22 or newer, or pass your own `fetch`."});let r=new P({http:this.#e,onWarning:this.#r,off:e.fallback===!1});this.#s=r,this.fallback={prime:()=>r.prime(),flush:()=>r.flush(),get pending(){return r.pending}},this.users={get:o=>this.request("GET",`/users/${encodeURIComponent(o)}`),compute:async o=>(await this.request("GET",`/users/${encodeURIComponent(o)}/compute`)).machines,setQuantity:(o,s,i)=>S(this.#o,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/quantity`,body:{quantity:i}}),check:(o,s,i)=>S(i?.use?{...this.#o,maxRetries:0}:this.#o,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/check`,body:i?.use?{use:i.use}:{}}),track:(o,s,i=1)=>S({...this.#o,maxRetries:0},{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/track`,body:{amount:i}})},this.usage={list:o=>this.request("GET","/usage",{query:{...o}})},this.connect=()=>this.request("GET","/connect"),this.runs={start:async o=>{if(!o.user)throw new u({code:"user_required",status:422,message:"`user` is required."});let s=x(o.tools),i={user:o.user,model:o.model??"auto",detached:!0};o.webhook&&(i.webhook=o.webhook),o.prompt&&(i.prompt=o.prompt),o.messages?.length&&(i.messages=o.messages),o.system&&(i.system=o.system),o.runtime&&(i.runtime=o.runtime),s.size&&(i.tools=I(s)),o.route&&(i.route=o.route),o.policy&&(i.policy=o.policy),o.metadata&&(i.metadata=o.metadata),o.task&&(i.task=o.task),o.surface&&(i.surface=o.surface),o.maxDurationMs&&(i.maxDurationMs=o.maxDurationMs),o.title&&(i.title=o.title),o.worktree&&(i.worktree=o.worktree),o.resume&&(i.resume=o.resume);let a=await S(this.#e,{method:"POST",path:"/runs",body:i,retry:"unsent"}),c={id:a.id};return a.stream&&(c.stream={url:a.stream.url,token:a.stream.token,expiresAt:a.stream.expires_at}),o.answerTools==="here"&&(c.answered=(async()=>{let m=await this.runs.attach(a.id,{user:o.user,tools:o.tools??[]});for await(let p of m);})().catch(m=>this.#r("Answering this run's tool calls stopped.",m))),c},attach:async(o,s)=>{if(!s.user)throw new u({code:"user_required",status:422,message:"`user` is required."});let i=await R(this.#e,{method:"GET",path:`/runs/${encodeURIComponent(o)}/stream`,...s.after?{query:{after:s.after}}:{},accept:"text/event-stream",signal:s.signal});return new _({config:this.#e,response:i,user:s.user,tools:x(s.tools),approve:s.approve,onWarning:this.#r,signal:s.signal,after:s.after??0})},cancel:async o=>{await this.request("POST",`/runs/${encodeURIComponent(o)}/cancel`,{body:{}})}},this.ops={run:o=>{if(!o.user)throw new u({code:"user_required",status:422,message:"`user` is required \u2014 it is how Soba knows whose machine to ask."});return this.request("POST","/ops",{body:{...o}})}},this.terminals={open:async o=>{if(!o.user)throw new u({code:"user_required",status:422,message:"`user` is required \u2014 it is how Soba knows whose machine to open it on."});let s=await this.request("POST","/term",{body:{...o}}),i=new URL(this.#e.baseURL);i.protocol=i.protocol==="http:"?"ws:":"wss:";let a=new URL(s.path,`${i.protocol}//${i.host}`);return a.searchParams.set("ticket",s.ticket),{termId:s.termId,url:a.toString(),expiresAt:s.expiresAt}}},this.plans={list:o=>this.request("GET","/plans",{...o?.user?{query:{user:o.user}}:{}})}}get baseURL(){return this.#e.baseURL}async run(e){if(!e.user)throw new u({code:"user_required",status:422,message:"`user` is required. A run with no user cannot be attributed or metered, so it cannot be defaulted."});if(!e.prompt&&!e.messages?.length)throw new u({code:"invalid_request",status:400,message:"A run needs a `prompt` or a non-empty `messages`."});let n=x(e.tools),r={user:e.user,model:e.model??"auto"};e.prompt&&(r.prompt=e.prompt),e.messages?.length&&(r.messages=e.messages),e.system&&(r.system=e.system),e.runtime&&(r.runtime=e.runtime),n.size&&(r.tools=I(n)),e.route&&(r.route=e.route),e.policy&&(r.policy=e.policy),e.metadata&&(r.metadata=e.metadata),e.task&&(r.task=e.task),r.resumable=e.resumable?!0:"restarts",e.maxDurationMs&&(r.maxDurationMs=e.maxDurationMs);let o;try{o=await R(this.#e,{method:"POST",path:"/runs",body:r,accept:"text/event-stream",signal:e.signal,retry:"unsent"})}catch(s){if(!this.#s.canServe(s,e.route))throw s;let i=this.#s.serve({runId:globalThis.crypto.randomUUID(),user:e.user,model:e.model,route:e.route,system:e.system,messages:e.messages?.length?e.messages:[{role:"user",content:e.prompt??""}],tools:I(n),task:e.task},e.signal);return this.#r("Soba could not be reached; your own provider is answering this run.",s),new _({config:this.#e,response:i.response,user:e.user,tools:n,approve:e.approve,onWarning:this.#r,signal:e.signal,local:{deliver:i.deliver,cancel:i.stop}})}return this.#s.refreshSoon(),this.#s.flushSoon(),new _({config:this.#e,response:o,user:e.user,tools:n,approve:e.approve,onWarning:this.#r,signal:e.signal})}async request(e,n,r={}){return S(this.#e,{method:e,path:n,...r})}};function O(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}function Me(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}var qe=300;function Fe(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function De(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}async function Le(t,e,n,r={}){let o=Object.fromEntries((e??"").split(",").map(l=>{let d=l.indexOf("=");return[l.slice(0,d).trim(),l.slice(d+1).trim()]})),s=Number(o.t),i=o.v1??"",a=l=>new u({code:"unauthorized",status:401,message:l});if(!Number.isFinite(s)||!i)throw a("Missing or malformed Soba-Signature.");let c=Math.floor((r.now??Date.now())/1e3);if(Math.abs(c-s)>(r.toleranceSeconds??qe))throw a("This delivery is too old to accept.");let m=await globalThis.crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),p=Fe(await globalThis.crypto.subtle.sign("HMAC",m,new TextEncoder().encode(`${s}.${t}`)));if(!De(p,i))throw a("The Soba-Signature does not match.");let g;try{g=JSON.parse(t)}catch{throw new u({code:"invalid_request",message:"The delivery is not JSON."})}let f=g;if(f.type!=="run.event"&&f.type!=="run.tool_call"||typeof f.run_id!="string")throw new u({code:"invalid_request",message:"Not a Soba run delivery."});return f}async function Ne(t,e){if(t.type!=="run.tool_call")return null;let{call_id:n,name:r,input:o}=t.data,s=x(e.tools).get(r);if(!s)return{result:`Unknown tool: ${r}`,is_error:!0};try{let i=await s.execute(o??{},{runId:t.run_id,user:e.user??"",callId:n,signal:AbortSignal.timeout(25e3)});return{result:E(i)}}catch(i){return{result:C(i),is_error:!0}}}export{ne as DEFAULT_BASE_URL,re as DEFAULT_WEB_BASE_URL,Q as METERED_CLASSES,_ as Run,$ as Soba,u as SobaError,Ee as TOOL_SLUGS,q as VERSION,Ne as handleRunWebhook,Ae as isCostClass,xe as isMetered,L as isTerminal,Pe as tool,Le as verifyWebhook};
3
+ `))}catch{}};this.#d(e,f,p,d,s).catch(b=>p({type:"error",message:w(b).message})).finally(()=>{o();try{l.close()}catch{}})},cancel:l=>r.abort(l)});return{response:new Response(g,{status:200,headers:{"content-type":"text/event-stream","soba-run-id":e.runId}}),deliver:u,stop:l=>r.abort(l)}}async flush(){return this.#a??=this.#u().finally(()=>{this.#a=null}),this.#a}flushSoon(){this.#n.length&&this.flush()}async#u(){for(;this.#n.length;){let e=this.#n.slice(0,qe),n;try{n=(await S(this.#t,{method:"POST",path:"/usage/backfill",body:{runs:e}}))?.results??[]}catch{return}let r=new Set(n.filter(s=>s.outcome==="failed").map(s=>s.id)),o=new Set(e.map(s=>s.id));for(let s of n)s.outcome==="rejected"&&this.#o("Soba would not record a run served while it was unreachable.",s);if(this.#n=[...e.filter(s=>r.has(s.id)),...this.#n.filter(s=>!o.has(s.id))],r.size===e.length)return}}#l(e){this.#n.push(e),this.#n.length>Ke&&(this.#n.shift(),this.#o("Dropped the oldest unreported fallback run: too many waiting for Soba."))}#c(e){let n=this.#s??De();return n?.enabled?n.providers.filter(r=>se(r)&&(!e?.allow||e.allow.includes(r.costClass))):[]}async#d(e,n,r,o,s){let i=new Date,a="None of your providers could be reached.";for(let u of n){let d=Fe(u,e.model),f={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},m=!1,g=(l,p)=>this.#l({id:e.runId,user:e.user,supplier:u.id,model:d.model,input_tokens:f.inputTokens,output_tokens:f.outputTokens,cache_read_tokens:f.cacheReadTokens,cache_write_tokens:f.cacheWriteTokens,started_at:i.toISOString(),ended_at:new Date().toISOString(),status:l,...p?{error:p}:{},...e.task?{task:e.task}:{}});try{r({type:"status",tier:u.costClass,message:`Soba can't be reached, so ${u.name} is answering.`});let l=$e(e);for(let b=0;;b++){if(b>=ne)throw new Error(`Stopped after ${ne} turns of tool calls.`);let y=await Ne(this.#t.fetch,u,d,l,e.tools,s,k=>{m=!0,r({type:"delta",text:k})});if(f.inputTokens+=y.inputTokens,f.outputTokens+=y.outputTokens,f.cacheReadTokens+=y.cacheReadTokens,!y.toolCalls.length)break;m=!0,l.push({role:"assistant",content:y.text||null,tool_calls:y.toolCalls});for(let k of y.toolCalls)r({type:"tool_call",callId:k.id,name:k.function.name,input:Le(k.function.arguments)});for(let k of y.toolCalls){let v=await o(k.id);l.push({role:"tool",tool_call_id:k.id,content:typeof v.result=="string"?v.result:JSON.stringify(v.result)})}}let p={model:d.model,provider:u.id,costClass:u.costClass,...f,webSearches:0};r({type:"usage",usage:p}),r({type:"done",usage:p}),g("done");return}catch(l){if(s.aborted)throw g("error","cancelled"),w(s.reason);if(a=`${u.name}: ${w(l).message}`,m)throw g("error",a),new c({code:"run_failed",message:a,retryable:!1})}}throw new c({code:"no_compute",message:a,retryable:!1})}};function re(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 oe=t=>t!==null;function De(){let t=ie("SOBA_FALLBACK");if(!t)return null;try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),r=(JSON.parse(e).providers??[]).map(re).filter(oe);return r.length?{enabled:!0,providers:r}:null}catch{return null}}function se(t){return ie(t.keyEnv)??t.apiKey}function Fe(t,e){let n=t.models,r=e?.startsWith(`@${t.id}/`)?e.slice(t.id.length+2):e,o=n.find(s=>s.model===r||s.alias===r);return o||(e==="large"||e==="best"?n[n.length-1]:n[0])}function $e(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 Ne(t,e,n,r,o,s,i){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}:{},...o.length?{tools:o.map(g=>({type:"function",function:{name:g.name,description:g.description,parameters:g.inputSchema}}))}:{}}),signal:s});if(!a.ok||!a.body){let g=await a.text().catch(()=>"");throw new Error(`${a.status} ${g.slice(0,300)}`.trim())}let u={text:"",toolCalls:[],inputTokens:0,outputTokens:0,cacheReadTokens:0},d=a.body.getReader(),f=new TextDecoder,m="";try{for(;;){let g=await d.read();if(g.done)break;for(m+=f.decode(g.value,{stream:!0});;){let l=m.indexOf(`
4
+ `);if(l===-1)break;let p=m.slice(0,l).trim();if(m=m.slice(l+1),!p.startsWith("data:"))continue;let b=p.slice(5).trim();if(!b||b==="[DONE]")continue;let y;try{y=JSON.parse(b)}catch{continue}y.usage&&(u.inputTokens=y.usage.prompt_tokens??0,u.outputTokens=y.usage.completion_tokens??0,u.cacheReadTokens=y.usage.prompt_tokens_details?.cached_tokens??0,u.inputTokens-=u.cacheReadTokens);let k=y.choices?.[0]?.delta;k?.content&&(u.text+=k.content,i(k.content));for(let v of k?.tool_calls??[]){let F=v.index??u.toolCalls.length;u.toolCalls[F]??={id:v.id??`call_${F}`,type:"function",function:{name:"",arguments:""}};let $=u.toolCalls[F];v.id&&($.id=v.id),v.function?.name&&($.function.name+=v.function.name),v.function?.arguments&&($.function.arguments+=v.function.arguments)}}}}finally{d.cancel().catch(()=>{})}return u.toolCalls=u.toolCalls.filter(g=>g?.function.name),u}function Le(t){if(!t)return{};try{return JSON.parse(t)}catch{return{}}}function ie(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}var ae=["open-weights","frontier"];function We(t){return ae.includes(t)}function je(t){return t==="user-hardware"||t==="user-subscription"||t==="user-api-key"||t==="open-weights"||t==="frontier"}function H(t){return t.type==="done"||t.type==="error"}var Be=["search","fetch","read","write","edit","bash","files","agent","todo","think","sources","tool"];var de=new Set(["delta","thinking","status","done","error"]);function J(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=h(n.runId);if(typeof n.type=="string"&&de.has(n.type)){let o=K(n);return o?{kind:"event",runId:r,event:o,...ue(n)}:null}switch(n.type){case"event":{if(!n.event||typeof n.event!="object")return null;let o=K(n.event);return o?{kind:"event",runId:r,event:o,...ue(n.event)}:null}case"usage":{let o=pe(n.usage);return o?{kind:"usage",runId:r,usage:o}:null}case"tool_call":{let o=h(n.callId),s=h(n.name);return!o||!s?null:{kind:"tool_call",runId:r,callId:o,name:s,input:n.input,...n.answered===!0?{answered:!0}:{}}}case"approval_request":{let o=h(n.approvalId),s=h(n.tool);return!o||!s?null:{kind:"approval",runId:r,approvalId:o,tool:s,input:n.input,cwd:h(n.cwd),...n.answered===!0?{answered:!0}:{}}}default:return null}}function ue(t){let e=t.sealed;return typeof e=="string"&&e.length>0?{sealed:e}:{}}function K(t){let e=typeof t.type=="string"&&de.has(t.type)?t.type:null;if(!e)return null;let n={type:e},r=h(t.text);r!==void 0&&(n.text=r);let o=h(t.message);o!==void 0&&(n.message=o);let s=h(t.tool);s!==void 0&&(n.tool=s);let i=h(t.tier);i!==void 0&&(n.tier=i);let a=pe(t.usage);a&&(n.usage=a);let u=h(t.reason);u!==void 0&&(n.reason=u),typeof t.retryable=="boolean"&&(n.retryable=t.retryable);let d=t.turn&&typeof t.turn=="object"?h(t.turn.text):void 0;d!==void 0&&(n.turn={text:d});let f=h(t.session);f!==void 0&&(n.session=f);let m=h(t.toolInput);m!==void 0&&(n.toolInput=m);let g=Ge(t.git);return g&&(n.git=g),(t.state==="interrupted"||t.state==="resumed")&&(n.state=t.state),n}function Ge(t){if(!t||typeof t!="object")return null;let e=t,n=h(e.branch);return!n||!Array.isArray(e.files)||!Array.isArray(e.commits)?null:{branch:n,base:h(e.base)??"",head:h(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:h(r.sha)??"",subject:h(r.subject)??""})),dirty:e.dirty===!0}}function pe(t){if(!t||typeof t!="object")return null;let e=t,n={model:h(e.model)??"unknown",inputTokens:R(e.inputTokens),outputTokens:R(e.outputTokens),cacheReadTokens:R(e.cacheReadTokens),cacheWriteTokens:R(e.cacheWriteTokens),webSearches:R(e.webSearches)},r=h(e.costClass);r!==void 0&&(n.costClass=r);let o=h(e.provider);return o!==void 0&&(n.provider=o),typeof e.costMicros=="number"&&Number.isFinite(e.costMicros)&&(n.costMicros=e.costMicros),n}function h(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*fe(t){let e=t.body;if(!e)throw new c({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"),o=e.getReader(),s=new TextDecoder,i="",a=[],u,d=f=>u===void 0?f:{...f,seq:u};try{for(;;){let m=await o.read();if(m.done)break;for(i+=s.decode(m.value,{stream:!0});;){let g=i.indexOf(`
5
+ `);if(g===-1)break;let l=ce(i.slice(0,g));if(i=i.slice(g+1),r){let p=l.trim()?J(l):null;p&&(yield p);continue}if(l===""){let p=a.join(`
6
+ `);if(a=[],p==="[DONE]")return;let b=p?J(p):null;b&&(yield d(b)),u=void 0;continue}if(l.startsWith("id:")){let p=Number(l.slice(3).trim());u=Number.isInteger(p)&&p>0?p:void 0;continue}le(l,a)}}!r&&i&&le(ce(i),a);let f=r?i.trim():a.join(`
7
+ `);if(f&&f!=="[DONE]"){let m=J(f);m&&(yield r?m:d(m))}}finally{o.cancel().catch(()=>{})}}function le(t,e){if(t.startsWith(":"))return;let n=t.indexOf(":");if(n===-1||t.slice(0,n)!=="data")return;let r=t.slice(n+1);e.push(r.startsWith(" ")?r.slice(1):r)}function ce(t){return t.endsWith("\r")?t.slice(0,-1):t}function He(t){return t}function E(t){let e=new Map;for(let n of t??[]){if(!n?.name)throw new c({code:"invalid_request",message:"Every tool needs a name."});if(typeof n.execute!="function")throw new c({code:"invalid_request",message:`Tool "${n.name}" has no execute function. A tool Soba cannot call is not a tool.`});if(e.has(n.name))throw new c({code:"invalid_request",message:`Two tools are named "${n.name}". Tool names must be unique within a run.`});e.set(n.name,n)}return e}function q(t){return[...t.values()].map(e=>({name:e.name,description:e.description??"",inputSchema:e.inputSchema??{type:"object"}}))}function P(t){if(t===void 0)return null;if(typeof t=="string")return t;try{return JSON.parse(JSON.stringify(t))}catch{return String(t)}}function I(t){return t instanceof Error?t.message||t.name:typeof t=="string"?t:String(t)}var Je=9e4,A=class{#t;#o;#r;#s=!1;#i;#e;#n=new AbortController;#a=new AbortController;#u=new Set;#l;constructor(e){this.#e=e,this.#t=e.response.headers.get("soba-run-id")??"",this.#i=e.after??0,this.#l=C(e.signal,this.#n)}get cursor(){return this.#i}get servedWithoutSoba(){return this.#e.local!==void 0}get resumable(){return this.#e.response.headers.get("soba-resumable")==="1"}get runId(){return this.#t}get tier(){return this.#o}get usage(){return this.#r}[Symbol.asyncIterator](){return this.#d()}async text(){let e="";for await(let n of this)if(n.type==="delta"&&n.text&&(e+=n.text),n.type==="error")throw new c({code:"run_failed",message:n.message??"The run ended with an error.",runId:this.#t,retryable:!1});return e}async cancel(){if(this.#n.abort(new c({code:"canceled",message:"The run was cancelled."})),this.#a.abort(new c({code:"canceled",message:"The run was cancelled."})),this.#e.local)return this.#e.local.cancel(this.#n.signal.reason);if(this.#t)try{await T(this.#e.config,{method:"POST",path:`/runs/${encodeURIComponent(this.#t)}/cancel`,retry:!1})}catch(e){this.#e.onWarning("Could not tell Soba the run was cancelled.",e)}}async#c(e){let n=Date.now()+Je,r=e;for(let o=0;Date.now()<n;o++){if(this.#n.signal.aborted)throw w(this.#n.signal.reason);o>0&&await G(Math.min(1e3*o,5e3),this.#n.signal);try{return await T(this.#e.config,{method:"GET",path:`/runs/${encodeURIComponent(this.#t)}/stream`,query:{after:this.#i},accept:"text/event-stream",signal:this.#n.signal,retry:!1})}catch(s){if(r=w(s),!["server_error","connection","timeout","rate_limited"].includes(r.code))break}}throw new c({code:"stream_truncated",message:`The run stream ended without a \`done\` or \`error\` event, and reading on failed: ${r.message}`,runId:this.#t,cause:r})}async*#d(){if(this.#s)throw new c({code:"invalid_request",message:"This run has already been consumed. A run's events can only be read once.",runId:this.#t});this.#s=!0;let e=!1;try{let n=this.#e.response;for(;;){for await(let o of fe(n)){if(o.runId&&!this.#t&&(this.#t=o.runId),o.seq!==void 0&&(this.#i=o.seq),o.kind==="event"){let s=this.#e.runKey?await this.#h(o):o.event;if(!s)continue;if(s.tier&&(this.#o=s.tier),s.usage&&(this.#r=s.usage),e=H(s),yield s,e)return;continue}if(o.kind==="usage"){this.#r=o.usage;continue}this.#m(this.#b(o))}let r=new c({code:"stream_truncated",message:"The run stream ended without a `done` or `error` event.",runId:this.#t});if(!this.resumable||!this.#t||this.#e.local)throw r;n=await this.#c(r)}}finally{e||this.#a.abort(new c({code:"canceled",message:"The run ended before this tool finished."})),await Promise.allSettled([...this.#u]),this.#n.abort(),this.#l()}}#m(e){this.#u.add(e),e.finally(()=>this.#u.delete(e)).catch(()=>{})}async#h(e){let n=this.#e.runKey;if(!e.sealed)return e.event.type==="delta"||e.event.type==="thinking"?(this.#e.onWarning("Dropped unsealed text on an encrypted run.",e.event),null):e.event;try{let r=await L(n,e.sealed);if(!r||typeof r!="object")throw new Error("not an object");return K({...e.event,...r})}catch(r){return this.#e.onWarning("Dropped an event on an encrypted run that would not open.",r),null}}async#y(e){let n=this.#e.runKey;if(!n)return{value:e};let r=X(e);if(r)try{return{value:await L(n,r)}}catch{return}}async#b(e){if(!((e.kind==="tool_call"||e.kind==="approval")&&e.answered)){if(this.#e.runKey&&(e.kind==="tool_call"||e.kind==="approval")){let n=await this.#y(e.input);if(!n){this.#e.onWarning(`Ignored a ${e.kind==="tool_call"?"tool call":"approval"} on an encrypted run that was not sealed by the machine.`),e.kind==="approval"&&await this.#p(`/runs/${encodeURIComponent(this.#t)}/approval`,{approvalId:e.approvalId,decision:"deny"});return}if(e.kind==="tool_call")return this.#f({...e,input:n.value});let{input:r,cwd:o}=n.value??{};return this.#g({...e,input:r,...typeof o=="string"&&o?{cwd:o}:{}})}if(e.kind==="tool_call")return this.#f(e);if(e.kind==="approval")return this.#g(e)}}async#f(e){let n=this.#e.tools.get(e.name),r,o=!1;if(!n)r=`No tool named "${e.name}" is registered by this app.`,o=!0;else{let i={runId:this.#t,user:this.#e.user,callId:e.callId,signal:this.#a.signal};try{r=await n.execute(e.input,i)}catch(a){r=I(a),o=!0}}if(this.#e.local){this.#e.local.deliver({callId:e.callId,result:P(r),isError:o});return}let s=P(r);await this.#p(`/runs/${encodeURIComponent(this.#t)}/tool_result`,{callId:e.callId,result:this.#e.runKey?{$sealed:await N(this.#e.runKey,s)}:s,isError:o})}async#g(e){let n="deny",r;if(!this.#e.approve)r="This app did not supply an approver, so escalations are denied.";else try{let o={runId:this.#t,approvalId:e.approvalId,tool:e.tool,input:e.input};e.cwd&&(o.cwd=e.cwd),n=await this.#e.approve(o)==="allow"?"allow":"deny"}catch(o){r=I(o)}await this.#p(`/runs/${encodeURIComponent(this.#t)}/approval`,{approvalId:e.approvalId,decision:n,...r?{reason:r}:{},...this.#e.runKey?{sealed:await N(this.#e.runKey,{approvalId:e.approvalId,decision:n})}:{}})}async#p(e,n){if(!this.#t){this.#e.onWarning("Soba sent a frame before the run had an id, so it could not be answered.",n);return}try{await(await T(this.#e.config,{method:"POST",path:e,body:n})).text()}catch(r){this.#e.onWarning(`Could not deliver an answer to ${e}.`,w(r))}}};var ge="https://api.soba.so/v1",me="https://soba.so/v1",ze=3e4,Qe=2,z=class{#t;#o;#r;#s;#i=Xe();#e;fallback;users;usage;connect;plans;runs;ops;terminals;constructor(e={}){let n=e.apiKey??D("SOBA_KEY")??D("SOBA_API_KEY");if(!n)throw new c({code:"unauthorized",message:"No Soba API key. Pass `apiKey`, or set SOBA_KEY. Keys are shaped sk_soba_<id>.<secret> and come from your dashboard."});if(Ve()&&!e.dangerouslyAllowBrowser)throw new c({code:"invalid_request",message:"A Soba app key is a server credential and this looks like a browser. Call Soba from your server, or pass dangerouslyAllowBrowser if you are certain."});if(this.#r=e.onWarning??(()=>{}),this.#s=e.encrypt===!0?{}:e.encrypt?e.encrypt:void 0,this.#t={apiKey:n,baseURL:e.baseURL??D("SOBA_BASE_URL")??ge,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??ze,maxRetries:e.maxRetries??Qe},this.#o={...this.#t,baseURL:e.webBaseURL??D("SOBA_WEB_URL")??me},typeof this.#t.fetch!="function")throw new c({code:"invalid_request",message:"No global fetch. Run on Node 22 or newer, or pass your own `fetch`."});let r=new M({http:this.#t,onWarning:this.#r,off:e.fallback===!1});this.#e=r,this.fallback={prime:()=>r.prime(),flush:()=>r.flush(),get pending(){return r.pending}},this.users={get:o=>this.request("GET",`/users/${encodeURIComponent(o)}`),compute:async o=>(await this.request("GET",`/users/${encodeURIComponent(o)}/compute`)).machines,setQuantity:(o,s,i)=>S(this.#o,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/quantity`,body:{quantity:i}}),check:(o,s,i)=>S(i?.use?{...this.#o,maxRetries:0}:this.#o,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/check`,body:i?.use?{use:i.use}:{}}),track:(o,s,i=1)=>S({...this.#o,maxRetries:0},{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/track`,body:{amount:i}})},this.usage={list:o=>this.request("GET","/usage",{query:{...o}})},this.connect=()=>this.request("GET","/connect"),this.runs={start:async o=>{if(!o.user)throw new c({code:"user_required",status:422,message:"`user` is required."});if(this.#s)throw new c({code:"invalid_request",message:"Detached runs cannot be encrypted end to end yet. Use soba.run() on a client with `encrypt`, or a client without it."});let s=E(o.tools),i={user:o.user,model:o.model??"auto",detached:!0};o.webhook&&(i.webhook=o.webhook),o.prompt&&(i.prompt=o.prompt),o.messages?.length&&(i.messages=o.messages),o.system&&(i.system=o.system),o.runtime&&(i.runtime=o.runtime),s.size&&(i.tools=q(s)),o.route&&(i.route=o.route),o.policy&&(i.policy=o.policy),o.metadata&&(i.metadata=o.metadata),o.task&&(i.task=o.task),o.surface&&(i.surface=o.surface),o.maxDurationMs&&(i.maxDurationMs=o.maxDurationMs),o.title&&(i.title=o.title),o.worktree&&(i.worktree=o.worktree),o.resume&&(i.resume=o.resume);let a=await S(this.#t,{method:"POST",path:"/runs",body:i,retry:"unsent"}),u={id:a.id};return a.stream&&(u.stream={url:a.stream.url,token:a.stream.token,expiresAt:a.stream.expires_at}),o.answerTools==="here"&&(u.answered=(async()=>{let d=await this.runs.attach(a.id,{user:o.user,tools:o.tools??[]});for await(let f of d);})().catch(d=>this.#r("Answering this run's tool calls stopped.",d))),u},attach:async(o,s)=>{if(!s.user)throw new c({code:"user_required",status:422,message:"`user` is required."});let i=await T(this.#t,{method:"GET",path:`/runs/${encodeURIComponent(o)}/stream`,...s.after?{query:{after:s.after}}:{},accept:"text/event-stream",signal:s.signal});return new A({config:this.#t,response:i,user:s.user,tools:E(s.tools),approve:s.approve,onWarning:this.#r,signal:s.signal,after:s.after??0})},cancel:async o=>{await this.request("POST",`/runs/${encodeURIComponent(o)}/cancel`,{body:{}})}},this.ops={run:o=>{if(!o.user)throw new c({code:"user_required",status:422,message:"`user` is required \u2014 it is how Soba knows whose machine to ask."});return this.request("POST","/ops",{body:{...o}})}},this.terminals={open:async o=>{if(!o.user)throw new c({code:"user_required",status:422,message:"`user` is required \u2014 it is how Soba knows whose machine to open it on."});let s=await this.request("POST","/term",{body:{...o}}),i=new URL(this.#t.baseURL);i.protocol=i.protocol==="http:"?"ws:":"wss:";let a=new URL(s.path,`${i.protocol}//${i.host}`);return a.searchParams.set("ticket",s.ticket),{termId:s.termId,url:a.toString(),expiresAt:s.expiresAt}}},this.plans={list:o=>this.request("GET","/plans",{...o?.user?{query:{user:o.user}}:{}})}}get baseURL(){return this.#t.baseURL}async run(e){if(!e.user)throw new c({code:"user_required",status:422,message:"`user` is required. A run with no user cannot be attributed or metered, so it cannot be defaulted."});if(!e.prompt&&!e.messages?.length)throw new c({code:"invalid_request",status:400,message:"A run needs a `prompt` or a non-empty `messages`."});let n=E(e.tools),r={user:e.user,model:e.model??"auto"};e.prompt&&(r.prompt=e.prompt),e.messages?.length&&(r.messages=e.messages),e.system&&(r.system=e.system),e.runtime&&(r.runtime=e.runtime),n.size&&(r.tools=q(n)),e.route&&(r.route=e.route),e.policy&&(r.policy=e.policy),e.metadata&&(r.metadata=e.metadata),e.task&&(r.task=e.task),r.resumable=e.resumable?!0:"restarts",e.maxDurationMs&&(r.maxDurationMs=e.maxDurationMs);let o,s;try{if(this.#s){let i=await this.#n(e.user,e.signal);if(i.length===0)throw new c({code:"no_compute",status:409,message:"None of this person's machines can open an encrypted run, so nothing was sent to Soba. Serve it with your own provider.",retryable:!1});s=await Q(),r.sealed=await V(s,{...r.prompt!==void 0?{prompt:r.prompt}:{},...r.messages!==void 0?{messages:r.messages}:{},...r.system!==void 0?{system:r.system}:{},...r.tools!==void 0?{tools:r.tools}:{}},i),delete r.prompt,delete r.messages,delete r.system,delete r.tools}o=await T(this.#t,{method:"POST",path:"/runs",body:r,accept:"text/event-stream",signal:e.signal,retry:"unsent"})}catch(i){if(!this.#e.canServe(i,e.route))throw i;let a=this.#e.serve({runId:globalThis.crypto.randomUUID(),user:e.user,model:e.model,route:e.route,system:e.system,messages:e.messages?.length?e.messages:[{role:"user",content:e.prompt??""}],tools:q(n),task:e.task},e.signal);return this.#r("Soba could not be reached; your own provider is answering this run.",i),new A({config:this.#t,response:a.response,user:e.user,tools:n,approve:e.approve,onWarning:this.#r,signal:e.signal,local:{deliver:a.deliver,cancel:a.stop}})}return this.#e.refreshSoon(),this.#e.flushSoon(),new A({config:this.#t,response:o,user:e.user,tools:n,approve:e.approve,onWarning:this.#r,signal:e.signal,...s?{runKey:s}:{}})}async#n(e,n){let r=await S(this.#t,{method:"GET",path:"/keys",query:{user:e},...n?{signal:n}:{}}),o=await Promise.all((Array.isArray(r.data)?r.data:[]).filter(Y).map(async a=>({...a,fingerprint:await W(a.publicKey),user:e}))),s=this.#s?.trust,i=[];for(let a of o)(!s||await s(a))&&i.push(a);return this.#a(e,i)}async#a(e,n){let r=this.#s?.pin;if(!r||n.length===0)return n;let o=(r===!0?void 0:r.store)??this.#i,s=r===!0?void 0:r.onNewKey,i=await o.get(e)??[];if(i.length===0)return await o.set(e,n.map(d=>d.publicKey)),n;let a=[],u=[];for(let d of n)i.includes(d.publicKey)?a.push(d):s&&await s(d)?(a.push(d),u.push(d.publicKey)):this.#r(`Refused a key for "${e}" that was not pinned (fingerprint ${d.fingerprint}).`,d);return u.length&&await o.set(e,[...i,...u]),a}async request(e,n,r={}){return S(this.#t,{method:e,path:n,...r})}};function D(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}function Ve(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}function Xe(){let t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}var Ye=300;function Ze(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function et(t,e){if(t.length!==e.length)return!1;let n=0;for(let r=0;r<t.length;r++)n|=t.charCodeAt(r)^e.charCodeAt(r);return n===0}async function tt(t,e,n,r={}){let o=Object.fromEntries((e??"").split(",").map(l=>{let p=l.indexOf("=");return[l.slice(0,p).trim(),l.slice(p+1).trim()]})),s=Number(o.t),i=o.v1??"",a=l=>new c({code:"unauthorized",status:401,message:l});if(!Number.isFinite(s)||!i)throw a("Missing or malformed Soba-Signature.");let u=Math.floor((r.now??Date.now())/1e3);if(Math.abs(u-s)>(r.toleranceSeconds??Ye))throw a("This delivery is too old to accept.");let d=await globalThis.crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),f=Ze(await globalThis.crypto.subtle.sign("HMAC",d,new TextEncoder().encode(`${s}.${t}`)));if(!et(f,i))throw a("The Soba-Signature does not match.");let m;try{m=JSON.parse(t)}catch{throw new c({code:"invalid_request",message:"The delivery is not JSON."})}let g=m;if(g.type!=="run.event"&&g.type!=="run.tool_call"||typeof g.run_id!="string")throw new c({code:"invalid_request",message:"Not a Soba run delivery."});return g}async function nt(t,e){if(t.type!=="run.tool_call")return null;let{call_id:n,name:r,input:o}=t.data,s=E(e.tools).get(r);if(!s)return{result:`Unknown tool: ${r}`,is_error:!0};try{let i=await s.execute(o??{},{runId:t.run_id,user:e.user??"",callId:n,signal:AbortSignal.timeout(25e3)});return{result:P(i)}}catch(i){return{result:I(i),is_error:!0}}}export{ge as DEFAULT_BASE_URL,me as DEFAULT_WEB_BASE_URL,ae as METERED_CLASSES,A as Run,z as Soba,c as SobaError,Be as TOOL_SLUGS,j as VERSION,W as fingerprint,nt as handleRunWebhook,je as isCostClass,We as isMetered,H as isTerminal,He as tool,tt as verifyWebhook};
@@ -130,6 +130,11 @@ export interface RunPolicy {
130
130
  allowNetwork?: string[];
131
131
  /** The owner's own browser, every action approved live. Only if their machine grants it. */
132
132
  browser?: boolean;
133
+ /** Skills the owner added to Soba, by name: `["pdf"]`. Asked for once, on their machine. */
134
+ skills?: string[];
135
+ /** Services the owner signed in to in Soba, with what this run does: `["gmail:read"]`.
136
+ * Every write stops for a yes on their machine. */
137
+ connections?: string[];
133
138
  }
134
139
  /**
135
140
  * WHICH ECONOMICS a run may use. You declare intent, not a runtime, which is
@@ -130,6 +130,14 @@ export interface PlanListItem {
130
130
  /** About how many runs a credit plan's allowance buys at this app's typical
131
131
  * run cost: "About 265 tasks a month". Null when it cannot be said. */
132
132
  estimated_tasks?: number | null;
133
+ /** A credit plan's top-up packs, in order: "1,000 credits for $10".
134
+ * Listed only; nothing sells one yet. Optional for older servers. */
135
+ credit_packs?: {
136
+ credits: number;
137
+ price: number;
138
+ }[];
139
+ /** When bought credits run out: `never` or `month_end`. */
140
+ credit_expiry?: string;
133
141
  /** A plan sold by conversation: "Talk to us" links here. */
134
142
  contact_url?: string | null;
135
143
  /** "Everything in" this plan id; its card lists that, then `features_own`. */
package/dist/run.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type HttpConfig } from "./http.js";
2
2
  import { type AgentEvent, type CostClass, type RunUsage } from "./protocol.js";
3
+ import { type RunKey } from "./e2e.js";
3
4
  import { type ToolDefinition } from "./tools.js";
4
5
  export type ApprovalDecision = "allow" | "deny";
5
6
  export interface ApprovalRequest {
@@ -35,6 +36,13 @@ export interface RunInit {
35
36
  }) => void;
36
37
  cancel: (reason: unknown) => void;
37
38
  };
39
+ /**
40
+ * AN END-TO-END RUN'S KEY (`encrypt` on the client). Every event's content is
41
+ * opened with it, every tool call and approval must arrive sealed with it,
42
+ * and every answer leaves sealed with it. Content that arrives unsealed on
43
+ * such a run was written by whoever carried it, and is dropped.
44
+ */
45
+ runKey?: RunKey;
38
46
  }
39
47
  /**
40
48
  * A run in flight.
package/dist/stream.d.ts CHANGED
@@ -9,6 +9,8 @@ export type StreamFrame = ({
9
9
  kind: "event";
10
10
  runId?: string;
11
11
  event: AgentEvent;
12
+ /** An end-to-end run's content, still sealed. `Run` opens it. */
13
+ sealed?: string;
12
14
  } | {
13
15
  kind: "usage";
14
16
  runId?: string;
@@ -32,6 +34,7 @@ export type StreamFrame = ({
32
34
  seq?: number;
33
35
  };
34
36
  export declare function parseStreamFrame(raw: string): StreamFrame | null;
37
+ export declare function parseEvent(o: Record<string, unknown>): AgentEvent | null;
35
38
  /**
36
39
  * Yield frames off a live response body.
37
40
  *
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.0.13";
1
+ export declare const VERSION = "0.0.15";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soba-so/sdk",
3
- "version": "0.0.13",
3
+ "version": "0.0.15",
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",