@soba-so/sdk 0.0.20 → 0.0.21
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 +12 -18
- package/dist/e2e.d.ts +8 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.mjs +8 -6
- package/dist/respond.d.ts +13 -0
- package/dist/run.d.ts +8 -0
- package/dist/version.d.ts +1 -1
- package/dist/webhooks.d.ts +13 -1
- package/package.json +1 -1
package/dist/client.d.ts
CHANGED
|
@@ -168,7 +168,7 @@ export interface RunParams {
|
|
|
168
168
|
/**
|
|
169
169
|
* Keep the run going if this request goes away, and keep its frames so it
|
|
170
170
|
* can be read again: `soba.runs.attach(run.runId, { user, tools, after:
|
|
171
|
-
* run.cursor })`. For a run that may outlast the function serving it — a
|
|
171
|
+
* run.cursor, key: run.key })`. For a run that may outlast the function serving it — a
|
|
172
172
|
* serverless time limit, a deploy — without a webhook, so the same code works
|
|
173
173
|
* on localhost. A run nobody attaches to again for fifteen minutes is
|
|
174
174
|
* stopped. https://soba.so/docs/runs#runs-that-outlive-the-request
|
|
@@ -190,6 +190,8 @@ export interface StartedRun {
|
|
|
190
190
|
token: string;
|
|
191
191
|
expiresAt: number;
|
|
192
192
|
};
|
|
193
|
+
/** On an encrypted run: what `soba.runs.attach` needs. See `Run.key`. */
|
|
194
|
+
key?: string;
|
|
193
195
|
/** With `answerTools: "here"`: settles when the run ends, after its last tool call is answered. */
|
|
194
196
|
answered?: Promise<void>;
|
|
195
197
|
}
|
|
@@ -202,6 +204,8 @@ export interface AttachParams {
|
|
|
202
204
|
approve?: Approver;
|
|
203
205
|
/** The last frame already read (`run.cursor`). Omitted reads from the start. */
|
|
204
206
|
after?: number;
|
|
207
|
+
/** `run.key`, when this is not the process that started the run. */
|
|
208
|
+
key?: string;
|
|
205
209
|
signal?: AbortSignal;
|
|
206
210
|
}
|
|
207
211
|
/**
|
|
@@ -215,7 +219,7 @@ export interface AttachParams {
|
|
|
215
219
|
* anywhere and the app reads it with `soba.runs.attach(id, …)` — no public URL,
|
|
216
220
|
* no tunnel on a laptop.
|
|
217
221
|
*/
|
|
218
|
-
export type OpKind = "git.snapshot" | "git.diff" | "git.push" | "git.update" | "git.worktree.add" | "git.worktree.remove" | "fs.list" | "fs.read" | "fs.write" | "fs.attach" | "git.mark" | "fs.copy" | "term.mode.get" | "term.mode.set" | "sessions.list" | "sessions.read" | "sessions.adopt";
|
|
222
|
+
export type OpKind = "git.snapshot" | "git.diff" | "git.push" | "git.update" | "git.worktree.add" | "git.worktree.remove" | "fs.list" | "fs.read" | "fs.write" | "fs.attach" | "git.mark" | "fs.copy" | "term.mode.get" | "term.mode.set" | "sessions.list" | "sessions.read" | "sessions.adopt" | "agent.open" | "editor.open" | "project.state" | "chat.latest" | "preview.send";
|
|
219
223
|
export interface OpParams {
|
|
220
224
|
/** Whose machine. Resolve it on your server, never from the browser. */
|
|
221
225
|
user: string;
|
|
@@ -252,6 +256,12 @@ export interface OpParams {
|
|
|
252
256
|
* worktree's chat with that session id was carried on from.
|
|
253
257
|
*/
|
|
254
258
|
runtime?: "claude-code" | "codex";
|
|
259
|
+
/** `editor.open`: which editor. */
|
|
260
|
+
editor?: "cursor";
|
|
261
|
+
/** `chat.latest`: only a conversation active after this time, in ms. */
|
|
262
|
+
since?: number;
|
|
263
|
+
/** `preview.send`: Soba hosting's upload address. */
|
|
264
|
+
url?: string;
|
|
255
265
|
session?: string;
|
|
256
266
|
}
|
|
257
267
|
/** The machine's answer. A refusal is an answer: `ok: false` with its reason. */
|
|
@@ -316,22 +326,6 @@ export interface DetachedRunParams extends Omit<RunParams, "approve" | "signal"
|
|
|
316
326
|
/** Continue the conversation a previous run reported as its `session`. */
|
|
317
327
|
resume?: string;
|
|
318
328
|
}
|
|
319
|
-
/**
|
|
320
|
-
* The Soba client.
|
|
321
|
-
*
|
|
322
|
-
* ```js
|
|
323
|
-
* const soba = new Soba({ apiKey: process.env.SOBA_KEY })
|
|
324
|
-
* const user = sobaUserId(session.user.username) // see @soba-so/sdk/identity
|
|
325
|
-
* const run = await soba.run({ user, prompt: "…" })
|
|
326
|
-
* for await (const event of run) …
|
|
327
|
-
* ```
|
|
328
|
-
*
|
|
329
|
-
* `soba.run()` exists alongside `chat/completions` for one reason:
|
|
330
|
-
* `chat/completions` is stateless and the CALLER owns the agent loop, so it
|
|
331
|
-
* reaches models. Claude Code and Codex run their own loop and never hand a
|
|
332
|
-
* tool call back to wait on an HTTP round trip, so reaching them means SOBA
|
|
333
|
-
* owns the loop, and that is this call.
|
|
334
|
-
*/
|
|
335
329
|
export declare class Soba {
|
|
336
330
|
#private;
|
|
337
331
|
readonly fallback: FallbackControl;
|
package/dist/e2e.d.ts
CHANGED
|
@@ -45,6 +45,14 @@ export interface RunKey {
|
|
|
45
45
|
key: CryptoKey;
|
|
46
46
|
}
|
|
47
47
|
export declare function newRunKey(): Promise<RunKey>;
|
|
48
|
+
/**
|
|
49
|
+
* A RUN'S KEY, SAFE TO KEEP ANYWHERE: a browser, a database, a queue. Opening it
|
|
50
|
+
* takes the app's API key, and this text is never sent to Soba, which is why
|
|
51
|
+
* Soba seeing that API key on each request does not let it read a run.
|
|
52
|
+
*/
|
|
53
|
+
export declare function wrapRunKey(runKey: RunKey, apiKey: string): Promise<string>;
|
|
54
|
+
/** Throws if it was wrapped with another API key, or altered. */
|
|
55
|
+
export declare function unwrapRunKey(text: string, apiKey: string): Promise<RunKey>;
|
|
48
56
|
/** Seal `payload` so that only the machines in `recipients` can open it. */
|
|
49
57
|
export declare function sealRequest(runKey: RunKey, payload: Record<string, unknown>, recipients: MachineKey[]): Promise<SealedRequest>;
|
|
50
58
|
/** One frame from the app to the machine: a tool result. */
|
package/dist/index.d.ts
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
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 { runResponse } from "./respond.js";
|
|
4
5
|
export { type ManagedApp, type ManagedKey, type Me, type MintedKey, SobaManagement, type SobaManagementOptions, type Workspace, } from "./management.js";
|
|
5
6
|
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";
|
|
6
7
|
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";
|
|
7
8
|
export { type ApprovalDecision, type ApprovalRequest, type Approver, Run, } from "./run.js";
|
|
8
9
|
export { type ToolContext, type ToolDefinition, tool } from "./tools.js";
|
|
9
10
|
export { VERSION } from "./version.js";
|
|
10
|
-
export { handleRunWebhook, type RunWebhookEvent, type ToolCallAnswer, verifyWebhook, } from "./webhooks.js";
|
|
11
|
+
export { handleRunWebhook, type RunWebhookEvent, type ToolCallAnswer, verifyWebhook, openRunWebhook, type SealedRunOptions, } from "./webhooks.js";
|
|
11
12
|
export { type AppKeys, type CreatedApp, SobaWorkspace, type SobaWorkspaceOptions, type WorkspaceApp, } from "./workspace.js";
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
|
-
var
|
|
1
|
+
var xe="soba-e2e-wrap-v1",Ee="soba-e2e-request-v1",D="e1.",T=new TextEncoder,Ce=new TextDecoder;async function re(){let t=crypto.getRandomValues(new Uint8Array(32));return{raw:t,key:await ae(t)}}var G="sobarunkey1.";async function oe(t){let e=await crypto.subtle.importKey("raw",T.encode(t),"HKDF",!1,["deriveKey"]);return crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:new Uint8Array(32),info:T.encode("soba-e2e-run-key-wrap")},e,{name:"AES-GCM",length:256},!1,["encrypt","decrypt"])}async function H(t,e){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:n},await oe(e),t.raw));return`${G}${S(n)}.${S(r)}`}async function W(t,e){if(!t.startsWith(G))throw new Error("not a run key");let[n,r]=t.slice(G.length).split(".");if(!n||!r)throw new Error("not a run key");let o=new Uint8Array(await crypto.subtle.decrypt({name:"AES-GCM",iv:E(n)},await oe(e),E(r)));return{raw:o,key:await ae(o)}}async function se(t,e,n){let r=await Promise.all(n.map(async({publicKey:i})=>{let a=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),u=S(new Uint8Array(await crypto.subtle.exportKey("raw",a.publicKey))),p=await crypto.subtle.importKey("raw",E(i),{name:"X25519"},!1,[]),d=await crypto.subtle.deriveBits({name:"X25519",public:p},a.privateKey,256),f=await crypto.subtle.importKey("raw",d,"HKDF",!1,["deriveKey"]),m=await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:T.encode(`${u}.${i}`),info:T.encode(xe)},f,{name:"AES-GCM",length:256},!1,["encrypt"]),l=crypto.getRandomValues(new Uint8Array(12)),g=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:l},m,t.raw));return{kid:i,epk:u,iv:S(l),ct:S(g)}})),o=crypto.getRandomValues(new Uint8Array(12)),s=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:T.encode(Ee)},t.key,T.encode(JSON.stringify(e))));return{v:1,keys:r,iv:S(o),ct:S(s)}}async function I(t,e){let n=crypto.getRandomValues(new Uint8Array(12)),r=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:n,additionalData:T.encode("soba-e2e-down")},t.key,T.encode(JSON.stringify(e===void 0?null:e))));return`${D}${S(n)}.${S(r)}`}async function C(t,e){if(!e.startsWith(D))throw new Error("not a sealed frame");let[n,r]=e.slice(D.length).split(".");if(!n||!r)throw new Error("not a sealed frame");let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:E(n),additionalData:T.encode("soba-e2e-up")},t.key,E(r));return JSON.parse(Ce.decode(o))}function O(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t.$sealed;return typeof e=="string"&&e.startsWith(D)?e:void 0}async function J(t){let n=[...new Uint8Array(await crypto.subtle.digest("SHA-256",E(t))).subarray(0,16)].map(r=>r.toString(16).padStart(2,"0")).join("");return n.match(/.{4}/g)?.join(" ")??n}function ie(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 ae(t){return crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}function S(t){let e="";for(let n of t)e+=String.fromCharCode(n);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function E(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??Pe.has(e.code),this.retryAfterMs=e.retryAfterMs,this.runId=e.runId}},Pe=new Set(["rate_limited","server_error","connection","timeout","stream_truncated"]),Ke={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=Ke[t];return e||(t>=500?"server_error":t>=400?"invalid_request":"unknown")}var ue=new WeakSet;function ce(t){return ue.has(t)}async function le(t){let e=t.status,n="";try{n=await t.text()}catch{}let r=Oe(n),o=new c({code:r?.code??Ie(e),type:r?.type,message:r?.message??Ue(e,t.statusText,n),status:e,retryAfterMs:qe(t.headers.get("retry-after")),runId:t.headers.get("soba-run-id")??void 0});return!r&&(e===502||e===503||e===504)&&ue.add(o),o}function Oe(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:Me.has(r.code)?r.code:void 0}}var Me=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 Ue(t,e,n){let r=n.trim().slice(0,200),o=r?`: ${r}`:"";return`Soba returned ${t}${e?` ${e}`:""}${o}`}function qe(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 z="0.0.21";var De=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]);function Y(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 We=8e3,$e=3e4;async function A(t,e){let n=Ne(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"||Y(i));for(let i=0;i<r;i++){i>0&&await V(je(i,o),e.signal);let a=new AbortController,u=M(e.signal,a),p=setTimeout(()=>{a.abort(new c({code:"timeout",message:`Soba did not answer within ${t.connectTimeoutMs}ms.`}))},t.connectTimeoutMs),d;try{d=await t.fetch(n,{method:e.method,headers:Fe(t,e),body:e.body===void 0?void 0:JSON.stringify(e.body),signal:a.signal})}catch(f){if(u(),o=k(a.signal.aborted?a.signal.reason??f:f),!s(o)||i===r-1)throw o;continue}finally{clearTimeout(p)}if(d.ok)return d;if(u(),o=await le(d),!s(o)||i===r-1)throw o}throw o??new c({code:"unknown",message:"The request failed with no error."})}async function w(t,e){let n=await A(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 Fe(t,e){let n={authorization:`Bearer ${t.apiKey}`,accept:e.accept??"application/json","user-agent":Le(),...t.headers};return e.body!==void 0&&(n["content-type"]="application/json"),n}function Le(){let t=typeof process>"u"?"":` node/${process.versions?.node??"?"}`;return`soba-sdk/${z}${t}`}function Ne(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 je(t,e){if(e?.retryAfterMs!==void 0)return Math.min(e.retryAfterMs,$e);let n=Math.min(We,500*2**(t-1));return Math.round(n*(.5+Math.random()/2))}function V(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 M(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 Be=5*60*1e3,de=25,Ge=1e3,He=100,$=class{#t;#s;#r;#o=null;#i=0;#a=null;#e=[];#n=null;constructor(e){this.#t=e.http,this.#s=e.onWarning,this.#r=e.off}async prime(){if(!this.#r)return this.#a??=w(this.#t,{method:"GET",path:"/fallback",retry:!1}).then(e=>{this.#o={enabled:e?.enabled===!0,providers:(e?.providers??[]).map(pe).filter(ge)},this.#i=Date.now()}).catch(()=>{}).finally(()=>{this.#a=null}),this.#a}refreshSoon(){this.#r||Date.now()-this.#i<Be||this.prime()}get pending(){return this.#e.length}canServe(e,n){if(this.#r)return!1;let r=k(e);return!Y(r)&&!ce(r)||r.code==="rate_limited"?!1:this.#l(n).length>0}serve(e,n){let r=new AbortController,o=M(n,r),s=r.signal,i=new Map,a=new Map,u=l=>{let g=i.get(l.callId);g?(i.delete(l.callId),g(l)):a.set(l.callId,l)},p=l=>new Promise((g,b)=>{let h=a.get(l);if(h)return a.delete(l),g(h);i.set(l,g),s.addEventListener("abort",()=>b(k(s.reason)),{once:!0})}),d=this.#l(e.route),f=new TextEncoder,m=new ReadableStream({start:l=>{let g=b=>{try{l.enqueue(f.encode(`data: ${JSON.stringify(b)}
|
|
2
2
|
|
|
3
|
-
`))}catch{}};this.#d(e,g,p,
|
|
4
|
-
`);if(l===-1)break;let
|
|
5
|
-
`);if(
|
|
6
|
-
`);if(a=[],
|
|
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 O(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 ye(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 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#y(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.#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.#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=O(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=O(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),o.effort&&(i.effort=o.effort);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),e.effort&&(r.effort=e.effort),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:O(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};
|
|
3
|
+
`))}catch{}};this.#d(e,d,g,p,s).catch(b=>g({type:"error",message:k(b).message})).finally(()=>{o();try{l.close()}catch{}})},cancel:l=>r.abort(l)});return{response:new Response(m,{status:200,headers:{"content-type":"text/event-stream","soba-run-id":e.runId}}),deliver:u,stop:l=>r.abort(l)}}async flush(){return this.#n??=this.#u().finally(()=>{this.#n=null}),this.#n}flushSoon(){this.#e.length&&this.flush()}async#u(){for(;this.#e.length;){let e=this.#e.slice(0,He),n;try{n=(await w(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.#s("Soba would not record a run served while it was unreachable.",s);if(this.#e=[...e.filter(s=>r.has(s.id)),...this.#e.filter(s=>!o.has(s.id))],r.size===e.length)return}}#c(e){this.#e.push(e),this.#e.length>Ge&&(this.#e.shift(),this.#s("Dropped the oldest unreported fallback run: too many waiting for Soba."))}#l(e){let n=this.#o??Je();return n?.enabled?n.providers.filter(r=>fe(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 p=ze(u,e.model),d={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},f=!1,m=(l,g)=>this.#c({id:e.runId,user:e.user,supplier:u.id,model:p.model,input_tokens:d.inputTokens,output_tokens:d.outputTokens,cache_read_tokens:d.cacheReadTokens,cache_write_tokens:d.cacheWriteTokens,started_at:i.toISOString(),ended_at:new Date().toISOString(),status:l,...g?{error:g}:{},...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=Ye(e);for(let b=0;;b++){if(b>=de)throw new Error(`Stopped after ${de} turns of tool calls.`);let h=await Ve(this.#t.fetch,u,p,l,e.tools,s,v=>{f=!0,r({type:"delta",text:v})});if(d.inputTokens+=h.inputTokens,d.outputTokens+=h.outputTokens,d.cacheReadTokens+=h.cacheReadTokens,!h.toolCalls.length)break;f=!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:Qe(v.function.arguments)});for(let v of h.toolCalls){let R=await o(v.id);l.push({role:"tool",tool_call_id:v.id,content:typeof R.result=="string"?R.result:JSON.stringify(R.result)})}}let g={model:p.model,provider:u.id,costClass:u.costClass,...d,webSearches:0};r({type:"usage",usage:g}),r({type:"done",usage:g}),m("done");return}catch(l){if(s.aborted)throw m("error","cancelled"),k(s.reason);if(a=`${u.name}: ${k(l).message}`,f)throw m("error",a),new c({code:"run_failed",message:a,retryable:!1})}}throw new c({code:"no_compute",message:a,retryable:!1})}};function pe(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 ge=t=>t!==null;function Je(){let t=me("SOBA_FALLBACK");if(!t)return null;try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),r=(JSON.parse(e).providers??[]).map(pe).filter(ge);return r.length?{enabled:!0,providers:r}:null}catch{return null}}function fe(t){return me(t.keyEnv)??t.apiKey}function ze(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 Ye(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 Ve(t,e,n,r,o,s,i){let a=await t(`${e.baseUrl.replace(/\/+$/,"")}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${fe(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(m=>({type:"function",function:{name:m.name,description:m.description,parameters:m.inputSchema}}))}:{}}),signal:s});if(!a.ok||!a.body){let m=await a.text().catch(()=>"");throw new Error(`${a.status} ${m.slice(0,300)}`.trim())}let u={text:"",toolCalls:[],inputTokens:0,outputTokens:0,cacheReadTokens:0},p=a.body.getReader(),d=new TextDecoder,f="";try{for(;;){let m=await p.read();if(m.done)break;for(f+=d.decode(m.value,{stream:!0});;){let l=f.indexOf(`
|
|
4
|
+
`);if(l===-1)break;let g=f.slice(0,l).trim();if(f=f.slice(l+1),!g.startsWith("data:"))continue;let b=g.slice(5).trim();if(!b||b==="[DONE]")continue;let h;try{h=JSON.parse(b)}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 R of v?.tool_calls??[]){let j=R.index??u.toolCalls.length;u.toolCalls[j]??={id:R.id??`call_${j}`,type:"function",function:{name:"",arguments:""}};let B=u.toolCalls[j];R.id&&(B.id=R.id),R.function?.name&&(B.function.name+=R.function.name),R.function?.arguments&&(B.function.arguments+=R.function.arguments)}}}}finally{p.cancel().catch(()=>{})}return u.toolCalls=u.toolCalls.filter(m=>m?.function.name),u}function Qe(t){if(!t)return{};try{return JSON.parse(t)}catch{return{}}}function me(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}var ye=["open-weights","frontier"];function Xe(t){return ye.includes(t)}function Ze(t){return t==="user-hardware"||t==="user-subscription"||t==="user-api-key"||t==="open-weights"||t==="frontier"}function Q(t){return t.type==="done"||t.type==="error"}var et=["search","fetch","read","write","edit","bash","files","agent","todo","think","sources","tool"];var ke=new Set(["delta","thinking","status","done","error"]);function X(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"&&ke.has(n.type)){let o=F(n);return o?{kind:"event",runId:r,event:o,...he(n)}:null}switch(n.type){case"event":{if(!n.event||typeof n.event!="object")return null;let o=F(n.event);return o?{kind:"event",runId:r,event:o,...he(n.event)}:null}case"usage":{let o=ve(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 he(t){let e=t.sealed;return typeof e=="string"&&e.length>0?{sealed:e}:{}}function F(t){let e=typeof t.type=="string"&&ke.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=ve(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 p=t.turn&&typeof t.turn=="object"?y(t.turn.text):void 0;p!==void 0&&(n.turn={text:p});let d=y(t.session);d!==void 0&&(n.session=d);let f=y(t.toolInput);f!==void 0&&(n.toolInput=f);let m=y(t.toolOutput);m!==void 0&&(n.toolOutput=m);let l=tt(t.git);return l&&(n.git=l),(t.state==="interrupted"||t.state==="resumed")&&(n.state=t.state),n}function tt(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:_(e.ahead),behind:_(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.added),removed:_(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 ve(t){if(!t||typeof t!="object")return null;let e=t,n={model:y(e.model)??"unknown",inputTokens:_(e.inputTokens),outputTokens:_(e.outputTokens),cacheReadTokens:_(e.cacheReadTokens),cacheWriteTokens:_(e.cacheWriteTokens),webSearches:_(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 _(t){return typeof t=="number"&&Number.isFinite(t)?t:0}async function*Re(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,p=d=>u===void 0?d:{...d,seq:u};try{for(;;){let f=await o.read();if(f.done)break;for(i+=s.decode(f.value,{stream:!0});;){let m=i.indexOf(`
|
|
5
|
+
`);if(m===-1)break;let l=be(i.slice(0,m));if(i=i.slice(m+1),r){let g=l.trim()?X(l):null;g&&(yield g);continue}if(l===""){let g=a.join(`
|
|
6
|
+
`);if(a=[],g==="[DONE]")return;let b=g?X(g):null;b&&(yield p(b)),u=void 0;continue}if(l.startsWith("id:")){let g=Number(l.slice(3).trim());u=Number.isInteger(g)&&g>0?g:void 0;continue}we(l,a)}}!r&&i&&we(be(i),a);let d=r?i.trim():a.join(`
|
|
7
|
+
`);if(d&&d!=="[DONE]"){let f=X(d);f&&(yield r?f:p(f))}}finally{o.cancel().catch(()=>{})}}function we(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 be(t){return t.endsWith("\r")?t.slice(0,-1):t}function nt(t){return t}function P(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 L(t){return[...t.values()].map(e=>({name:e.name,description:e.description??"",inputSchema:e.inputSchema??{type:"object"}}))}function U(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 q(t){return t instanceof Error?t.message||t.name:typeof t=="string"?t:String(t)}var rt=9e4,x=class{#t;#s;#r;#o=!1;#i=!1;#a;#e;#n=new AbortController;#u=new AbortController;#c=new Set;#l;constructor(e){this.#e=e,this.#t=e.response.headers.get("soba-run-id")??"",this.#a=e.after??0,this.#l=M(e.signal,this.#n)}get cursor(){return this.#a}get key(){return this.#e.key}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.#s}get usage(){return this.#r}[Symbol.asyncIterator](){return this.#m()}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.#u.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 A(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#d(e){let n=Date.now()+rt,r=e;for(let o=0;Date.now()<n;o++){if(this.#n.signal.aborted)throw k(this.#n.signal.reason);o>0&&await V(Math.min(1e3*o,5e3),this.#n.signal);try{return await A(this.#e.config,{method:"GET",path:`/runs/${encodeURIComponent(this.#t)}/stream`,query:{after:this.#a},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.#t,cause:r})}async*#m(){if(this.#o)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.#o=!0;let e=!1;try{let n=this.#e.response;for(;;){for await(let o of Re(n)){if(o.runId&&!this.#t&&(this.#t=o.runId),o.seq!==void 0&&(this.#a=o.seq),o.kind==="event"){o.sealed&&!this.#e.runKey&&!this.#i&&(this.#i=!0,this.#e.onWarning("This run is end-to-end encrypted, so its content cannot be read here. Keep `run.key` and pass it to `soba.runs.attach`."));let s=this.#e.runKey?await this.#h(o):o.event;if(!s)continue;if(s.tier&&(this.#s=s.tier),s.usage&&(this.#r=s.usage),e=Q(s),yield s,e)return;continue}if(o.kind==="usage"){this.#r=o.usage;continue}this.#y(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.#d(r)}}finally{e||this.#u.abort(new c({code:"canceled",message:"The run ended before this tool finished."})),await Promise.allSettled([...this.#c]),this.#n.abort(),this.#l()}}#y(e){this.#c.add(e),e.finally(()=>this.#c.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 C(n,e.sealed);if(!r||typeof r!="object")throw new Error("not an object");return F({...e.event,...r})}catch(r){return this.#e.onWarning("Dropped an event on an encrypted run that would not open.",r),null}}async#w(e){let n=this.#e.runKey;if(!n)return{value:e};let r=O(e);if(r)try{return{value:await C(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.#w(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.#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.#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.#u.signal};try{r=await n.execute(e.input,i)}catch(a){r=q(a),o=!0}}if(this.#e.local){this.#e.local.deliver({callId:e.callId,result:U(r),isError:o});return}let s=U(r);await this.#p(`/runs/${encodeURIComponent(this.#t)}/tool_result`,{callId:e.callId,result:this.#e.runKey?{$sealed:await I(this.#e.runKey,s)}:s,isError:o})}async#f(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=q(o)}await this.#p(`/runs/${encodeURIComponent(this.#t)}/approval`,{approvalId:e.approvalId,decision:n,...r?{reason:r}:{},...this.#e.runKey?{sealed:await I(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 A(this.#e.config,{method:"POST",path:e,body:n})).text()}catch(r){this.#e.onWarning(`Could not deliver an answer to ${e}.`,k(r))}}};var Se="https://api.soba.so/v1",K="https://soba.so/v1",ot=3e4,st=2,it=256,Z=class{#t;#s=new Map;#r;#o;#i;#a=ut();#e;fallback;users;usage;connect;plans;runs;ops;terminals;constructor(e={}){let n=e.apiKey??N("SOBA_KEY")??N("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(at()&&!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.#o=e.onWarning??(()=>{}),this.#i=e.encrypt===!1?void 0:typeof e.encrypt=="object"?e.encrypt:{},this.#t={apiKey:n,baseURL:e.baseURL??N("SOBA_BASE_URL")??Se,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??ot,maxRetries:e.maxRetries??st},this.#r={...this.#t,baseURL:e.webBaseURL??N("SOBA_WEB_URL")??K},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 $({http:this.#t,onWarning:this.#o,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)=>w(this.#r,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/quantity`,body:{quantity:i}}),check:(o,s,i)=>w(i?.use?{...this.#r,maxRetries:0}:this.#r,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/check`,body:i?.use?{use:i.use}:{}}),track:(o,s,i=1)=>w({...this.#r,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.#i&&o.surface==="terminal")throw new c({code:"invalid_request",message:"Terminal sessions 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=P(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=L(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),o.effort&&(i.effort=o.effort);let a=this.#i?await this.#n(i,o.user):void 0,u=await w(this.#t,{method:"POST",path:"/runs",body:i,retry:"unsent"}),p={id:u.id};return a&&(this.#u(u.id,a),p.key=await H(a,this.#t.apiKey)),u.stream&&(p.stream={url:u.stream.url,token:u.stream.token,expiresAt:u.stream.expires_at}),o.answerTools==="here"&&(p.answered=(async()=>{let d=await this.runs.attach(u.id,{user:o.user,tools:o.tools??[]});for await(let f of d);})().catch(d=>this.#o("Answering this run's tool calls stopped.",d))),p},attach:async(o,s)=>{if(!s.user)throw new c({code:"user_required",status:422,message:"`user` is required."});let i=s.key?await this.#c(s.key,o):this.#s.get(o),a=await A(this.#t,{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.#t,response:a,user:s.user,tools:P(s.tools),approve:s.approve,onWarning:this.#o,signal:s.signal,after:s.after??0,...i?{runKey:i}:{},...s.key?{key:s.key}:{}})},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=P(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=L(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),e.effort&&(r.effort=e.effort),r.resumable=e.resumable?!0:"restarts",e.maxDurationMs&&(r.maxDurationMs=e.maxDurationMs);let o,s;try{this.#i&&(s=await this.#n(r,e.user,e.signal)),o=await A(this.#t,{method:"POST",path:"/runs",body:r,accept:"text/event-stream",signal:e.signal,retry:"unsent"})}catch(a){if(!this.#e.canServe(a,e.route))throw a;let u=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:L(n),task:e.task},e.signal);return this.#o("Soba could not be reached; your own provider is answering this run.",a),new x({config:this.#t,response:u.response,user:e.user,tools:n,approve:e.approve,onWarning:this.#o,signal:e.signal,local:{deliver:u.deliver,cancel:u.stop}})}this.#e.refreshSoon(),this.#e.flushSoon();let i=o.headers.get("soba-run-id");return s&&i&&this.#u(i,s),new x({config:this.#t,response:o,user:e.user,tools:n,approve:e.approve,onWarning:this.#o,signal:e.signal,...s?{runKey:s,key:await H(s,this.#t.apiKey)}:{}})}async#n(e,n,r){let o=await this.#l(n,r);if(o.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});let s=await re();return e.sealed=await se(s,{...e.prompt!==void 0?{prompt:e.prompt}:{},...e.messages!==void 0?{messages:e.messages}:{},...e.system!==void 0?{system:e.system}:{},...e.tools!==void 0?{tools:e.tools}:{},...e.resume!==void 0?{resume:e.resume}:{}},o),delete e.prompt,delete e.messages,delete e.system,delete e.tools,delete e.resume,s}#u(e,n){this.#s.set(e,n);let r=this.#s.keys().next().value;this.#s.size>it&&r&&this.#s.delete(r)}async#c(e,n){try{return await W(e,this.#t.apiKey)}catch{throw new c({code:"invalid_request",message:"That run key does not open with this API key. It is the `key` from the run, made with the same API key.",runId:n})}}async#l(e,n){let r=await w(this.#t,{method:"GET",path:"/keys",query:{user:e},...n?{signal:n}:{}}),o=await Promise.all((Array.isArray(r.data)?r.data:[]).filter(ie).map(async a=>({...a,fingerprint:await J(a.publicKey),user:e}))),s=this.#i?.trust,i=[];for(let a of o)(!s||await s(a))&&i.push(a);return this.#d(e,i)}async#d(e,n){let r=this.#i?.pin;if(!r||n.length===0)return n;let o=(r===!0?void 0:r.store)??this.#a,s=r===!0?void 0:r.onNewKey,i=await o.get(e)??[];if(i.length===0)return await o.set(e,n.map(p=>p.publicKey)),n;let a=[],u=[];for(let p of n)i.includes(p.publicKey)?a.push(p):s&&await s(p)?(a.push(p),u.push(p.publicKey)):this.#o(`Refused a key for "${e}" that was not pinned (fingerprint ${p.fingerprint}).`,p);return u.length&&await o.set(e,[...i,...u]),a}async request(e,n,r={}){return w(this.#t,{method:e,path:n,...r})}};function N(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}function at(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}function ut(){let t=new Map;return{get:e=>t.get(e),set:(e,n)=>{t.set(e,n)}}}function ct(t,e={}){let n=new TextEncoder,r=s=>n.encode(`data: ${JSON.stringify(s)}
|
|
8
|
+
|
|
9
|
+
`),o=new ReadableStream({async start(s){try{s.enqueue(r({type:"run",runId:t.runId,...t.key?{key:t.key}:{}}));for await(let i of t)s.enqueue(r({...i,cursor:t.cursor}))}catch(i){s.error(i);return}s.close()}});return new Response(o,{headers:{"content-type":"text/event-stream","cache-control":"no-cache, no-transform",...e.headers}})}var te=class{#t;me;workspaces;apps;constructor(e={}){let n=e.accessToken??ee("SOBA_ACCESS_TOKEN")??ee("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(lt())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.#t={apiKey:n,baseURL:e.baseURL??ee("SOBA_WEB_URL")??K,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??3e4,maxRetries:e.maxRetries??2};let r=this.#t,o=a=>w(r,{method:"GET",path:a}),s=(a,u,p)=>w(r,{method:a,path:u,...a==="DELETE"?{}:{body:p??{}},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 ee(t){return typeof process<"u"?process.env?.[t]:void 0}function lt(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}var dt=300;function pt(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function gt(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 ft(t,e,n,r={}){let o=Object.fromEntries((e??"").split(",").map(l=>{let g=l.indexOf("=");return[l.slice(0,g).trim(),l.slice(g+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??dt))throw a("This delivery is too old to accept.");let p=await globalThis.crypto.subtle.importKey("raw",new TextEncoder().encode(n),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),d=pt(await globalThis.crypto.subtle.sign("HMAC",p,new TextEncoder().encode(`${s}.${t}`)));if(!gt(d,i))throw a("The Soba-Signature does not match.");let f;try{f=JSON.parse(t)}catch{throw new c({code:"invalid_request",message:"The delivery is not JSON."})}let m=f;if(m.type!=="run.event"&&m.type!=="run.tool_call"||typeof m.run_id!="string")throw new c({code:"invalid_request",message:"Not a Soba run delivery."});return m}async function Te({key:t,apiKey:e}){if(!t)return null;let n=e??globalThis.process?.env?.SOBA_KEY;if(!n)throw new c({code:"invalid_request",message:"Opening an encrypted run needs your API key: pass `apiKey`, or set SOBA_KEY."});try{return await W(t,n)}catch{throw new c({code:"invalid_request",message:"That run key does not open with this API key."})}}function mt(){return new c({code:"invalid_request",message:"This run is end-to-end encrypted. Keep `started.key` from `soba.runs.start` and pass it as `key`."})}async function _e(t,e={}){let n=t.type==="run.tool_call"?O(t.data.input):void 0,r=t.type==="run.event"?t.data.event.sealed:void 0;if(!n&&typeof r!="string")return t;let o=await Te(e);if(!o)throw mt();if(t.type==="run.tool_call"&&n)return{...t,data:{...t.data,input:await C(o,n)}};if(t.type==="run.event"){let{sealed:s,...i}=t.data.event;return{...t,data:{event:{...i,...await C(o,s)}}}}return t}async function yt(t,e){if(t.type!=="run.tool_call")return null;let n=O(t.data.input)!==void 0,r=await _e(t,e);if(r.type!=="run.tool_call")return null;let o=n?await Te(e):null,s=async(d,f=!1)=>({result:o?{$sealed:await I(o,d)}:d,...f?{is_error:!0}:{}}),{call_id:i,name:a,input:u}=r.data,p=P(e.tools).get(a);if(!p)return s(`Unknown tool: ${a}`,!0);try{let d=await p.execute(u??{},{runId:t.run_id,user:e.user??"",callId:i,signal:AbortSignal.timeout(25e3)});return s(U(d))}catch(d){return s(q(d),!0)}}var ne=class{#t;apps;constructor(e={}){let n=e.apiKey??Ae("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(ht())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.#t={apiKey:n,baseURL:e.baseURL??Ae("SOBA_WEB_URL")??K,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??3e4,maxRetries:e.maxRetries??2};let r=this.#t;this.apps={list:async()=>(await w(r,{method:"GET",path:"/workspace/apps"})).data,create:({name:o})=>w(r,{method:"POST",path:"/workspace/apps",body:{name:o},retry:"unsent"}),keys:o=>w(r,{method:"POST",path:`/workspace/apps/${encodeURIComponent(o)}/keys`,body:{},retry:"unsent"})}}};function Ae(t){return typeof process<"u"?process.env?.[t]:void 0}function ht(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}export{Se as DEFAULT_BASE_URL,K as DEFAULT_WEB_BASE_URL,ye as METERED_CLASSES,x as Run,Z as Soba,c as SobaError,te as SobaManagement,ne as SobaWorkspace,et as TOOL_SLUGS,z as VERSION,J as fingerprint,yt as handleRunWebhook,Ze as isCostClass,Xe as isMetered,Q as isTerminal,_e as openRunWebhook,ct as runResponse,nt as tool,ft as verifyWebhook};
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { Run } from "./run.js";
|
|
2
|
+
/**
|
|
3
|
+
* A RUN, AS THE RESPONSE OF YOUR OWN ROUTE, for `useRun` in `@soba-so/react`.
|
|
4
|
+
*
|
|
5
|
+
* Start with `resumable: true` and return this, and read on with the same call
|
|
6
|
+
* around `soba.runs.attach`. The first frame names the run and carries its key,
|
|
7
|
+
* and every event carries its place, which is all a browser needs to come back
|
|
8
|
+
* to a run after a page switch or a dropped connection. The key is safe to send:
|
|
9
|
+
* see `Run.key`. A reader leaving does not stop the run.
|
|
10
|
+
*/
|
|
11
|
+
export declare function runResponse(run: Run, init?: {
|
|
12
|
+
headers?: Record<string, string>;
|
|
13
|
+
}): Response;
|
package/dist/run.d.ts
CHANGED
|
@@ -43,6 +43,8 @@ export interface RunInit {
|
|
|
43
43
|
* such a run was written by whoever carried it, and is dropped.
|
|
44
44
|
*/
|
|
45
45
|
runKey?: RunKey;
|
|
46
|
+
/** `runKey` wrapped for keeping. See `Run.key`. */
|
|
47
|
+
key?: string;
|
|
46
48
|
}
|
|
47
49
|
/**
|
|
48
50
|
* A run in flight.
|
|
@@ -65,6 +67,12 @@ export declare class Run implements AsyncIterable<AgentEvent> {
|
|
|
65
67
|
* about to hit its time limit, a deploy, a closed tab.
|
|
66
68
|
*/
|
|
67
69
|
get cursor(): number;
|
|
70
|
+
/**
|
|
71
|
+
* On an end-to-end run: what `soba.runs.attach` needs to read it from another
|
|
72
|
+
* process. Keep it with the run's id, anywhere, even in a browser: it is
|
|
73
|
+
* useless without your API key. A server that stays up does not need it.
|
|
74
|
+
*/
|
|
75
|
+
get key(): string | undefined;
|
|
68
76
|
/** Answered by your own provider because Soba could not be reached. Not
|
|
69
77
|
* resumable, and reported to Soba later (`soba.fallback.flush()`). */
|
|
70
78
|
get servedWithoutSoba(): boolean;
|
package/dist/version.d.ts
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export declare const VERSION = "0.0.
|
|
1
|
+
export declare const VERSION = "0.0.21";
|
package/dist/webhooks.d.ts
CHANGED
|
@@ -42,6 +42,18 @@ export declare function verifyWebhook(rawBody: string, header: string | null | u
|
|
|
42
42
|
toleranceSeconds?: number;
|
|
43
43
|
now?: number;
|
|
44
44
|
}): Promise<RunWebhookEvent>;
|
|
45
|
+
/** Whose run this is, on an encrypted one. */
|
|
46
|
+
export interface SealedRunOptions {
|
|
47
|
+
/** `started.key` from `soba.runs.start`: keep it with the run's id. */
|
|
48
|
+
key?: string;
|
|
49
|
+
/** Defaults to `SOBA_KEY`. It must be the key the run was started with. */
|
|
50
|
+
apiKey?: string;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* A delivery from an encrypted run, with its content put back. Soba only ever
|
|
54
|
+
* carried it sealed. A delivery that was never sealed comes back as it is.
|
|
55
|
+
*/
|
|
56
|
+
export declare function openRunWebhook(event: RunWebhookEvent, options?: SealedRunOptions): Promise<RunWebhookEvent>;
|
|
45
57
|
/**
|
|
46
58
|
* Answer a verified delivery. A tool call runs the named tool from `tools` and
|
|
47
59
|
* resolves to its result; anything else resolves to `null`.
|
|
@@ -53,4 +65,4 @@ export declare function verifyWebhook(rawBody: string, header: string | null | u
|
|
|
53
65
|
export declare function handleRunWebhook(event: RunWebhookEvent, options: {
|
|
54
66
|
tools: readonly ToolDefinition[];
|
|
55
67
|
user?: string;
|
|
56
|
-
}): Promise<ToolCallAnswer | null>;
|
|
68
|
+
} & SealedRunOptions): Promise<ToolCallAnswer | null>;
|
package/package.json
CHANGED