@soba-so/sdk 0.0.17 → 0.0.19

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/README.md CHANGED
@@ -139,23 +139,34 @@ failures **before** a response arrives and never after, and it does not retry
139
139
  `409 no_compute` at all: that clears when a laptop wakes up, which is minutes
140
140
  away, not milliseconds. Your app owns that decision.
141
141
 
142
- ## Making apps
142
+ ## Managing Soba: workspaces, apps, keys
143
143
 
144
- A product that turns each thing it builds into its own Soba app uses a
145
- **workspace key** (`wk_soba_…`, from `npx @soba-so/cli login --workspace-key`)
146
- with a separate client:
144
+ `SobaManagement` is the management API, the way Supabase's and Railway's work. It
145
+ takes a personal access token (`pat_soba_…`, from `npx @soba-so/cli login`) that
146
+ acts as you, or a workspace key (`wk_soba_…`, from `soba workspace-key`) for a
147
+ server that makes an app per thing it builds:
147
148
 
148
149
  ```js
149
- import { Soba, SobaWorkspace } from "@soba-so/sdk"
150
+ import { Soba, SobaManagement } from "@soba-so/sdk"
150
151
 
151
- const workspace = new SobaWorkspace({ apiKey: process.env.SOBA_WORKSPACE_KEY })
152
- const app = await workspace.apps.create({ name: "Study planner" })
153
- const { keys, publishable_keys } = await workspace.apps.keys(app.id)
154
- const soba = new Soba({ apiKey: keys.production })
152
+ const soba = new SobaManagement({ accessToken: process.env.SOBA_ACCESS_TOKEN })
153
+
154
+ await soba.me()
155
+ const [workspace] = await soba.workspaces.list()
156
+ const app = await soba.apps.create({ workspace: workspace.id, name: "Study planner" })
157
+ await soba.apps.update(app.id, { name: "Study coach" })
158
+ const { key } = await soba.apps.keys.create(app.id, { environment: "production" })
159
+ await soba.apps.keys.list(app.id)
160
+ await soba.apps.delete(app.id) // a person's token only
161
+
162
+ const runs = new Soba({ apiKey: key }) // that app's own key, which runs things
155
163
  ```
156
164
 
157
- `apps.list()` returns the workspace's apps. Each client refuses the other's key,
158
- so a workspace key never travels on a run. Keys are shown once; store them.
165
+ Each client refuses the other's credential before sending anything, so a
166
+ management token never travels on a run and an app key never manages anything.
167
+ Keys are shown once; store them. A personal token signs itself out after 90
168
+ days without use. `SobaWorkspace` (0.0.17) is deprecated: it still works, and
169
+ `SobaManagement` with the same workspace key does everything it does.
159
170
 
160
171
  ## Errors
161
172
 
package/dist/http.d.ts CHANGED
@@ -10,7 +10,7 @@ export interface HttpConfig {
10
10
  maxRetries: number;
11
11
  }
12
12
  export interface RequestOptions {
13
- method: "GET" | "POST" | "DELETE";
13
+ method: "GET" | "POST" | "PATCH" | "DELETE";
14
14
  path: string;
15
15
  query?: Record<string, string | number | boolean | undefined>;
16
16
  body?: unknown;
package/dist/index.d.ts CHANGED
@@ -1,8 +1,9 @@
1
1
  export { type AttachParams, DEFAULT_BASE_URL, DEFAULT_WEB_BASE_URL, type DetachedRunParams, type EncryptOptions, type FallbackControl, type OfferedKey, type OpKind, type OpParams, type OpResult, type PinStore, type RunParams, Soba, type SobaOptions, type StartedRun, type TerminalBooking, type TerminalParams, } from "./client.js";
2
2
  export { fingerprint, type MachineKey } from "./e2e.js";
3
3
  export { SobaError, type SobaErrorCode } from "./errors.js";
4
+ export { type ManagedApp, type ManagedKey, type Me, type MintedKey, SobaManagement, type SobaManagementOptions, type Workspace, } from "./management.js";
4
5
  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";
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";
6
+ export type { Allowance, ConnectContextResponse, ConnectedMachine, CurrentPlanItem, FeatureCheckResult, FeatureDenial, MachineListItem, MachineListState, MachineRuntime, PlanFeatureWire, PlanLimitsWire, PlanListItem, PlanListResponse, PlanSummary, QuantityResult, RuntimeListItem, SobaUser, TrackResult, UsagePage, UsageQuery, UsageRow, } from "./resources.js";
6
7
  export { type ApprovalDecision, type ApprovalRequest, type Approver, Run, } from "./run.js";
7
8
  export { type ToolContext, type ToolDefinition, tool } from "./tools.js";
8
9
  export { VERSION } from "./version.js";
package/dist/index.mjs CHANGED
@@ -1,7 +1,7 @@
1
- var be="soba-e2e-wrap-v1",we="soba-e2e-request-v1",O="e1.",A=new TextEncoder,ke=new TextDecoder;async function X(){let t=crypto.getRandomValues(new Uint8Array(32));return{raw:t,key:await ve(t)}}async function Y(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:A.encode(`${u}.${i}`),info:A.encode(be)},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:A.encode(we)},t.key,A.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:A.encode("soba-e2e-down")},t.key,A.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:A.encode("soba-e2e-up")},t.key,U(r));return JSON.parse(ke.decode(o))}function Z(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 j(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 ee(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 ve(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??Se.has(e.code),this.retryAfterMs=e.retryAfterMs,this.runId=e.runId}},Se=new Set(["rate_limited","server_error","connection","timeout","stream_truncated"]),Re={400:"invalid_request",401:"unauthorized",402:"payment_required",403:"forbidden",404:"not_found",409:"no_compute",422:"user_required",429:"rate_limited"};function Te(t){let e=Re[t];return e||(t>=500?"server_error":t>=400?"invalid_request":"unknown")}var te=new WeakSet;function ne(t){return te.has(t)}async function re(t){let e=t.status,n="";try{n=await t.text()}catch{}let r=_e(n),o=new c({code:r?.code??Te(e),type:r?.type,message:r?.message??xe(e,t.statusText,n),status:e,retryAfterMs:Ee(t.headers.get("retry-after")),runId:t.headers.get("soba-run-id")??void 0});return!r&&(e===502||e===503||e===504)&&te.add(o),o}function _e(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:Ae.has(r.code)?r.code:void 0}}var Ae=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 xe(t,e,n){let r=n.trim().slice(0,200),o=r?`: ${r}`:"";return`Soba returned ${t}${e?` ${e}`:""}${o}`}function Ee(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 B="0.0.17";var Ce=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]);function G(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"&&Ce.has(r))return!0;e=e.cause}return!1}var Pe=8e3,Ie=3e4;async function T(t,e){let n=Me(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"||G(i));for(let i=0;i<r;i++){i>0&&await H(Ke(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:Oe(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 re(f),!s(o)||i===r-1)throw o}throw o??new c({code:"unknown",message:"The request failed with no error."})}async function k(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 Oe(t,e){let n={authorization:`Bearer ${t.apiKey}`,accept:e.accept??"application/json","user-agent":Ue(),...t.headers};return e.body!==void 0&&(n["content-type"]="application/json"),n}function Ue(){let t=typeof process>"u"?"":` node/${process.versions?.node??"?"}`;return`soba-sdk/${B}${t}`}function Me(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 Ke(t,e){if(e?.retryAfterMs!==void 0)return Math.min(e.retryAfterMs,Ie);let n=Math.min(Pe,500*2**(t-1));return Math.round(n*(.5+Math.random()/2))}function H(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 qe=5*60*1e3,oe=25,De=1e3,Fe=100,M=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??=k(this.#e,{method:"GET",path:"/fallback",retry:!1}).then(e=>{this.#s={enabled:e?.enabled===!0,providers:(e?.providers??[]).map(se).filter(ie)},this.#i=Date.now()}).catch(()=>{}).finally(()=>{this.#t=null}),this.#t}refreshSoon(){this.#r||Date.now()-this.#i<qe||this.prime()}get pending(){return this.#n.length}canServe(e,n){if(this.#r)return!1;let r=w(e);return!G(r)&&!ne(r)||r.code==="rate_limited"?!1:this.#l(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.#l(e.route),m=new TextEncoder,g=new ReadableStream({start:l=>{let p=b=>{try{l.enqueue(m.encode(`data: ${JSON.stringify(b)}
1
+ var ke="soba-e2e-wrap-v1",ve="soba-e2e-request-v1",O="e1.",A=new TextEncoder,Se=new TextDecoder;async function Z(){let t=crypto.getRandomValues(new Uint8Array(32));return{raw:t,key:await Re(t)}}async function ee(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,[]),g=await crypto.subtle.deriveBits({name:"X25519",public:d},a.privateKey,256),m=await crypto.subtle.importKey("raw",g,"HKDF",!1,["deriveKey"]),f=await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:A.encode(`${u}.${i}`),info:A.encode(ke)},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},f,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:A.encode(ve)},t.key,A.encode(JSON.stringify(e))));return{v:1,keys:r,iv:_(o),ct:_(s)}}async function L(t,e){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:n,additionalData:A.encode("soba-e2e-down")},t.key,A.encode(JSON.stringify(e===void 0?null:e))));return`${O}${_(n)}.${_(r)}`}async function N(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:A.encode("soba-e2e-up")},t.key,U(r));return JSON.parse(Se.decode(o))}function te(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 j(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 ne(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 Re(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??Te.has(e.code),this.retryAfterMs=e.retryAfterMs,this.runId=e.runId}},Te=new Set(["rate_limited","server_error","connection","timeout","stream_truncated"]),_e={400:"invalid_request",401:"unauthorized",402:"payment_required",403:"forbidden",404:"not_found",409:"no_compute",422:"user_required",429:"rate_limited"};function Ae(t){let e=_e[t];return e||(t>=500?"server_error":t>=400?"invalid_request":"unknown")}var re=new WeakSet;function oe(t){return re.has(t)}async function se(t){let e=t.status,n="";try{n=await t.text()}catch{}let r=xe(n),o=new c({code:r?.code??Ae(e),type:r?.type,message:r?.message??Ce(e,t.statusText,n),status:e,retryAfterMs:Pe(t.headers.get("retry-after")),runId:t.headers.get("soba-run-id")??void 0});return!r&&(e===502||e===503||e===504)&&re.add(o),o}function xe(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:Ee.has(r.code)?r.code:void 0}}var Ee=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 Ce(t,e,n){let r=n.trim().slice(0,200),o=r?`: ${r}`:"";return`Soba returned ${t}${e?` ${e}`:""}${o}`}function Pe(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 k(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 B="0.0.19";var Ie=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]);function G(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"&&Ie.has(r))return!0;e=e.cause}return!1}var Me=8e3,Oe=3e4;async function T(t,e){let n=qe(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"||G(i));for(let i=0;i<r;i++){i>0&&await H(De(i,o),e.signal);let a=new AbortController,u=P(e.signal,a),d=setTimeout(()=>{a.abort(new c({code:"timeout",message:`Soba did not answer within ${t.connectTimeoutMs}ms.`}))},t.connectTimeoutMs),g;try{g=await t.fetch(n,{method:e.method,headers:Ue(t,e),body:e.body===void 0?void 0:JSON.stringify(e.body),signal:a.signal})}catch(m){if(u(),o=k(a.signal.aborted?a.signal.reason??m:m),!s(o)||i===r-1)throw o;continue}finally{clearTimeout(d)}if(g.ok)return g;if(u(),o=await se(g),!s(o)||i===r-1)throw o}throw o??new c({code:"unknown",message:"The request failed with no error."})}async function b(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 Ue(t,e){let n={authorization:`Bearer ${t.apiKey}`,accept:e.accept??"application/json","user-agent":Ke(),...t.headers};return e.body!==void 0&&(n["content-type"]="application/json"),n}function Ke(){let t=typeof process>"u"?"":` node/${process.versions?.node??"?"}`;return`soba-sdk/${B}${t}`}function qe(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 De(t,e){if(e?.retryAfterMs!==void 0)return Math.min(e.retryAfterMs,Oe);let n=Math.min(Me,500*2**(t-1));return Math.round(n*(.5+Math.random()/2))}function H(t,e){return new Promise((n,r)=>{if(e?.aborted)return r(k(e.reason));let o=setTimeout(()=>{e?.removeEventListener("abort",s),n()},t);function s(){clearTimeout(o),r(k(e?.reason))}e?.addEventListener("abort",s,{once:!0})})}function P(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 We=5*60*1e3,ie=25,$e=1e3,Fe=100,K=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??=b(this.#e,{method:"GET",path:"/fallback",retry:!1}).then(e=>{this.#s={enabled:e?.enabled===!0,providers:(e?.providers??[]).map(ae).filter(ue)},this.#i=Date.now()}).catch(()=>{}).finally(()=>{this.#t=null}),this.#t}refreshSoon(){this.#r||Date.now()-this.#i<We||this.prime()}get pending(){return this.#n.length}canServe(e,n){if(this.#r)return!1;let r=k(e);return!G(r)&&!oe(r)||r.code==="rate_limited"?!1:this.#l(n).length>0}serve(e,n){let r=new AbortController,o=P(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,w)=>{let h=a.get(l);if(h)return a.delete(l),p(h);i.set(l,p),s.addEventListener("abort",()=>w(k(s.reason)),{once:!0})}),g=this.#l(e.route),m=new TextEncoder,f=new ReadableStream({start:l=>{let p=w=>{try{l.enqueue(m.encode(`data: ${JSON.stringify(w)}
2
2
 
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,Fe),n;try{n=(await k(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}}#c(e){this.#n.push(e),this.#n.length>De&&(this.#n.shift(),this.#o("Dropped the oldest unreported fallback run: too many waiting for Soba."))}#l(e){let n=this.#s??We();return n?.enabled?n.providers.filter(r=>ae(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=$e(u,e.model),f={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},m=!1,g=(l,p)=>this.#c({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=Ne(e);for(let b=0;;b++){if(b>=oe)throw new Error(`Stopped after ${oe} turns of tool calls.`);let y=await Le(this.#e.fetch,u,d,l,e.tools,s,v=>{m=!0,r({type:"delta",text:v})});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 v of y.toolCalls)r({type:"tool_call",callId:v.id,name:v.function.name,input:je(v.function.arguments)});for(let v of y.toolCalls){let S=await o(v.id);l.push({role:"tool",tool_call_id:v.id,content:typeof S.result=="string"?S.result:JSON.stringify(S.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 se(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 ie=t=>t!==null;function We(){let t=ue("SOBA_FALLBACK");if(!t)return null;try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),r=(JSON.parse(e).providers??[]).map(se).filter(ie);return r.length?{enabled:!0,providers:r}:null}catch{return null}}function ae(t){return ue(t.keyEnv)??t.apiKey}function $e(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 Ne(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 Le(t,e,n,r,o,s,i){let a=await t(`${e.baseUrl.replace(/\/+$/,"")}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${ae(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 v=y.choices?.[0]?.delta;v?.content&&(u.text+=v.content,i(v.content));for(let S of v?.tool_calls??[]){let W=S.index??u.toolCalls.length;u.toolCalls[W]??={id:S.id??`call_${W}`,type:"function",function:{name:"",arguments:""}};let $=u.toolCalls[W];S.id&&($.id=S.id),S.function?.name&&($.function.name+=S.function.name),S.function?.arguments&&($.function.arguments+=S.function.arguments)}}}}finally{d.cancel().catch(()=>{})}return u.toolCalls=u.toolCalls.filter(g=>g?.function.name),u}function je(t){if(!t)return{};try{return JSON.parse(t)}catch{return{}}}function ue(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}var ce=["open-weights","frontier"];function Be(t){return ce.includes(t)}function Ge(t){return t==="user-hardware"||t==="user-subscription"||t==="user-api-key"||t==="open-weights"||t==="frontier"}function J(t){return t.type==="done"||t.type==="error"}var He=["search","fetch","read","write","edit","bash","files","agent","todo","think","sources","tool"];var fe=new Set(["delta","thinking","status","done","error"]);function z(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"&&fe.has(n.type)){let o=K(n);return o?{kind:"event",runId:r,event:o,...le(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,...le(n.event)}:null}case"usage":{let o=ge(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 le(t){let e=t.sealed;return typeof e=="string"&&e.length>0?{sealed:e}:{}}function K(t){let e=typeof t.type=="string"&&fe.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=ge(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=Je(t.git);return g&&(n.git=g),(t.state==="interrupted"||t.state==="resumed")&&(n.state=t.state),n}function Je(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 ge(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*me(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=pe(i.slice(0,g));if(i=i.slice(g+1),r){let p=l.trim()?z(l):null;p&&(yield p);continue}if(l===""){let p=a.join(`
6
- `);if(a=[],p==="[DONE]")return;let b=p?z(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}de(l,a)}}!r&&i&&de(pe(i),a);let f=r?i.trim():a.join(`
7
- `);if(f&&f!=="[DONE]"){let m=z(f);m&&(yield r?m:d(m))}}finally{o.cancel().catch(()=>{})}}function de(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 pe(t){return t.endsWith("\r")?t.slice(0,-1):t}function ze(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 Qe=9e4,x=class{#e;#o;#r;#s=!1;#i;#t;#n=new AbortController;#a=new AbortController;#u=new Set;#c;constructor(e){this.#t=e,this.#e=e.response.headers.get("soba-run-id")??"",this.#i=e.after??0,this.#c=C(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 c({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 c({code:"canceled",message:"The run was cancelled."})),this.#a.abort(new c({code:"canceled",message:"The run was cancelled."})),this.#t.local)return this.#t.local.cancel(this.#n.signal.reason);if(this.#e)try{await T(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#l(e){let n=Date.now()+Qe,r=e;for(let o=0;Date.now()<n;o++){if(this.#n.signal.aborted)throw w(this.#n.signal.reason);o>0&&await H(Math.min(1e3*o,5e3),this.#n.signal);try{return await T(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 c({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 c({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 me(n)){if(o.runId&&!this.#e&&(this.#e=o.runId),o.seq!==void 0&&(this.#i=o.seq),o.kind==="event"){let s=this.#t.runKey?await this.#h(o):o.event;if(!s)continue;if(s.tier&&(this.#o=s.tier),s.usage&&(this.#r=s.usage),e=J(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.#e});if(!this.resumable||!this.#e||this.#t.local)throw r;n=await this.#l(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.#c()}}#m(e){this.#u.add(e),e.finally(()=>this.#u.delete(e)).catch(()=>{})}async#h(e){let n=this.#t.runKey;if(!e.sealed)return e.event.type==="delta"||e.event.type==="thinking"?(this.#t.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.#t.onWarning("Dropped an event on an encrypted run that would not open.",r),null}}async#y(e){let n=this.#t.runKey;if(!n)return{value:e};let r=Z(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.#t.runKey&&(e.kind==="tool_call"||e.kind==="approval")){let n=await this.#y(e.input);if(!n){this.#t.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.#e)}/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.#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 i={runId:this.#e,user:this.#t.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.#t.local){this.#t.local.deliver({callId:e.callId,result:P(r),isError:o});return}let s=P(r);await this.#p(`/runs/${encodeURIComponent(this.#e)}/tool_result`,{callId:e.callId,result:this.#t.runKey?{$sealed:await N(this.#t.runKey,s)}:s,isError:o})}async#g(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=I(o)}await this.#p(`/runs/${encodeURIComponent(this.#e)}/approval`,{approvalId:e.approvalId,decision:n,...r?{reason:r}:{},...this.#t.runKey?{sealed:await N(this.#t.runKey,{approvalId:e.approvalId,decision:n})}:{}})}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 T(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 he="https://api.soba.so/v1",F="https://soba.so/v1",Ve=3e4,Xe=2,Q=class{#e;#o;#r;#s;#i=Ze();#t;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(Ye()&&!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===!1?void 0:typeof e.encrypt=="object"?e.encrypt:{},this.#e={apiKey:n,baseURL:e.baseURL??D("SOBA_BASE_URL")??he,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??Ve,maxRetries:e.maxRetries??Xe},this.#o={...this.#e,baseURL:e.webBaseURL??D("SOBA_WEB_URL")??F},typeof this.#e.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.#e,onWarning:this.#r,off:e.fallback===!1});this.#t=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)=>k(this.#o,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/quantity`,body:{quantity:i}}),check:(o,s,i)=>k(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)=>k({...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, and encryption is on by default. Start this one from a client made with `encrypt: false`."});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 k(this.#e,{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.#e,{method:"GET",path:`/runs/${encodeURIComponent(o)}/stream`,...s.after?{query:{after:s.after}}:{},accept:"text/event-stream",signal:s.signal});return new x({config:this.#e,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.#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 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, or send it unencrypted from a client made with `encrypt: false`.",retryable:!1});s=await X(),r.sealed=await Y(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.#e,{method:"POST",path:"/runs",body:r,accept:"text/event-stream",signal:e.signal,retry:"unsent"})}catch(i){if(!this.#t.canServe(i,e.route))throw i;let a=this.#t.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 x({config:this.#e,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.#t.refreshSoon(),this.#t.flushSoon(),new x({config:this.#e,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 k(this.#e,{method:"GET",path:"/keys",query:{user:e},...n?{signal:n}:{}}),o=await Promise.all((Array.isArray(r.data)?r.data:[]).filter(ee).map(async a=>({...a,fingerprint:await j(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 k(this.#e,{method:e,path:n,...r})}};function D(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}function Ye(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}function Ze(){let t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}var et=300;function tt(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function nt(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 rt(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??et))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=tt(await globalThis.crypto.subtle.sign("HMAC",d,new TextEncoder().encode(`${s}.${t}`)));if(!nt(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 ot(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}}}var V=class{#e;apps;constructor(e={}){let n=e.apiKey??ye("SOBA_WORKSPACE_KEY");if(!n?.startsWith("wk_soba_"))throw new c({code:"unauthorized",message:n?"That is not a workspace key. Workspace keys are shaped wk_soba_<id>.<secret>; an app's sk_soba_ key goes to `new Soba()`.":"No workspace key. Pass `apiKey`, or set SOBA_WORKSPACE_KEY. Get one with `npx @soba-so/cli login --workspace-key`."});if(st())throw new c({code:"invalid_request",message:"A workspace key makes apps and mints their keys. It belongs on a server, never in a browser."});this.#e={apiKey:n,baseURL:e.baseURL??ye("SOBA_WEB_URL")??F,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??3e4,maxRetries:e.maxRetries??2};let r=this.#e;this.apps={list:async()=>(await k(r,{method:"GET",path:"/workspace/apps"})).data,create:({name:o})=>k(r,{method:"POST",path:"/workspace/apps",body:{name:o},retry:"unsent"}),keys:o=>k(r,{method:"POST",path:`/workspace/apps/${encodeURIComponent(o)}/keys`,body:{},retry:"unsent"})}}};function ye(t){return typeof process<"u"?process.env?.[t]:void 0}function st(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}export{he as DEFAULT_BASE_URL,F as DEFAULT_WEB_BASE_URL,ce as METERED_CLASSES,x as Run,Q as Soba,c as SobaError,V as SobaWorkspace,He as TOOL_SLUGS,B as VERSION,j as fingerprint,ot as handleRunWebhook,Ge as isCostClass,Be as isMetered,J as isTerminal,ze as tool,rt as verifyWebhook};
3
+ `))}catch{}};this.#d(e,g,p,d,s).catch(w=>p({type:"error",message:k(w).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: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,Fe),n;try{n=(await b(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}}#c(e){this.#n.push(e),this.#n.length>$e&&(this.#n.shift(),this.#o("Dropped the oldest unreported fallback run: too many waiting for Soba."))}#l(e){let n=this.#s??Le();return n?.enabled?n.providers.filter(r=>ce(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=Ne(u,e.model),g={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},m=!1,f=(l,p)=>this.#c({id:e.runId,user:e.user,supplier:u.id,model:d.model,input_tokens:g.inputTokens,output_tokens:g.outputTokens,cache_read_tokens:g.cacheReadTokens,cache_write_tokens:g.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=je(e);for(let w=0;;w++){if(w>=ie)throw new Error(`Stopped after ${ie} turns of tool calls.`);let h=await Be(this.#e.fetch,u,d,l,e.tools,s,v=>{m=!0,r({type:"delta",text:v})});if(g.inputTokens+=h.inputTokens,g.outputTokens+=h.outputTokens,g.cacheReadTokens+=h.cacheReadTokens,!h.toolCalls.length)break;m=!0,l.push({role:"assistant",content:h.text||null,tool_calls:h.toolCalls});for(let v of h.toolCalls)r({type:"tool_call",callId:v.id,name:v.function.name,input:Ge(v.function.arguments)});for(let v of h.toolCalls){let S=await o(v.id);l.push({role:"tool",tool_call_id:v.id,content:typeof S.result=="string"?S.result:JSON.stringify(S.result)})}}let p={model:d.model,provider:u.id,costClass:u.costClass,...g,webSearches:0};r({type:"usage",usage:p}),r({type:"done",usage:p}),f("done");return}catch(l){if(s.aborted)throw f("error","cancelled"),k(s.reason);if(a=`${u.name}: ${k(l).message}`,m)throw f("error",a),new c({code:"run_failed",message:a,retryable:!1})}}throw new c({code:"no_compute",message:a,retryable:!1})}};function ae(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 ue=t=>t!==null;function Le(){let t=le("SOBA_FALLBACK");if(!t)return null;try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),r=(JSON.parse(e).providers??[]).map(ae).filter(ue);return r.length?{enabled:!0,providers:r}:null}catch{return null}}function ce(t){return le(t.keyEnv)??t.apiKey}function Ne(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 je(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 Be(t,e,n,r,o,s,i){let a=await t(`${e.baseUrl.replace(/\/+$/,"")}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${ce(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 u={text:"",toolCalls:[],inputTokens:0,outputTokens:0,cacheReadTokens:0},d=a.body.getReader(),g=new TextDecoder,m="";try{for(;;){let f=await d.read();if(f.done)break;for(m+=g.decode(f.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 w=p.slice(5).trim();if(!w||w==="[DONE]")continue;let h;try{h=JSON.parse(w)}catch{continue}h.usage&&(u.inputTokens=h.usage.prompt_tokens??0,u.outputTokens=h.usage.completion_tokens??0,u.cacheReadTokens=h.usage.prompt_tokens_details?.cached_tokens??0,u.inputTokens-=u.cacheReadTokens);let v=h.choices?.[0]?.delta;v?.content&&(u.text+=v.content,i(v.content));for(let S of v?.tool_calls??[]){let $=S.index??u.toolCalls.length;u.toolCalls[$]??={id:S.id??`call_${$}`,type:"function",function:{name:"",arguments:""}};let F=u.toolCalls[$];S.id&&(F.id=S.id),S.function?.name&&(F.function.name+=S.function.name),S.function?.arguments&&(F.function.arguments+=S.function.arguments)}}}}finally{d.cancel().catch(()=>{})}return u.toolCalls=u.toolCalls.filter(f=>f?.function.name),u}function Ge(t){if(!t)return{};try{return JSON.parse(t)}catch{return{}}}function le(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}var de=["open-weights","frontier"];function He(t){return de.includes(t)}function Je(t){return t==="user-hardware"||t==="user-subscription"||t==="user-api-key"||t==="open-weights"||t==="frontier"}function J(t){return t.type==="done"||t.type==="error"}var ze=["search","fetch","read","write","edit","bash","files","agent","todo","think","sources","tool"];var me=new Set(["delta","thinking","status","done","error"]);function z(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"&&me.has(n.type)){let o=q(n);return o?{kind:"event",runId:r,event:o,...pe(n)}:null}switch(n.type){case"event":{if(!n.event||typeof n.event!="object")return null;let o=q(n.event);return o?{kind:"event",runId:r,event:o,...pe(n.event)}:null}case"usage":{let o=ye(n.usage);return o?{kind:"usage",runId:r,usage:o}:null}case"tool_call":{let o=y(n.callId),s=y(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=y(n.approvalId),s=y(n.tool);return!o||!s?null:{kind:"approval",runId:r,approvalId:o,tool:s,input:n.input,cwd:y(n.cwd),...n.answered===!0?{answered:!0}:{}}}default:return null}}function pe(t){let e=t.sealed;return typeof e=="string"&&e.length>0?{sealed:e}:{}}function q(t){let e=typeof t.type=="string"&&me.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 o=y(t.message);o!==void 0&&(n.message=o);let s=y(t.tool);s!==void 0&&(n.tool=s);let i=y(t.tier);i!==void 0&&(n.tier=i);let a=ye(t.usage);a&&(n.usage=a);let u=y(t.reason);u!==void 0&&(n.reason=u),typeof t.retryable=="boolean"&&(n.retryable=t.retryable);let d=t.turn&&typeof t.turn=="object"?y(t.turn.text):void 0;d!==void 0&&(n.turn={text:d});let g=y(t.session);g!==void 0&&(n.session=g);let m=y(t.toolInput);m!==void 0&&(n.toolInput=m);let f=Qe(t.git);return f&&(n.git=f),(t.state==="interrupted"||t.state==="resumed")&&(n.state=t.state),n}function Qe(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 ye(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 o=y(e.provider);return o!==void 0&&(n.provider=o),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*he(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=g=>u===void 0?g:{...g,seq:u};try{for(;;){let m=await o.read();if(m.done)break;for(i+=s.decode(m.value,{stream:!0});;){let f=i.indexOf(`
5
+ `);if(f===-1)break;let l=fe(i.slice(0,f));if(i=i.slice(f+1),r){let p=l.trim()?z(l):null;p&&(yield p);continue}if(l===""){let p=a.join(`
6
+ `);if(a=[],p==="[DONE]")return;let w=p?z(p):null;w&&(yield d(w)),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}ge(l,a)}}!r&&i&&ge(fe(i),a);let g=r?i.trim():a.join(`
7
+ `);if(g&&g!=="[DONE]"){let m=z(g);m&&(yield r?m:d(m))}}finally{o.cancel().catch(()=>{})}}function ge(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 fe(t){return t.endsWith("\r")?t.slice(0,-1):t}function Ve(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 D(t){return[...t.values()].map(e=>({name:e.name,description:e.description??"",inputSchema:e.inputSchema??{type:"object"}}))}function I(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 M(t){return t instanceof Error?t.message||t.name:typeof t=="string"?t:String(t)}var Ye=9e4,x=class{#e;#o;#r;#s=!1;#i;#t;#n=new AbortController;#a=new AbortController;#u=new Set;#c;constructor(e){this.#t=e,this.#e=e.response.headers.get("soba-run-id")??"",this.#i=e.after??0,this.#c=P(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 c({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 c({code:"canceled",message:"The run was cancelled."})),this.#a.abort(new c({code:"canceled",message:"The run was cancelled."})),this.#t.local)return this.#t.local.cancel(this.#n.signal.reason);if(this.#e)try{await T(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#l(e){let n=Date.now()+Ye,r=e;for(let o=0;Date.now()<n;o++){if(this.#n.signal.aborted)throw k(this.#n.signal.reason);o>0&&await H(Math.min(1e3*o,5e3),this.#n.signal);try{return await T(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=k(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.#e,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.#e});this.#s=!0;let e=!1;try{let n=this.#t.response;for(;;){for await(let o of he(n)){if(o.runId&&!this.#e&&(this.#e=o.runId),o.seq!==void 0&&(this.#i=o.seq),o.kind==="event"){let s=this.#t.runKey?await this.#y(o):o.event;if(!s)continue;if(s.tier&&(this.#o=s.tier),s.usage&&(this.#r=s.usage),e=J(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.#e});if(!this.resumable||!this.#e||this.#t.local)throw r;n=await this.#l(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.#c()}}#m(e){this.#u.add(e),e.finally(()=>this.#u.delete(e)).catch(()=>{})}async#y(e){let n=this.#t.runKey;if(!e.sealed)return e.event.type==="delta"||e.event.type==="thinking"?(this.#t.onWarning("Dropped unsealed text on an encrypted run.",e.event),null):e.event;try{let r=await N(n,e.sealed);if(!r||typeof r!="object")throw new Error("not an object");return q({...e.event,...r})}catch(r){return this.#t.onWarning("Dropped an event on an encrypted run that would not open.",r),null}}async#h(e){let n=this.#t.runKey;if(!n)return{value:e};let r=te(e);if(r)try{return{value:await N(n,r)}}catch{return}}async#b(e){if(!((e.kind==="tool_call"||e.kind==="approval")&&e.answered)){if(this.#t.runKey&&(e.kind==="tool_call"||e.kind==="approval")){let n=await this.#h(e.input);if(!n){this.#t.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.#e)}/approval`,{approvalId:e.approvalId,decision:"deny"});return}if(e.kind==="tool_call")return this.#g({...e,input:n.value});let{input:r,cwd:o}=n.value??{};return this.#f({...e,input:r,...typeof o=="string"&&o?{cwd:o}:{}})}if(e.kind==="tool_call")return this.#g(e);if(e.kind==="approval")return this.#f(e)}}async#g(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 i={runId:this.#e,user:this.#t.user,callId:e.callId,signal:this.#a.signal};try{r=await n.execute(e.input,i)}catch(a){r=M(a),o=!0}}if(this.#t.local){this.#t.local.deliver({callId:e.callId,result:I(r),isError:o});return}let s=I(r);await this.#p(`/runs/${encodeURIComponent(this.#e)}/tool_result`,{callId:e.callId,result:this.#t.runKey?{$sealed:await L(this.#t.runKey,s)}:s,isError:o})}async#f(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=M(o)}await this.#p(`/runs/${encodeURIComponent(this.#e)}/approval`,{approvalId:e.approvalId,decision:n,...r?{reason:r}:{},...this.#t.runKey?{sealed:await L(this.#t.runKey,{approvalId:e.approvalId,decision:n})}:{}})}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 T(this.#t.config,{method:"POST",path:e,body:n})).text()}catch(r){this.#t.onWarning(`Could not deliver an answer to ${e}.`,k(r))}}};var be="https://api.soba.so/v1",C="https://soba.so/v1",Xe=3e4,Ze=2,Q=class{#e;#o;#r;#s;#i=tt();#t;fallback;users;usage;connect;plans;runs;ops;terminals;constructor(e={}){let n=e.apiKey??W("SOBA_KEY")??W("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(et()&&!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===!1?void 0:typeof e.encrypt=="object"?e.encrypt:{},this.#e={apiKey:n,baseURL:e.baseURL??W("SOBA_BASE_URL")??be,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??Xe,maxRetries:e.maxRetries??Ze},this.#o={...this.#e,baseURL:e.webBaseURL??W("SOBA_WEB_URL")??C},typeof this.#e.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 K({http:this.#e,onWarning:this.#r,off:e.fallback===!1});this.#t=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)=>b(this.#o,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/quantity`,body:{quantity:i}}),check:(o,s,i)=>b(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)=>b({...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, and encryption is on by default. Start this one from a client made with `encrypt: false`."});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=D(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 b(this.#e,{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 g 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.#e,{method:"GET",path:`/runs/${encodeURIComponent(o)}/stream`,...s.after?{query:{after:s.after}}:{},accept:"text/event-stream",signal:s.signal});return new x({config:this.#e,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.#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 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=D(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, or send it unencrypted from a client made with `encrypt: false`.",retryable:!1});s=await Z(),r.sealed=await ee(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.#e,{method:"POST",path:"/runs",body:r,accept:"text/event-stream",signal:e.signal,retry:"unsent"})}catch(i){if(!this.#t.canServe(i,e.route))throw i;let a=this.#t.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:D(n),task:e.task},e.signal);return this.#r("Soba could not be reached; your own provider is answering this run.",i),new x({config:this.#e,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.#t.refreshSoon(),this.#t.flushSoon(),new x({config:this.#e,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 b(this.#e,{method:"GET",path:"/keys",query:{user:e},...n?{signal:n}:{}}),o=await Promise.all((Array.isArray(r.data)?r.data:[]).filter(ne).map(async a=>({...a,fingerprint:await j(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 b(this.#e,{method:e,path:n,...r})}};function W(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}function et(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}function tt(){let t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}var Y=class{#e;me;workspaces;apps;constructor(e={}){let n=e.accessToken??V("SOBA_ACCESS_TOKEN")??V("SOBA_WORKSPACE_KEY");if(!n||!/^(pat|wk)_soba_/.test(n))throw new c({code:"unauthorized",message:n?"That is not an access token. Pass a pat_soba_ token from `npx @soba-so/cli login`, or a wk_soba_ workspace key; an app's sk_soba_ key goes to `new Soba()`.":"No access token. Pass `accessToken`, or set SOBA_ACCESS_TOKEN. `npx @soba-so/cli login` makes one."});if(nt())throw new c({code:"invalid_request",message:"An access token acts as you across your workspaces. It belongs on a server or a terminal, never in a browser."});this.#e={apiKey:n,baseURL:e.baseURL??V("SOBA_WEB_URL")??C,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??3e4,maxRetries:e.maxRetries??2};let r=this.#e,o=a=>b(r,{method:"GET",path:a}),s=(a,u,d)=>b(r,{method:a,path:u,...a==="DELETE"?{}:{body:d??{}},retry:"unsent"}),i=a=>`/apps/${encodeURIComponent(a)}`;this.me=()=>o("/me"),this.workspaces={list:async()=>(await o("/workspaces")).data,createKey:(a,u={})=>s("POST",`/workspaces/${encodeURIComponent(a)}/keys`,u.name?{name:u.name}:{})},this.apps={list:async({workspace:a})=>(await o(`/workspaces/${encodeURIComponent(a)}/apps`)).data,get:a=>o(i(a)),create:({workspace:a,name:u})=>s("POST",`/workspaces/${encodeURIComponent(a)}/apps`,{name:u}),update:(a,{name:u})=>s("PATCH",i(a),{name:u}),delete:a=>s("DELETE",i(a)),keys:{list:async a=>(await o(`${i(a)}/keys`)).data,create:(a,u={})=>s("POST",`${i(a)}/keys`,{environment:u.environment??"production",...u.name?{name:u.name}:{},...u.replaceIdle?{replace_idle:!0}:{}}),revoke:(a,u)=>s("DELETE",`${i(a)}/keys/${encodeURIComponent(u)}`)}}}};function V(t){return typeof process<"u"?process.env?.[t]:void 0}function nt(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}var rt=300;function ot(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function st(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 it(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??rt))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"]),g=ot(await globalThis.crypto.subtle.sign("HMAC",d,new TextEncoder().encode(`${s}.${t}`)));if(!st(g,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 f=m;if(f.type!=="run.event"&&f.type!=="run.tool_call"||typeof f.run_id!="string")throw new c({code:"invalid_request",message:"Not a Soba run delivery."});return f}async function at(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:I(i)}}catch(i){return{result:M(i),is_error:!0}}}var X=class{#e;apps;constructor(e={}){let n=e.apiKey??we("SOBA_WORKSPACE_KEY");if(!n?.startsWith("wk_soba_"))throw new c({code:"unauthorized",message:n?"That is not a workspace key. Workspace keys are shaped wk_soba_<id>.<secret>; an app's sk_soba_ key goes to `new Soba()`.":"No workspace key. Pass `apiKey`, or set SOBA_WORKSPACE_KEY. Get one with `npx @soba-so/cli login --workspace-key`."});if(ut())throw new c({code:"invalid_request",message:"A workspace key makes apps and mints their keys. It belongs on a server, never in a browser."});this.#e={apiKey:n,baseURL:e.baseURL??we("SOBA_WEB_URL")??C,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??3e4,maxRetries:e.maxRetries??2};let r=this.#e;this.apps={list:async()=>(await b(r,{method:"GET",path:"/workspace/apps"})).data,create:({name:o})=>b(r,{method:"POST",path:"/workspace/apps",body:{name:o},retry:"unsent"}),keys:o=>b(r,{method:"POST",path:`/workspace/apps/${encodeURIComponent(o)}/keys`,body:{},retry:"unsent"})}}};function we(t){return typeof process<"u"?process.env?.[t]:void 0}function ut(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}export{be as DEFAULT_BASE_URL,C as DEFAULT_WEB_BASE_URL,de as METERED_CLASSES,x as Run,Q as Soba,c as SobaError,Y as SobaManagement,X as SobaWorkspace,ze as TOOL_SLUGS,B as VERSION,j as fingerprint,at as handleRunWebhook,Je as isCostClass,He as isMetered,J as isTerminal,Ve as tool,it as verifyWebhook};
@@ -0,0 +1,136 @@
1
+ /**
2
+ * SOBA ITSELF, MANAGED FROM CODE: workspaces, apps and their keys — the way
3
+ * the Supabase and Railway management APIs work.
4
+ *
5
+ * ```js
6
+ * const soba = new SobaManagement({ accessToken: process.env.SOBA_ACCESS_TOKEN })
7
+ *
8
+ * const [workspace] = await soba.workspaces.list()
9
+ * const app = await soba.apps.create({ workspace: workspace.id, name: "Study planner" })
10
+ * const { key } = await soba.apps.keys.create(app.id, { environment: "production" })
11
+ * ```
12
+ *
13
+ * TWO CREDENTIALS, ONE CLIENT:
14
+ *
15
+ * pat_soba_… YOU, from `npx @soba-so/cli login` (read from
16
+ * ~/.soba/config.json by the CLI; pass it here yourself). Acts
17
+ * with exactly what you may do in each workspace.
18
+ * wk_soba_… ONE WORKSPACE, from `soba login --workspace-key`. For a server
19
+ * that makes apps: everything here except deleting an app.
20
+ *
21
+ * Neither runs anything, and an app's `sk_soba_` key is refused before a
22
+ * request is sent: that one goes to `new Soba()`.
23
+ */
24
+ export interface SobaManagementOptions {
25
+ /** `pat_soba_…` or `wk_soba_…`. Defaults to SOBA_ACCESS_TOKEN, then SOBA_WORKSPACE_KEY. */
26
+ accessToken?: string;
27
+ /** Defaults to SOBA_WEB_URL, then https://soba.so/v1. */
28
+ baseURL?: string;
29
+ fetch?: typeof globalThis.fetch;
30
+ headers?: Record<string, string>;
31
+ connectTimeoutMs?: number;
32
+ maxRetries?: number;
33
+ }
34
+ export interface Workspace {
35
+ id: string;
36
+ name: string;
37
+ slug: string;
38
+ /** False while the workspace is still being set up in the dashboard. */
39
+ ready: boolean;
40
+ can: {
41
+ create_apps: boolean;
42
+ manage_keys: boolean;
43
+ };
44
+ }
45
+ export interface ManagedApp {
46
+ id: string;
47
+ name: string;
48
+ slug: string;
49
+ workspace_id: string;
50
+ created_at: string;
51
+ }
52
+ export interface ManagedKey {
53
+ id: string;
54
+ kind: "secret" | "publishable" | "management";
55
+ name: string;
56
+ environment: "development" | "production";
57
+ /** Enough to tell keys apart. Never the secret. */
58
+ preview: string;
59
+ created_at: string;
60
+ last_used_at: string | null;
61
+ }
62
+ export interface MintedKey {
63
+ id: string;
64
+ /** The secret. Shown once: store it now. */
65
+ key: string;
66
+ preview: string;
67
+ environment: "development" | "production";
68
+ }
69
+ export type Me = {
70
+ kind: "person";
71
+ user_id: string;
72
+ email: string | null;
73
+ } | {
74
+ kind: "workspace";
75
+ workspace_id: string;
76
+ };
77
+ export declare class SobaManagement {
78
+ #private;
79
+ /** Who this credential acts as. */
80
+ readonly me: () => Promise<Me>;
81
+ readonly workspaces: {
82
+ /** Every workspace you can reach, and what you may do in each. */
83
+ list(): Promise<Workspace[]>;
84
+ /**
85
+ * Mint a workspace key (`wk_soba_…`) for a server that makes apps. Needs a
86
+ * person's token holding app and key management there. Shown once.
87
+ */
88
+ createKey(workspaceId: string, params?: {
89
+ name?: string;
90
+ }): Promise<{
91
+ id: string;
92
+ key: string;
93
+ workspace_id: string;
94
+ }>;
95
+ };
96
+ readonly apps: {
97
+ /** A workspace's apps, oldest first. */
98
+ list(params: {
99
+ workspace: string;
100
+ }): Promise<ManagedApp[]>;
101
+ get(appId: string): Promise<ManagedApp>;
102
+ /** Counts against the workspace tier's app limit. */
103
+ create(params: {
104
+ workspace: string;
105
+ name: string;
106
+ }): Promise<ManagedApp>;
107
+ update(appId: string, params: {
108
+ name: string;
109
+ }): Promise<ManagedApp>;
110
+ /**
111
+ * Delete the app and everything that is its: users, machines, runs, usage,
112
+ * plans and keys. Needs a person's token; a workspace's only app cannot go.
113
+ */
114
+ delete(appId: string): Promise<{
115
+ id: string;
116
+ deleted: true;
117
+ }>;
118
+ keys: {
119
+ list(appId: string): Promise<ManagedKey[]>;
120
+ /**
121
+ * Mint a secret key. Refused while a never-used one exists for that
122
+ * environment, unless `replaceIdle` revokes it first.
123
+ */
124
+ create(appId: string, params?: {
125
+ environment?: "development" | "production";
126
+ name?: string;
127
+ replaceIdle?: boolean;
128
+ }): Promise<MintedKey>;
129
+ revoke(appId: string, keyId: string): Promise<{
130
+ id: string;
131
+ revoked: true;
132
+ }>;
133
+ };
134
+ };
135
+ constructor(options?: SobaManagementOptions);
136
+ }
@@ -229,6 +229,24 @@ export interface RuntimeListItem {
229
229
  /** A runtime that appeared after pairing, waiting to be approved. */
230
230
  quarantined: boolean;
231
231
  first_seen_at: string;
232
+ /**
233
+ * How much of the signed-in plan is left — the five hours, the week, a
234
+ * model's own week. Null with no reading or on a login with no plan limits
235
+ * (an API key); absent from an older gateway. `used_percent` is 0–100.
236
+ */
237
+ limits?: PlanLimitsWire | null;
238
+ }
239
+ /** A runtime's plan limits, window by window, as its machine last read them. */
240
+ export interface PlanLimitsWire {
241
+ checked_at: string;
242
+ windows: {
243
+ id: string;
244
+ kind: "session" | "weekly" | "monthly" | "other";
245
+ label: string;
246
+ used_percent: number;
247
+ resets_at: string | null;
248
+ window_mins: number | null;
249
+ }[];
232
250
  }
233
251
  /** The same three values `<ComputeStatus />` renders. Narrow rather than
234
252
  * `string`, so a server can hand the list straight to the component without a
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.0.17";
1
+ export declare const VERSION = "0.0.19";
@@ -48,6 +48,12 @@ export interface AppKeys {
48
48
  production: string;
49
49
  };
50
50
  }
51
+ /**
52
+ * @deprecated Use `SobaManagement`, which takes the same `wk_soba_` key and
53
+ * does everything this does, with workspaces and key management besides:
54
+ * `apps.list({ workspace })`, `apps.create({ workspace, name })` and
55
+ * `apps.keys.create(appId, { environment })`. This keeps working.
56
+ */
51
57
  export declare class SobaWorkspace {
52
58
  #private;
53
59
  readonly apps: {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soba-so/sdk",
3
- "version": "0.0.17",
3
+ "version": "0.0.19",
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",