@soba-so/sdk 0.0.12 → 0.0.14

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import { type MachineKey } from "./e2e.js";
1
2
  import type { Message, RouteRequest, RunPolicy } from "./protocol.js";
2
3
  import type { ConnectContextResponse, FeatureCheckResult, MachineListItem, PlanListResponse, QuantityResult, SobaUser, TrackResult, UsagePage, UsageQuery } from "./resources.js";
3
4
  import { type Approver, Run } from "./run.js";
@@ -40,6 +41,45 @@ export interface SobaOptions {
40
41
  * visitor the ability to spend your account. Only set this for a trusted
41
42
  * first-party context you control. */
42
43
  dangerouslyAllowBrowser?: boolean;
44
+ /**
45
+ * Answer runs with your own provider when Soba cannot be reached. On by
46
+ * default, and it does nothing until "Also use if Soba can't be reached" is
47
+ * switched on under Models in your dashboard. `false` turns it off here
48
+ * whatever the dashboard says. See `soba.fallback`.
49
+ */
50
+ fallback?: boolean;
51
+ /**
52
+ * END-TO-END ENCRYPTION. Every `soba.run()` is sealed here, on your server,
53
+ * to the person's own machines, and everything it sends back is sealed to
54
+ * you. Soba routes and bills on what stays outside (model, route, policy,
55
+ * token counts) and never sees a prompt, a tool result or an answer.
56
+ *
57
+ * A run nobody can open (the person has no machine connected that holds a
58
+ * key) is never sent: `soba.run()` throws `no_compute` at once, the same
59
+ * handback as a run with nowhere to go, so your own provider answers it.
60
+ * Bought supply and the connected-plan channel are never used for an
61
+ * encrypted run, because Soba would have to read it to serve it.
62
+ *
63
+ * Pass `{ trust }` to pin keys: it is shown each machine's key and its
64
+ * fingerprint, and a machine it says no to is never sealed to. Without it, a
65
+ * key is trusted as Soba hands it over, which is what a pin guards against.
66
+ */
67
+ encrypt?: boolean | EncryptOptions;
68
+ }
69
+ export interface EncryptOptions {
70
+ trust?: (key: MachineKey & {
71
+ fingerprint: string;
72
+ }) => boolean | Promise<boolean>;
73
+ }
74
+ /** Your own provider answering while Soba cannot be reached. See `fallback.ts`. */
75
+ export interface FallbackControl {
76
+ /** Read what to fall back to now rather than on the first run. Never throws. */
77
+ prime(): Promise<void>;
78
+ /** Report the runs served while Soba was unreachable. Call it from `waitUntil`
79
+ * on serverless; it is also tried after every run Soba answers. */
80
+ flush(): Promise<void>;
81
+ /** Runs served without Soba and not yet reported. */
82
+ readonly pending: number;
43
83
  }
44
84
  export interface RunParams {
45
85
  /**
@@ -250,6 +290,7 @@ export interface DetachedRunParams extends Omit<RunParams, "approve" | "signal"
250
290
  */
251
291
  export declare class Soba {
252
292
  #private;
293
+ readonly fallback: FallbackControl;
253
294
  readonly users: {
254
295
  /** What this user has: plan, allowance, usage this period, what they connected. */
255
296
  get(id: string): Promise<SobaUser>;
package/dist/e2e.d.ts ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * END-TO-END RUNS, the app's half.
3
+ *
4
+ * With `encrypt: true`, a run's content (prompt, messages, system, tool
5
+ * schemas) is sealed here, on your server, to the public keys of the person's
6
+ * machines. Everything the run sends back (text, tool calls, approvals) is
7
+ * sealed to the same per-run key, and so is every answer you send it. Soba
8
+ * routes and bills on what stays outside (model, route, policy, token counts)
9
+ * and only ever carries ciphertext.
10
+ *
11
+ * The scheme matches packages/worker/src/e2e.ts byte for byte, and a test
12
+ * opens each half with the other:
13
+ *
14
+ * - A random 32-byte run key K.
15
+ * - For each machine: a fresh X25519 key, HKDF-SHA256 over the shared secret
16
+ * (salt `epk.kid`, info `soba-e2e-wrap-v1`), and K sealed with AES-256-GCM.
17
+ * - The content: AES-256-GCM under K, AAD `soba-e2e-request-v1`.
18
+ * - Frames: AES-256-GCM under K, AAD `soba-e2e-up` from the machine and
19
+ * `soba-e2e-down` from the app.
20
+ *
21
+ * WebCrypto rather than `node:crypto`, so the SDK runs wherever `fetch` does.
22
+ */
23
+ type CryptoKey = Awaited<ReturnType<typeof crypto.subtle.importKey>>;
24
+ /** One of the person's machines that can open a run: its public key, as Soba handed it over. */
25
+ export interface MachineKey {
26
+ /** The machine's id on Soba. */
27
+ machine: string;
28
+ /** base64url, 32 bytes, X25519. */
29
+ publicKey: string;
30
+ }
31
+ export interface SealedRequest {
32
+ v: 1;
33
+ keys: {
34
+ kid: string;
35
+ epk: string;
36
+ iv: string;
37
+ ct: string;
38
+ }[];
39
+ iv: string;
40
+ ct: string;
41
+ }
42
+ /** A run's key, held in memory for as long as the run is read. Never sent to Soba. */
43
+ export interface RunKey {
44
+ raw: Uint8Array;
45
+ key: CryptoKey;
46
+ }
47
+ export declare function newRunKey(): Promise<RunKey>;
48
+ /** Seal `payload` so that only the machines in `recipients` can open it. */
49
+ export declare function sealRequest(runKey: RunKey, payload: Record<string, unknown>, recipients: MachineKey[]): Promise<SealedRequest>;
50
+ /** One frame from the app to the machine: a tool result. */
51
+ export declare function sealDown(runKey: RunKey, value: unknown): Promise<string>;
52
+ /** One frame from the machine. Throws if it was not sealed to this run, or was altered. */
53
+ export declare function openUp(runKey: RunKey, frame: string): Promise<unknown>;
54
+ /** `{ $sealed: "e1…" }`, the shape a sealed tool input or result travels in. */
55
+ export declare function sealedValue(v: unknown): string | undefined;
56
+ /**
57
+ * A key's fingerprint, for pinning: the first 16 bytes of its SHA-256, hex,
58
+ * in groups of four, short enough to read aloud and compare.
59
+ */
60
+ export declare function fingerprint(publicKey: string): Promise<string>;
61
+ export declare function isMachineKey(v: unknown): v is MachineKey;
62
+ export {};
package/dist/errors.d.ts CHANGED
@@ -61,12 +61,7 @@ export declare class SobaError extends Error {
61
61
  constructor(init: SobaErrorInit);
62
62
  }
63
63
  export declare function codeForStatus(status: number): SobaErrorCode;
64
- /**
65
- * Build an error from a failed response. The envelope is
66
- * `{ error: { type, message, code } }` on every endpoint, but a proxy, a
67
- * gateway timeout page or an HTML error can arrive here too, so nothing about
68
- * the body is assumed.
69
- */
64
+ export declare function fromSobaEdge(err: SobaError): boolean;
70
65
  export declare function errorFromResponse(response: Response): Promise<SobaError>;
71
66
  /** RFC 7231 allows seconds or an HTTP date. Both appear in the wild. */
72
67
  export declare function retryAfterMs(header: string | null): number | undefined;
@@ -0,0 +1,143 @@
1
+ import { type HttpConfig } from "./http.js";
2
+ import type { Message, RouteRequest, ToolSchema } from "./protocol.js";
3
+ /**
4
+ * WHEN SOBA ITSELF CANNOT BE REACHED, YOUR OWN PROVIDER ANSWERS.
5
+ *
6
+ * Your providers (the dashboard's Models page) already catch a run your users'
7
+ * own AI cannot serve — but Soba's gateway does the catching, so with the
8
+ * gateway down your server got a refused connection and your users got
9
+ * nothing, on a provider account you pay for and could have called yourself.
10
+ *
11
+ * With "Also use if Soba can't be reached" switched on, this calls that
12
+ * provider directly from your server instead: the same OpenAI-compatible
13
+ * endpoint the gateway would have called, your tools answered here, and the
14
+ * same events back from `soba.run()`. Each run it serves is reported to Soba
15
+ * once Soba answers again (`flush`), so usage and allowances are late rather
16
+ * than wrong.
17
+ *
18
+ * WHERE THE PROVIDER COMES FROM, in order:
19
+ *
20
+ * 1. What Soba last said (`GET /v1/fallback`), read while it was up and kept
21
+ * in memory — the key included, if Soba holds it. Nothing to set.
22
+ * 2. `SOBA_FALLBACK`, the line the dashboard gives you to paste, for a server
23
+ * that starts while Soba is already down and so never read (1) — the
24
+ * usual case on serverless. It holds no key: the key comes from the
25
+ * variable the provider names (`SOBA_SUPPLIER_…_KEY`), which you set.
26
+ *
27
+ * WHEN IT ENGAGES: only when the run provably never reached Soba — a refused
28
+ * connection, a name that did not resolve, or an error page from in front of
29
+ * the gateway rather than from it. Not on a timeout, and never once Soba has
30
+ * answered: either can follow a run Soba already started, and answering it
31
+ * again here would be a second run, paid for twice.
32
+ */
33
+ export interface FallbackProvider {
34
+ /** The provider's id on the Models page, which a reported run is priced by. */
35
+ id: string;
36
+ name: string;
37
+ baseUrl: string;
38
+ /** The variable read for the key, ahead of `apiKey`. */
39
+ keyEnv: string;
40
+ costClass: string;
41
+ apiKey?: string;
42
+ models: {
43
+ model: string;
44
+ alias: string | null;
45
+ maxOutputTokens: number | null;
46
+ }[];
47
+ }
48
+ interface FallbackConfig {
49
+ enabled: boolean;
50
+ providers: FallbackProvider[];
51
+ }
52
+ /** A run this served, as it is reported to Soba (`POST /v1/usage/backfill`). */
53
+ export interface FallbackRecord {
54
+ id: string;
55
+ user: string;
56
+ supplier: string;
57
+ model: string;
58
+ input_tokens: number;
59
+ output_tokens: number;
60
+ cache_read_tokens: number;
61
+ cache_write_tokens: number;
62
+ started_at: string;
63
+ ended_at: string;
64
+ status: "done" | "error";
65
+ error?: string;
66
+ task?: string;
67
+ }
68
+ export interface FallbackRequest {
69
+ runId: string;
70
+ user: string;
71
+ model: string | undefined;
72
+ route: RouteRequest | undefined;
73
+ system: string | undefined;
74
+ messages: Message[];
75
+ tools: ToolSchema[];
76
+ task: string | undefined;
77
+ }
78
+ /** A run's tool result, handed back by `Run` instead of posted to Soba. */
79
+ export interface ToolAnswer {
80
+ callId: string;
81
+ result: unknown;
82
+ isError: boolean;
83
+ }
84
+ export declare class Fallback {
85
+ #private;
86
+ constructor(init: {
87
+ http: HttpConfig;
88
+ onWarning: (message: string, detail?: unknown) => void;
89
+ off: boolean;
90
+ });
91
+ /**
92
+ * Read what to fall back to now, rather than on the first run. For a server
93
+ * that starts while Soba is up and wants to be ready before it goes down.
94
+ * Never throws: with Soba unreachable there is simply nothing new to keep.
95
+ */
96
+ prime(): Promise<void>;
97
+ /** Called on every run: a read in the background when what is kept is old. */
98
+ refreshSoon(): void;
99
+ /** Runs served here and not yet reported to Soba. */
100
+ get pending(): number;
101
+ /**
102
+ * Whether this error means the run never reached Soba, and something here
103
+ * can answer it instead.
104
+ */
105
+ canServe(err: unknown, route: RouteRequest | undefined): boolean;
106
+ /**
107
+ * The run, answered by the vendor's own provider: Soba's stream format, so
108
+ * `Run` reads it exactly as it reads one from the gateway.
109
+ */
110
+ serve(request: FallbackRequest, parent: AbortSignal | undefined): {
111
+ response: Response;
112
+ deliver: (answer: ToolAnswer) => void;
113
+ stop: (reason: unknown) => void;
114
+ };
115
+ /**
116
+ * Report the runs served here, now. Safe to call any time and from several
117
+ * places at once; a run Soba already has is dropped, not counted twice.
118
+ * On serverless, call it where the platform lets work finish after the
119
+ * response (`waitUntil`) — a function frozen between requests reports
120
+ * nothing until it next runs.
121
+ */
122
+ flush(): Promise<void>;
123
+ /** After a run Soba answered: it is up, so whatever is queued can go. */
124
+ flushSoon(): void;
125
+ }
126
+ /**
127
+ * `SOBA_FALLBACK`: the dashboard's providers as base64url JSON, keys left out.
128
+ * Pasted into the deploy's environment, so a server that never reached Soba
129
+ * still knows where to go. Its presence is the vendor opting in; Soba saying
130
+ * otherwise (`enabled: false`, read later) still wins.
131
+ */
132
+ export declare function fromEnv(): FallbackConfig | null;
133
+ /**
134
+ * Which of this provider's models answers.
135
+ *
136
+ * A model it lists by name or alias, as the picker sends it. Otherwise what
137
+ * the gateway would pick: the cheapest (models arrive cheapest first) for
138
+ * Automatic and Fast, the dearest for Best — and a name only a machine knows,
139
+ * like `opus` for Claude Code, is Automatic here, because the run has to go
140
+ * somewhere.
141
+ */
142
+ export declare function pickModel(provider: FallbackProvider, wanted: string | undefined): FallbackProvider["models"][number];
143
+ export {};
package/dist/http.d.ts CHANGED
@@ -28,6 +28,7 @@ export interface RequestOptions {
28
28
  */
29
29
  retry?: boolean | "unsent";
30
30
  }
31
+ export declare function provablyUnsent(err: SobaError): boolean;
31
32
  export declare function httpRequest(cfg: HttpConfig, opts: RequestOptions): Promise<Response>;
32
33
  export declare function requestJson<T>(cfg: HttpConfig, opts: RequestOptions): Promise<T>;
33
34
  export declare function buildUrl(baseURL: string, path: string, query?: Record<string, string | number | boolean | undefined>): string;
package/dist/index.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- export { type AttachParams, DEFAULT_BASE_URL, DEFAULT_WEB_BASE_URL, type DetachedRunParams, type OpKind, type OpParams, type OpResult, type RunParams, Soba, type SobaOptions, type StartedRun, type TerminalBooking, type TerminalParams, } from "./client.js";
1
+ export { type AttachParams, DEFAULT_BASE_URL, DEFAULT_WEB_BASE_URL, type DetachedRunParams, type EncryptOptions, type FallbackControl, type OpKind, type OpParams, type OpResult, type RunParams, Soba, type SobaOptions, type StartedRun, type TerminalBooking, type TerminalParams, } from "./client.js";
2
+ export { fingerprint, type MachineKey } from "./e2e.js";
2
3
  export { SobaError, type SobaErrorCode } from "./errors.js";
3
4
  export { type AgentEvent, type AgentEventType, type CostClass, type GitSnapshot, type ImageInput, isCostClass, isMetered, isTerminal, METERED_CLASSES, type Message, type PermissionMode, type RouteRequest, type RunPolicy, type RunUsage, TOOL_SLUGS, type ToolSchema, type ToolSlug, } from "./protocol.js";
4
5
  export type { Allowance, ConnectContextResponse, ConnectedMachine, CurrentPlanItem, FeatureCheckResult, FeatureDenial, MachineListItem, MachineListState, MachineRuntime, PlanFeatureWire, PlanListItem, PlanListResponse, PlanSummary, QuantityResult, RuntimeListItem, SobaUser, TrackResult, UsagePage, UsageQuery, UsageRow, } from "./resources.js";
package/dist/index.mjs CHANGED
@@ -1,4 +1,7 @@
1
- var a=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??B.has(e.code),this.retryAfterMs=e.retryAfterMs,this.runId=e.runId}},B=new Set(["rate_limited","server_error","connection","timeout","stream_truncated"]),G={400:"invalid_request",401:"unauthorized",402:"payment_required",403:"forbidden",404:"not_found",409:"no_compute",422:"user_required",429:"rate_limited"};function K(n){let e=G[n];return e||(n>=500?"server_error":n>=400?"invalid_request":"unknown")}async function q(n){let e=n.status,r="";try{r=await n.text()}catch{}let t=H(r);return new a({code:t?.code??K(e),type:t?.type,message:t?.message??z(e,n.statusText,r),status:e,retryAfterMs:Q(n.headers.get("retry-after")),runId:n.headers.get("soba-run-id")??void 0})}function H(n){if(!n)return null;let e;try{e=JSON.parse(n)}catch{return null}if(!e||typeof e!="object")return null;let r=e.error;if(!r||typeof r!="object")return null;let t=r;return{message:typeof t.message=="string"&&t.message?t.message:void 0,type:typeof t.type=="string"&&t.type?t.type:void 0,code:J.has(t.code)?t.code:void 0}}var J=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 z(n,e,r){let t=r.trim().slice(0,200),o=t?`: ${t}`:"";return`Soba returned ${n}${e?` ${e}`:""}${o}`}function Q(n){if(!n)return;let e=Number(n);if(Number.isFinite(e)&&e>=0)return Math.round(e*1e3);let r=Date.parse(n);if(!Number.isNaN(r))return Math.max(0,r-Date.now())}function w(n){if(n instanceof a)return n;let e=n;return e?.name==="AbortError"||e?.name==="TimeoutError"?new a({code:"canceled",message:e.message||"The request was aborted.",retryable:!1,cause:n}):new a({code:"connection",message:e?.message?`Could not reach Soba: ${e.message}`:"Could not reach Soba.",cause:n})}var E="0.0.12";var Y=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]);function V(n){if(n.code==="rate_limited")return!0;if(n.code!=="connection")return!1;let e=n.cause;for(let r=0;e&&r<4;r++){let t=e.code;if(typeof t=="string"&&Y.has(t))return!0;e=e.cause}return!1}var X=8e3,Z=3e4;async function b(n,e){let r=ne(n.baseURL,e.path,e.query),t=e.retry===!1?1:Math.max(0,n.maxRetries)+1,o,s=i=>i.retryable&&(e.retry!=="unsent"||V(i));for(let i=0;i<t;i++){i>0&&await oe(re(i,o),e.signal);let u=new AbortController,d=A(e.signal,u),h=setTimeout(()=>{u.abort(new a({code:"timeout",message:`Soba did not answer within ${n.connectTimeoutMs}ms.`}))},n.connectTimeoutMs),l;try{l=await n.fetch(r,{method:e.method,headers:ee(n,e),body:e.body===void 0?void 0:JSON.stringify(e.body),signal:u.signal})}catch(p){if(d(),o=w(u.signal.aborted?u.signal.reason??p:p),!s(o)||i===t-1)throw o;continue}finally{clearTimeout(h)}if(l.ok)return l;if(d(),o=await q(l),!s(o)||i===t-1)throw o}throw o??new a({code:"unknown",message:"The request failed with no error."})}async function R(n,e){let r=await b(n,{accept:"application/json",...e}),t=await r.text();if(t)try{return JSON.parse(t)}catch(o){throw new a({code:"server_error",message:`Soba returned a body that is not JSON: ${t.slice(0,200)}`,status:r.status,cause:o})}}function ee(n,e){let r={authorization:`Bearer ${n.apiKey}`,accept:e.accept??"application/json","user-agent":te(),...n.headers};return e.body!==void 0&&(r["content-type"]="application/json"),r}function te(){let n=typeof process>"u"?"":` node/${process.versions?.node??"?"}`;return`soba-sdk/${E}${n}`}function ne(n,e,r){let t=n.replace(/\/+$/,""),o=new URL(`${t}${e.startsWith("/")?e:`/${e}`}`);for(let[s,i]of Object.entries(r??{}))i!==void 0&&o.searchParams.set(s,String(i));return o.toString()}function re(n,e){if(e?.retryAfterMs!==void 0)return Math.min(e.retryAfterMs,Z);let r=Math.min(X,500*2**(n-1));return Math.round(r*(.5+Math.random()/2))}function oe(n,e){return new Promise((r,t)=>{if(e?.aborted)return t(w(e.reason));let o=setTimeout(()=>{e?.removeEventListener("abort",s),r()},n);function s(){clearTimeout(o),t(w(e?.reason))}e?.addEventListener("abort",s,{once:!0})})}function A(n,e){if(!n)return()=>{};if(n.aborted)return e.abort(n.reason),()=>{};let r=()=>e.abort(n.reason);return n.addEventListener("abort",r,{once:!0}),()=>n.removeEventListener("abort",r)}var M=["open-weights","frontier"];function se(n){return M.includes(n)}function ie(n){return n==="user-hardware"||n==="user-subscription"||n==="user-api-key"||n==="open-weights"||n==="frontier"}function _(n){return n.type==="done"||n.type==="error"}var ae=["search","fetch","read","write","edit","bash","files","agent","todo","think","sources","tool"];var N=new Set(["delta","thinking","status","done","error"]);function C(n){let e;try{e=JSON.parse(n)}catch{return null}if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e,t=c(r.runId);if(typeof r.type=="string"&&N.has(r.type)){let o=O(r);return o?{kind:"event",runId:t,event:o}:null}switch(r.type){case"event":{if(!r.event||typeof r.event!="object")return null;let o=O(r.event);return o?{kind:"event",runId:t,event:o}:null}case"usage":{let o=$(r.usage);return o?{kind:"usage",runId:t,usage:o}:null}case"tool_call":{let o=c(r.callId),s=c(r.name);return!o||!s?null:{kind:"tool_call",runId:t,callId:o,name:s,input:r.input,...r.answered===!0?{answered:!0}:{}}}case"approval_request":{let o=c(r.approvalId),s=c(r.tool);return!o||!s?null:{kind:"approval",runId:t,approvalId:o,tool:s,input:r.input,cwd:c(r.cwd),...r.answered===!0?{answered:!0}:{}}}default:return null}}function O(n){let e=typeof n.type=="string"&&N.has(n.type)?n.type:null;if(!e)return null;let r={type:e},t=c(n.text);t!==void 0&&(r.text=t);let o=c(n.message);o!==void 0&&(r.message=o);let s=c(n.tool);s!==void 0&&(r.tool=s);let i=c(n.tier);i!==void 0&&(r.tier=i);let u=$(n.usage);u&&(r.usage=u);let d=c(n.reason);d!==void 0&&(r.reason=d),typeof n.retryable=="boolean"&&(r.retryable=n.retryable);let h=n.turn&&typeof n.turn=="object"?c(n.turn.text):void 0;h!==void 0&&(r.turn={text:h});let l=c(n.session);l!==void 0&&(r.session=l);let p=c(n.toolInput);p!==void 0&&(r.toolInput=p);let m=ue(n.git);return m&&(r.git=m),(n.state==="interrupted"||n.state==="resumed")&&(r.state=n.state),r}function ue(n){if(!n||typeof n!="object")return null;let e=n,r=c(e.branch);return!r||!Array.isArray(e.files)||!Array.isArray(e.commits)?null:{branch:r,base:c(e.base)??"",head:c(e.head)??"",ahead:y(e.ahead),behind:y(e.behind),files:e.files.filter(t=>!!t&&typeof t=="object"&&typeof t.path=="string").map(t=>({path:t.path,status:t.status==="A"||t.status==="D"||t.status==="R"?t.status:"M",added:y(t.added),removed:y(t.removed)})),commits:e.commits.filter(t=>!!t&&typeof t=="object").map(t=>({sha:c(t.sha)??"",subject:c(t.subject)??""})),dirty:e.dirty===!0}}function $(n){if(!n||typeof n!="object")return null;let e=n,r={model:c(e.model)??"unknown",inputTokens:y(e.inputTokens),outputTokens:y(e.outputTokens),cacheReadTokens:y(e.cacheReadTokens),cacheWriteTokens:y(e.cacheWriteTokens),webSearches:y(e.webSearches)},t=c(e.costClass);t!==void 0&&(r.costClass=t);let o=c(e.provider);return o!==void 0&&(r.provider=o),typeof e.costMicros=="number"&&Number.isFinite(e.costMicros)&&(r.costMicros=e.costMicros),r}function c(n){return typeof n=="string"&&n.length>0?n:void 0}function y(n){return typeof n=="number"&&Number.isFinite(n)?n:0}async function*F(n){let e=n.body;if(!e)throw new a({code:"connection",message:"The run response arrived with no body to stream.",status:n.status});let r=n.headers.get("content-type")??"",t=r.includes("ndjson")||r.includes("jsonlines"),o=e.getReader(),s=new TextDecoder,i="",u=[],d,h=l=>d===void 0?l:{...l,seq:d};try{for(;;){let p=await o.read();if(p.done)break;for(i+=s.decode(p.value,{stream:!0});;){let m=i.indexOf(`
2
- `);if(m===-1)break;let f=L(i.slice(0,m));if(i=i.slice(m+1),t){let g=f.trim()?C(f):null;g&&(yield g);continue}if(f===""){let g=u.join(`
3
- `);if(u=[],g==="[DONE]")return;let U=g?C(g):null;U&&(yield h(U)),d=void 0;continue}if(f.startsWith("id:")){let g=Number(f.slice(3).trim());d=Number.isInteger(g)&&g>0?g:void 0;continue}D(f,u)}}!t&&i&&D(L(i),u);let l=t?i.trim():u.join(`
4
- `);if(l&&l!=="[DONE]"){let p=C(l);p&&(yield t?p:h(p))}}finally{o.cancel().catch(()=>{})}}function D(n,e){if(n.startsWith(":"))return;let r=n.indexOf(":");if(r===-1||n.slice(0,r)!=="data")return;let t=n.slice(r+1);e.push(t.startsWith(" ")?t.slice(1):t)}function L(n){return n.endsWith("\r")?n.slice(0,-1):n}function ce(n){return n}function S(n){let e=new Map;for(let r of n??[]){if(!r?.name)throw new a({code:"invalid_request",message:"Every tool needs a name."});if(typeof r.execute!="function")throw new a({code:"invalid_request",message:`Tool "${r.name}" has no execute function. A tool Soba cannot call is not a tool.`});if(e.has(r.name))throw new a({code:"invalid_request",message:`Two tools are named "${r.name}". Tool names must be unique within a run.`});e.set(r.name,r)}return e}function I(n){return[...n.values()].map(e=>({name:e.name,description:e.description??"",inputSchema:e.inputSchema??{type:"object"}}))}function x(n){if(n===void 0)return null;if(typeof n=="string")return n;try{return JSON.parse(JSON.stringify(n))}catch{return String(n)}}function T(n){return n instanceof Error?n.message||n.name:typeof n=="string"?n:String(n)}var k=class{#e;#n;#r;#u=!1;#o;#t;#s=new AbortController;#i=new AbortController;#a=new Set;#c;constructor(e){this.#t=e,this.#e=e.response.headers.get("soba-run-id")??"",this.#o=e.after??0,this.#c=A(e.signal,this.#s)}get cursor(){return this.#o}get resumable(){return this.#t.response.headers.get("soba-resumable")==="1"}get runId(){return this.#e}get tier(){return this.#n}get usage(){return this.#r}[Symbol.asyncIterator](){return this.#l()}async text(){let e="";for await(let r of this)if(r.type==="delta"&&r.text&&(e+=r.text),r.type==="error")throw new a({code:"run_failed",message:r.message??"The run ended with an error.",runId:this.#e,retryable:!1});return e}async cancel(){if(this.#s.abort(new a({code:"canceled",message:"The run was cancelled."})),this.#i.abort(new a({code:"canceled",message:"The run was cancelled."})),!!this.#e)try{await b(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(){if(this.#u)throw new a({code:"invalid_request",message:"This run has already been consumed. A run's events can only be read once.",runId:this.#e});this.#u=!0;let e=!1;try{for await(let r of F(this.#t.response)){if(r.runId&&!this.#e&&(this.#e=r.runId),r.seq!==void 0&&(this.#o=r.seq),r.kind==="event"){let t=r.event;if(t.tier&&(this.#n=t.tier),t.usage&&(this.#r=t.usage),e=_(t),yield t,e)return;continue}if(r.kind==="usage"){this.#r=r.usage;continue}this.#p(this.#g(r))}throw new a({code:"stream_truncated",message:"The run stream ended without a `done` or `error` event.",runId:this.#e})}finally{e||this.#i.abort(new a({code:"canceled",message:"The run ended before this tool finished."})),await Promise.allSettled([...this.#a]),this.#s.abort(),this.#c()}}#p(e){this.#a.add(e),e.finally(()=>this.#a.delete(e)).catch(()=>{})}async#g(e){if(!((e.kind==="tool_call"||e.kind==="approval")&&e.answered)){if(e.kind==="tool_call")return this.#f(e);if(e.kind==="approval")return this.#m(e)}}async#f(e){let r=this.#t.tools.get(e.name),t,o=!1;if(!r)t=`No tool named "${e.name}" is registered by this app.`,o=!0;else{let s={runId:this.#e,user:this.#t.user,callId:e.callId,signal:this.#i.signal};try{t=await r.execute(e.input,s)}catch(i){t=T(i),o=!0}}await this.#d(`/runs/${encodeURIComponent(this.#e)}/tool_result`,{callId:e.callId,result:x(t),isError:o})}async#m(e){let r="deny",t;if(!this.#t.approve)t="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),r=await this.#t.approve(o)==="allow"?"allow":"deny"}catch(o){t=T(o)}await this.#d(`/runs/${encodeURIComponent(this.#e)}/approval`,{approvalId:e.approvalId,decision:r,...t?{reason:t}:{}})}async#d(e,r){if(!this.#e){this.#t.onWarning("Soba sent a frame before the run had an id, so it could not be answered.",r);return}try{await(await b(this.#t.config,{method:"POST",path:e,body:r})).text()}catch(t){this.#t.onWarning(`Could not deliver an answer to ${e}.`,w(t))}}};var j="https://api.soba.so/v1",W="https://soba.so/v1",de=3e4,le=2,P=class{#e;#n;#r;users;usage;connect;plans;runs;ops;terminals;constructor(e={}){let r=e.apiKey??v("SOBA_KEY")??v("SOBA_API_KEY");if(!r)throw new a({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(pe()&&!e.dangerouslyAllowBrowser)throw new a({code:"invalid_request",message:"A Soba app key is a server credential and this looks like a browser. Call Soba from your server, or pass dangerouslyAllowBrowser if you are certain."});if(this.#r=e.onWarning??(()=>{}),this.#e={apiKey:r,baseURL:e.baseURL??v("SOBA_BASE_URL")??j,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??de,maxRetries:e.maxRetries??le},this.#n={...this.#e,baseURL:e.webBaseURL??v("SOBA_WEB_URL")??W},typeof this.#e.fetch!="function")throw new a({code:"invalid_request",message:"No global fetch. Run on Node 22 or newer, or pass your own `fetch`."});this.users={get:t=>this.request("GET",`/users/${encodeURIComponent(t)}`),compute:async t=>(await this.request("GET",`/users/${encodeURIComponent(t)}/compute`)).machines,setQuantity:(t,o,s)=>R(this.#n,{method:"POST",path:`/end_users/${encodeURIComponent(t)}/features/${encodeURIComponent(o)}/quantity`,body:{quantity:s}}),check:(t,o,s)=>R(s?.use?{...this.#n,maxRetries:0}:this.#n,{method:"POST",path:`/end_users/${encodeURIComponent(t)}/features/${encodeURIComponent(o)}/check`,body:s?.use?{use:s.use}:{}}),track:(t,o,s=1)=>R({...this.#n,maxRetries:0},{method:"POST",path:`/end_users/${encodeURIComponent(t)}/features/${encodeURIComponent(o)}/track`,body:{amount:s}})},this.usage={list:t=>this.request("GET","/usage",{query:{...t}})},this.connect=()=>this.request("GET","/connect"),this.runs={start:async t=>{if(!t.user)throw new a({code:"user_required",status:422,message:"`user` is required."});let o=S(t.tools),s={user:t.user,model:t.model??"auto",detached:!0};t.webhook&&(s.webhook=t.webhook),t.prompt&&(s.prompt=t.prompt),t.messages?.length&&(s.messages=t.messages),t.system&&(s.system=t.system),t.runtime&&(s.runtime=t.runtime),o.size&&(s.tools=I(o)),t.route&&(s.route=t.route),t.policy&&(s.policy=t.policy),t.metadata&&(s.metadata=t.metadata),t.task&&(s.task=t.task),t.surface&&(s.surface=t.surface),t.maxDurationMs&&(s.maxDurationMs=t.maxDurationMs),t.title&&(s.title=t.title),t.worktree&&(s.worktree=t.worktree),t.resume&&(s.resume=t.resume);let i=await R(this.#e,{method:"POST",path:"/runs",body:s,retry:"unsent"}),u={id:i.id};return i.stream&&(u.stream={url:i.stream.url,token:i.stream.token,expiresAt:i.stream.expires_at}),t.answerTools==="here"&&(u.answered=(async()=>{let d=await this.runs.attach(i.id,{user:t.user,tools:t.tools??[]});for await(let h of d);})().catch(d=>this.#r("Answering this run's tool calls stopped.",d))),u},attach:async(t,o)=>{if(!o.user)throw new a({code:"user_required",status:422,message:"`user` is required."});let s=await b(this.#e,{method:"GET",path:`/runs/${encodeURIComponent(t)}/stream`,...o.after?{query:{after:o.after}}:{},accept:"text/event-stream",signal:o.signal});return new k({config:this.#e,response:s,user:o.user,tools:S(o.tools),approve:o.approve,onWarning:this.#r,signal:o.signal,after:o.after??0})},cancel:async t=>{await this.request("POST",`/runs/${encodeURIComponent(t)}/cancel`,{body:{}})}},this.ops={run:t=>{if(!t.user)throw new a({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:{...t}})}},this.terminals={open:async t=>{if(!t.user)throw new a({code:"user_required",status:422,message:"`user` is required \u2014 it is how Soba knows whose machine to open it on."});let o=await this.request("POST","/term",{body:{...t}}),s=new URL(this.#e.baseURL);s.protocol=s.protocol==="http:"?"ws:":"wss:";let i=new URL(o.path,`${s.protocol}//${s.host}`);return i.searchParams.set("ticket",o.ticket),{termId:o.termId,url:i.toString(),expiresAt:o.expiresAt}}},this.plans={list:t=>this.request("GET","/plans",{...t?.user?{query:{user:t.user}}:{}})}}get baseURL(){return this.#e.baseURL}async run(e){if(!e.user)throw new a({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 a({code:"invalid_request",status:400,message:"A run needs a `prompt` or a non-empty `messages`."});let r=S(e.tools),t={user:e.user,model:e.model??"auto"};e.prompt&&(t.prompt=e.prompt),e.messages?.length&&(t.messages=e.messages),e.system&&(t.system=e.system),e.runtime&&(t.runtime=e.runtime),r.size&&(t.tools=I(r)),e.route&&(t.route=e.route),e.policy&&(t.policy=e.policy),e.metadata&&(t.metadata=e.metadata),e.task&&(t.task=e.task),e.resumable&&(t.resumable=!0),e.maxDurationMs&&(t.maxDurationMs=e.maxDurationMs);let o=await b(this.#e,{method:"POST",path:"/runs",body:t,accept:"text/event-stream",signal:e.signal,retry:"unsent"});return new k({config:this.#e,response:o,user:e.user,tools:r,approve:e.approve,onWarning:this.#r,signal:e.signal})}async request(e,r,t={}){return R(this.#e,{method:e,path:r,...t})}};function v(n){if(typeof process>"u")return;let e=process.env?.[n];return e||void 0}function pe(){let n=globalThis;return typeof n.window=="object"&&typeof n.window?.document=="object"}var ge=300;function fe(n){return[...new Uint8Array(n)].map(e=>e.toString(16).padStart(2,"0")).join("")}function me(n,e){if(n.length!==e.length)return!1;let r=0;for(let t=0;t<n.length;t++)r|=n.charCodeAt(t)^e.charCodeAt(t);return r===0}async function he(n,e,r,t={}){let o=Object.fromEntries((e??"").split(",").map(f=>{let g=f.indexOf("=");return[f.slice(0,g).trim(),f.slice(g+1).trim()]})),s=Number(o.t),i=o.v1??"",u=f=>new a({code:"unauthorized",status:401,message:f});if(!Number.isFinite(s)||!i)throw u("Missing or malformed Soba-Signature.");let d=Math.floor((t.now??Date.now())/1e3);if(Math.abs(d-s)>(t.toleranceSeconds??ge))throw u("This delivery is too old to accept.");let h=await globalThis.crypto.subtle.importKey("raw",new TextEncoder().encode(r),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),l=fe(await globalThis.crypto.subtle.sign("HMAC",h,new TextEncoder().encode(`${s}.${n}`)));if(!me(l,i))throw u("The Soba-Signature does not match.");let p;try{p=JSON.parse(n)}catch{throw new a({code:"invalid_request",message:"The delivery is not JSON."})}let m=p;if(m.type!=="run.event"&&m.type!=="run.tool_call"||typeof m.run_id!="string")throw new a({code:"invalid_request",message:"Not a Soba run delivery."});return m}async function ye(n,e){if(n.type!=="run.tool_call")return null;let{call_id:r,name:t,input:o}=n.data,s=S(e.tools).get(t);if(!s)return{result:`Unknown tool: ${t}`,is_error:!0};try{let i=await s.execute(o??{},{runId:n.run_id,user:e.user??"",callId:r,signal:AbortSignal.timeout(25e3)});return{result:x(i)}}catch(i){return{result:T(i),is_error:!0}}}export{j as DEFAULT_BASE_URL,W as DEFAULT_WEB_BASE_URL,M as METERED_CLASSES,k as Run,P as Soba,a as SobaError,ae as TOOL_SLUGS,E as VERSION,ye as handleRunWebhook,ie as isCostClass,se as isMetered,_ as isTerminal,ce as tool,he as verifyWebhook};
1
+ var he="soba-e2e-wrap-v1",ye="soba-e2e-request-v1",U="e1.",x=new TextEncoder,be=new TextDecoder;async function Q(){let t=crypto.getRandomValues(new Uint8Array(32));return{raw:t,key:await we(t)}}async function V(t,e,r){let n=await Promise.all(r.map(async({publicKey:i})=>{let a=await crypto.subtle.generateKey({name:"X25519"},!0,["deriveBits"]),c=_(new Uint8Array(await crypto.subtle.exportKey("raw",a.publicKey))),m=await crypto.subtle.importKey("raw",O(i),{name:"X25519"},!1,[]),p=await crypto.subtle.deriveBits({name:"X25519",public:m},a.privateKey,256),g=await crypto.subtle.importKey("raw",p,"HKDF",!1,["deriveKey"]),f=await crypto.subtle.deriveKey({name:"HKDF",hash:"SHA-256",salt:x.encode(`${c}.${i}`),info:x.encode(he)},g,{name:"AES-GCM",length:256},!1,["encrypt"]),u=crypto.getRandomValues(new Uint8Array(12)),d=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:u},f,t.raw));return{kid:i,epk:c,iv:_(u),ct:_(d)}})),o=crypto.getRandomValues(new Uint8Array(12)),s=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:o,additionalData:x.encode(ye)},t.key,x.encode(JSON.stringify(e))));return{v:1,keys:n,iv:_(o),ct:_(s)}}async function N(t,e){let r=crypto.getRandomValues(new Uint8Array(12)),n=new Uint8Array(await crypto.subtle.encrypt({name:"AES-GCM",iv:r,additionalData:x.encode("soba-e2e-down")},t.key,x.encode(JSON.stringify(e===void 0?null:e))));return`${U}${_(r)}.${_(n)}`}async function L(t,e){if(!e.startsWith(U))throw new Error("not a sealed frame");let[r,n]=e.slice(U.length).split(".");if(!r||!n)throw new Error("not a sealed frame");let o=await crypto.subtle.decrypt({name:"AES-GCM",iv:O(r),additionalData:x.encode("soba-e2e-up")},t.key,O(n));return JSON.parse(be.decode(o))}function X(t){if(!t||typeof t!="object"||Array.isArray(t))return;let e=t.$sealed;return typeof e=="string"&&e.startsWith(U)?e:void 0}async function W(t){let r=[...new Uint8Array(await crypto.subtle.digest("SHA-256",O(t))).subarray(0,16)].map(n=>n.toString(16).padStart(2,"0")).join("");return r.match(/.{4}/g)?.join(" ")??r}function Y(t){if(!t||typeof t!="object")return!1;let e=t;return typeof e.machine=="string"&&typeof e.publicKey=="string"&&/^[A-Za-z0-9_-]{43}$/.test(e.publicKey)}function we(t){return crypto.subtle.importKey("raw",t,"AES-GCM",!1,["encrypt","decrypt"])}function _(t){let e="";for(let r of t)e+=String.fromCharCode(r);return btoa(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function O(t){let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r}var l=class extends Error{code;type;status;retryable;retryAfterMs;runId;constructor(e){super(e.message,e.cause===void 0?void 0:{cause:e.cause}),this.name="SobaError",this.code=e.code,this.type=e.type??e.code,this.status=e.status,this.retryable=e.retryable??ke.has(e.code),this.retryAfterMs=e.retryAfterMs,this.runId=e.runId}},ke=new Set(["rate_limited","server_error","connection","timeout","stream_truncated"]),ve={400:"invalid_request",401:"unauthorized",402:"payment_required",403:"forbidden",404:"not_found",409:"no_compute",422:"user_required",429:"rate_limited"};function Se(t){let e=ve[t];return e||(t>=500?"server_error":t>=400?"invalid_request":"unknown")}var Z=new WeakSet;function ee(t){return Z.has(t)}async function te(t){let e=t.status,r="";try{r=await t.text()}catch{}let n=Re(r),o=new l({code:n?.code??Se(e),type:n?.type,message:n?.message??_e(e,t.statusText,r),status:e,retryAfterMs:xe(t.headers.get("retry-after")),runId:t.headers.get("soba-run-id")??void 0});return!n&&(e===502||e===503||e===504)&&Z.add(o),o}function Re(t){if(!t)return null;let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object")return null;let r=e.error;if(!r||typeof r!="object")return null;let n=r;return{message:typeof n.message=="string"&&n.message?n.message:void 0,type:typeof n.type=="string"&&n.type?n.type:void 0,code:Te.has(n.code)?n.code:void 0}}var Te=new Set(["invalid_request","user_required","unauthorized","payment_required","forbidden","not_found","no_compute","unknown_run","not_resumable","machine_gone","rate_limited","server_error","connection","timeout","stream_truncated","run_failed","canceled","unknown"]);function _e(t,e,r){let n=r.trim().slice(0,200),o=n?`: ${n}`:"";return`Soba returned ${t}${e?` ${e}`:""}${o}`}function xe(t){if(!t)return;let e=Number(t);if(Number.isFinite(e)&&e>=0)return Math.round(e*1e3);let r=Date.parse(t);if(!Number.isNaN(r))return Math.max(0,r-Date.now())}function w(t){if(t instanceof l)return t;let e=t;return e?.name==="AbortError"||e?.name==="TimeoutError"?new l({code:"canceled",message:e.message||"The request was aborted.",retryable:!1,cause:t}):new l({code:"connection",message:e?.message?`Could not reach Soba: ${e.message}`:"Could not reach Soba.",cause:t})}var j="0.0.14";var Ae=new Set(["ECONNREFUSED","ENOTFOUND","EAI_AGAIN"]);function B(t){if(t.code==="rate_limited")return!0;if(t.code!=="connection")return!1;let e=t.cause;for(let r=0;e&&r<4;r++){let n=e.code;if(typeof n=="string"&&Ae.has(n))return!0;e=e.cause}return!1}var Ee=8e3,Ce=3e4;async function T(t,e){let r=Ue(t.baseURL,e.path,e.query),n=e.retry===!1?1:Math.max(0,t.maxRetries)+1,o,s=i=>i.retryable&&(e.retry!=="unsent"||B(i));for(let i=0;i<n;i++){i>0&&await G(Oe(i,o),e.signal);let a=new AbortController,c=C(e.signal,a),m=setTimeout(()=>{a.abort(new l({code:"timeout",message:`Soba did not answer within ${t.connectTimeoutMs}ms.`}))},t.connectTimeoutMs),p;try{p=await t.fetch(r,{method:e.method,headers:Pe(t,e),body:e.body===void 0?void 0:JSON.stringify(e.body),signal:a.signal})}catch(g){if(c(),o=w(a.signal.aborted?a.signal.reason??g:g),!s(o)||i===n-1)throw o;continue}finally{clearTimeout(m)}if(p.ok)return p;if(c(),o=await te(p),!s(o)||i===n-1)throw o}throw o??new l({code:"unknown",message:"The request failed with no error."})}async function S(t,e){let r=await T(t,{accept:"application/json",...e}),n=await r.text();if(n)try{return JSON.parse(n)}catch(o){throw new l({code:"server_error",message:`Soba returned a body that is not JSON: ${n.slice(0,200)}`,status:r.status,cause:o})}}function Pe(t,e){let r={authorization:`Bearer ${t.apiKey}`,accept:e.accept??"application/json","user-agent":Ie(),...t.headers};return e.body!==void 0&&(r["content-type"]="application/json"),r}function Ie(){let t=typeof process>"u"?"":` node/${process.versions?.node??"?"}`;return`soba-sdk/${j}${t}`}function Ue(t,e,r){let n=t.replace(/\/+$/,""),o=new URL(`${n}${e.startsWith("/")?e:`/${e}`}`);for(let[s,i]of Object.entries(r??{}))i!==void 0&&o.searchParams.set(s,String(i));return o.toString()}function Oe(t,e){if(e?.retryAfterMs!==void 0)return Math.min(e.retryAfterMs,Ce);let r=Math.min(Ee,500*2**(t-1));return Math.round(r*(.5+Math.random()/2))}function G(t,e){return new Promise((r,n)=>{if(e?.aborted)return n(w(e.reason));let o=setTimeout(()=>{e?.removeEventListener("abort",s),r()},t);function s(){clearTimeout(o),n(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 r=()=>e.abort(t.reason);return t.addEventListener("abort",r,{once:!0}),()=>t.removeEventListener("abort",r)}var Me=5*60*1e3,ne=25,qe=1e3,Ke=100,M=class{#e;#s;#r;#i=null;#o=0;#t=null;#n=[];#a=null;constructor(e){this.#e=e.http,this.#s=e.onWarning,this.#r=e.off}async prime(){if(!this.#r)return this.#t??=S(this.#e,{method:"GET",path:"/fallback",retry:!1}).then(e=>{this.#i={enabled:e?.enabled===!0,providers:(e?.providers??[]).map(re).filter(oe)},this.#o=Date.now()}).catch(()=>{}).finally(()=>{this.#t=null}),this.#t}refreshSoon(){this.#r||Date.now()-this.#o<Me||this.prime()}get pending(){return this.#n.length}canServe(e,r){if(this.#r)return!1;let n=w(e);return!B(n)&&!ee(n)||n.code==="rate_limited"?!1:this.#c(r).length>0}serve(e,r){let n=new AbortController,o=C(r,n),s=n.signal,i=new Map,a=new Map,c=u=>{let d=i.get(u.callId);d?(i.delete(u.callId),d(u)):a.set(u.callId,u)},m=u=>new Promise((d,b)=>{let y=a.get(u);if(y)return a.delete(u),d(y);i.set(u,d),s.addEventListener("abort",()=>b(w(s.reason)),{once:!0})}),p=this.#c(e.route),g=new TextEncoder,f=new ReadableStream({start:u=>{let d=b=>{try{u.enqueue(g.encode(`data: ${JSON.stringify(b)}
2
+
3
+ `))}catch{}};this.#d(e,p,d,m,s).catch(b=>d({type:"error",message:w(b).message})).finally(()=>{o();try{u.close()}catch{}})},cancel:u=>n.abort(u)});return{response:new Response(f,{status:200,headers:{"content-type":"text/event-stream","soba-run-id":e.runId}}),deliver:c,stop:u=>n.abort(u)}}async flush(){return this.#a??=this.#u().finally(()=>{this.#a=null}),this.#a}flushSoon(){this.#n.length&&this.flush()}async#u(){for(;this.#n.length;){let e=this.#n.slice(0,Ke),r;try{r=(await S(this.#e,{method:"POST",path:"/usage/backfill",body:{runs:e}}))?.results??[]}catch{return}let n=new Set(r.filter(s=>s.outcome==="failed").map(s=>s.id)),o=new Set(e.map(s=>s.id));for(let s of r)s.outcome==="rejected"&&this.#s("Soba would not record a run served while it was unreachable.",s);if(this.#n=[...e.filter(s=>n.has(s.id)),...this.#n.filter(s=>!o.has(s.id))],n.size===e.length)return}}#l(e){this.#n.push(e),this.#n.length>qe&&(this.#n.shift(),this.#s("Dropped the oldest unreported fallback run: too many waiting for Soba."))}#c(e){let r=this.#i??De();return r?.enabled?r.providers.filter(n=>se(n)&&(!e?.allow||e.allow.includes(n.costClass))):[]}async#d(e,r,n,o,s){let i=new Date,a="None of your providers could be reached.";for(let c of r){let m=Fe(c,e.model),p={inputTokens:0,outputTokens:0,cacheReadTokens:0,cacheWriteTokens:0},g=!1,f=(u,d)=>this.#l({id:e.runId,user:e.user,supplier:c.id,model:m.model,input_tokens:p.inputTokens,output_tokens:p.outputTokens,cache_read_tokens:p.cacheReadTokens,cache_write_tokens:p.cacheWriteTokens,started_at:i.toISOString(),ended_at:new Date().toISOString(),status:u,...d?{error:d}:{},...e.task?{task:e.task}:{}});try{n({type:"status",tier:c.costClass,message:`Soba can't be reached, so ${c.name} is answering.`});let u=$e(e);for(let b=0;;b++){if(b>=ne)throw new Error(`Stopped after ${ne} turns of tool calls.`);let y=await Ne(this.#e.fetch,c,m,u,e.tools,s,k=>{g=!0,n({type:"delta",text:k})});if(p.inputTokens+=y.inputTokens,p.outputTokens+=y.outputTokens,p.cacheReadTokens+=y.cacheReadTokens,!y.toolCalls.length)break;g=!0,u.push({role:"assistant",content:y.text||null,tool_calls:y.toolCalls});for(let k of y.toolCalls)n({type:"tool_call",callId:k.id,name:k.function.name,input:Le(k.function.arguments)});for(let k of y.toolCalls){let v=await o(k.id);u.push({role:"tool",tool_call_id:k.id,content:typeof v.result=="string"?v.result:JSON.stringify(v.result)})}}let d={model:m.model,provider:c.id,costClass:c.costClass,...p,webSearches:0};n({type:"usage",usage:d}),n({type:"done",usage:d}),f("done");return}catch(u){if(s.aborted)throw f("error","cancelled"),w(s.reason);if(a=`${c.name}: ${w(u).message}`,g)throw f("error",a),new l({code:"run_failed",message:a,retryable:!1})}}throw new l({code:"no_compute",message:a,retryable:!1})}};function re(t){if(!t?.id||!t.base_url||!t.key_env||!t.cost_class)return null;let e=(t.models??[]).filter(r=>typeof r?.model=="string"&&r.model).map(r=>({model:r.model,alias:r.alias??null,maxOutputTokens:r.max_output_tokens??null}));return e.length?{id:t.id,name:t.name??t.id,baseUrl:t.base_url,keyEnv:t.key_env,costClass:t.cost_class,...t.api_key?{apiKey:t.api_key}:{},models:e}:null}var oe=t=>t!==null;function De(){let t=ie("SOBA_FALLBACK");if(!t)return null;try{let e=atob(t.replace(/-/g,"+").replace(/_/g,"/")),n=(JSON.parse(e).providers??[]).map(re).filter(oe);return n.length?{enabled:!0,providers:n}:null}catch{return null}}function se(t){return ie(t.keyEnv)??t.apiKey}function Fe(t,e){let r=t.models,n=e?.startsWith(`@${t.id}/`)?e.slice(t.id.length+2):e,o=r.find(s=>s.model===n||s.alias===n);return o||(e==="large"||e==="best"?r[r.length-1]:r[0])}function $e(t){let e=[];t.system&&e.push({role:"system",content:t.system});for(let r of t.messages)r.role==="user"&&r.images?.length?e.push({role:"user",content:[{type:"text",text:r.content},...r.images.map(n=>({type:"image_url",image_url:{url:`data:${n.mediaType};base64,${n.data}`}}))]}):r.role==="user"?e.push({role:"user",content:r.content}):e.push({role:"assistant",content:r.content});return e}async function Ne(t,e,r,n,o,s,i){let a=await t(`${e.baseUrl.replace(/\/+$/,"")}/chat/completions`,{method:"POST",headers:{authorization:`Bearer ${se(e)}`,"content-type":"application/json",accept:"text/event-stream"},body:JSON.stringify({model:r.model,messages:n,stream:!0,stream_options:{include_usage:!0},...r.maxOutputTokens?{max_tokens:r.maxOutputTokens}:{},...o.length?{tools:o.map(f=>({type:"function",function:{name:f.name,description:f.description,parameters:f.inputSchema}}))}:{}}),signal:s});if(!a.ok||!a.body){let f=await a.text().catch(()=>"");throw new Error(`${a.status} ${f.slice(0,300)}`.trim())}let c={text:"",toolCalls:[],inputTokens:0,outputTokens:0,cacheReadTokens:0},m=a.body.getReader(),p=new TextDecoder,g="";try{for(;;){let f=await m.read();if(f.done)break;for(g+=p.decode(f.value,{stream:!0});;){let u=g.indexOf(`
4
+ `);if(u===-1)break;let d=g.slice(0,u).trim();if(g=g.slice(u+1),!d.startsWith("data:"))continue;let b=d.slice(5).trim();if(!b||b==="[DONE]")continue;let y;try{y=JSON.parse(b)}catch{continue}y.usage&&(c.inputTokens=y.usage.prompt_tokens??0,c.outputTokens=y.usage.completion_tokens??0,c.cacheReadTokens=y.usage.prompt_tokens_details?.cached_tokens??0,c.inputTokens-=c.cacheReadTokens);let k=y.choices?.[0]?.delta;k?.content&&(c.text+=k.content,i(k.content));for(let v of k?.tool_calls??[]){let F=v.index??c.toolCalls.length;c.toolCalls[F]??={id:v.id??`call_${F}`,type:"function",function:{name:"",arguments:""}};let $=c.toolCalls[F];v.id&&($.id=v.id),v.function?.name&&($.function.name+=v.function.name),v.function?.arguments&&($.function.arguments+=v.function.arguments)}}}}finally{m.cancel().catch(()=>{})}return c.toolCalls=c.toolCalls.filter(f=>f?.function.name),c}function Le(t){if(!t)return{};try{return JSON.parse(t)}catch{return{}}}function ie(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}var ae=["open-weights","frontier"];function We(t){return ae.includes(t)}function je(t){return t==="user-hardware"||t==="user-subscription"||t==="user-api-key"||t==="open-weights"||t==="frontier"}function H(t){return t.type==="done"||t.type==="error"}var Be=["search","fetch","read","write","edit","bash","files","agent","todo","think","sources","tool"];var de=new Set(["delta","thinking","status","done","error"]);function J(t){let e;try{e=JSON.parse(t)}catch{return null}if(!e||typeof e!="object"||Array.isArray(e))return null;let r=e,n=h(r.runId);if(typeof r.type=="string"&&de.has(r.type)){let o=q(r);return o?{kind:"event",runId:n,event:o,...ue(r)}:null}switch(r.type){case"event":{if(!r.event||typeof r.event!="object")return null;let o=q(r.event);return o?{kind:"event",runId:n,event:o,...ue(r.event)}:null}case"usage":{let o=pe(r.usage);return o?{kind:"usage",runId:n,usage:o}:null}case"tool_call":{let o=h(r.callId),s=h(r.name);return!o||!s?null:{kind:"tool_call",runId:n,callId:o,name:s,input:r.input,...r.answered===!0?{answered:!0}:{}}}case"approval_request":{let o=h(r.approvalId),s=h(r.tool);return!o||!s?null:{kind:"approval",runId:n,approvalId:o,tool:s,input:r.input,cwd:h(r.cwd),...r.answered===!0?{answered:!0}:{}}}default:return null}}function ue(t){let e=t.sealed;return typeof e=="string"&&e.length>0?{sealed:e}:{}}function q(t){let e=typeof t.type=="string"&&de.has(t.type)?t.type:null;if(!e)return null;let r={type:e},n=h(t.text);n!==void 0&&(r.text=n);let o=h(t.message);o!==void 0&&(r.message=o);let s=h(t.tool);s!==void 0&&(r.tool=s);let i=h(t.tier);i!==void 0&&(r.tier=i);let a=pe(t.usage);a&&(r.usage=a);let c=h(t.reason);c!==void 0&&(r.reason=c),typeof t.retryable=="boolean"&&(r.retryable=t.retryable);let m=t.turn&&typeof t.turn=="object"?h(t.turn.text):void 0;m!==void 0&&(r.turn={text:m});let p=h(t.session);p!==void 0&&(r.session=p);let g=h(t.toolInput);g!==void 0&&(r.toolInput=g);let f=Ge(t.git);return f&&(r.git=f),(t.state==="interrupted"||t.state==="resumed")&&(r.state=t.state),r}function Ge(t){if(!t||typeof t!="object")return null;let e=t,r=h(e.branch);return!r||!Array.isArray(e.files)||!Array.isArray(e.commits)?null:{branch:r,base:h(e.base)??"",head:h(e.head)??"",ahead:R(e.ahead),behind:R(e.behind),files:e.files.filter(n=>!!n&&typeof n=="object"&&typeof n.path=="string").map(n=>({path:n.path,status:n.status==="A"||n.status==="D"||n.status==="R"?n.status:"M",added:R(n.added),removed:R(n.removed)})),commits:e.commits.filter(n=>!!n&&typeof n=="object").map(n=>({sha:h(n.sha)??"",subject:h(n.subject)??""})),dirty:e.dirty===!0}}function pe(t){if(!t||typeof t!="object")return null;let e=t,r={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)},n=h(e.costClass);n!==void 0&&(r.costClass=n);let o=h(e.provider);return o!==void 0&&(r.provider=o),typeof e.costMicros=="number"&&Number.isFinite(e.costMicros)&&(r.costMicros=e.costMicros),r}function h(t){return typeof t=="string"&&t.length>0?t:void 0}function R(t){return typeof t=="number"&&Number.isFinite(t)?t:0}async function*fe(t){let e=t.body;if(!e)throw new l({code:"connection",message:"The run response arrived with no body to stream.",status:t.status});let r=t.headers.get("content-type")??"",n=r.includes("ndjson")||r.includes("jsonlines"),o=e.getReader(),s=new TextDecoder,i="",a=[],c,m=p=>c===void 0?p:{...p,seq:c};try{for(;;){let g=await o.read();if(g.done)break;for(i+=s.decode(g.value,{stream:!0});;){let f=i.indexOf(`
5
+ `);if(f===-1)break;let u=ce(i.slice(0,f));if(i=i.slice(f+1),n){let d=u.trim()?J(u):null;d&&(yield d);continue}if(u===""){let d=a.join(`
6
+ `);if(a=[],d==="[DONE]")return;let b=d?J(d):null;b&&(yield m(b)),c=void 0;continue}if(u.startsWith("id:")){let d=Number(u.slice(3).trim());c=Number.isInteger(d)&&d>0?d:void 0;continue}le(u,a)}}!n&&i&&le(ce(i),a);let p=n?i.trim():a.join(`
7
+ `);if(p&&p!=="[DONE]"){let g=J(p);g&&(yield n?g:m(g))}}finally{o.cancel().catch(()=>{})}}function le(t,e){if(t.startsWith(":"))return;let r=t.indexOf(":");if(r===-1||t.slice(0,r)!=="data")return;let n=t.slice(r+1);e.push(n.startsWith(" ")?n.slice(1):n)}function ce(t){return t.endsWith("\r")?t.slice(0,-1):t}function He(t){return t}function E(t){let e=new Map;for(let r of t??[]){if(!r?.name)throw new l({code:"invalid_request",message:"Every tool needs a name."});if(typeof r.execute!="function")throw new l({code:"invalid_request",message:`Tool "${r.name}" has no execute function. A tool Soba cannot call is not a tool.`});if(e.has(r.name))throw new l({code:"invalid_request",message:`Two tools are named "${r.name}". Tool names must be unique within a run.`});e.set(r.name,r)}return e}function K(t){return[...t.values()].map(e=>({name:e.name,description:e.description??"",inputSchema:e.inputSchema??{type:"object"}}))}function P(t){if(t===void 0)return null;if(typeof t=="string")return t;try{return JSON.parse(JSON.stringify(t))}catch{return String(t)}}function I(t){return t instanceof Error?t.message||t.name:typeof t=="string"?t:String(t)}var Je=9e4,A=class{#e;#s;#r;#i=!1;#o;#t;#n=new AbortController;#a=new AbortController;#u=new Set;#l;constructor(e){this.#t=e,this.#e=e.response.headers.get("soba-run-id")??"",this.#o=e.after??0,this.#l=C(e.signal,this.#n)}get cursor(){return this.#o}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.#s}get usage(){return this.#r}[Symbol.asyncIterator](){return this.#d()}async text(){let e="";for await(let r of this)if(r.type==="delta"&&r.text&&(e+=r.text),r.type==="error")throw new l({code:"run_failed",message:r.message??"The run ended with an error.",runId:this.#e,retryable:!1});return e}async cancel(){if(this.#n.abort(new l({code:"canceled",message:"The run was cancelled."})),this.#a.abort(new l({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#c(e){let r=Date.now()+Je,n=e;for(let o=0;Date.now()<r;o++){if(this.#n.signal.aborted)throw w(this.#n.signal.reason);o>0&&await G(Math.min(1e3*o,5e3),this.#n.signal);try{return await T(this.#t.config,{method:"GET",path:`/runs/${encodeURIComponent(this.#e)}/stream`,query:{after:this.#o},accept:"text/event-stream",signal:this.#n.signal,retry:!1})}catch(s){if(n=w(s),!["server_error","connection","timeout","rate_limited"].includes(n.code))break}}throw new l({code:"stream_truncated",message:`The run stream ended without a \`done\` or \`error\` event, and reading on failed: ${n.message}`,runId:this.#e,cause:n})}async*#d(){if(this.#i)throw new l({code:"invalid_request",message:"This run has already been consumed. A run's events can only be read once.",runId:this.#e});this.#i=!0;let e=!1;try{let r=this.#t.response;for(;;){for await(let o of fe(r)){if(o.runId&&!this.#e&&(this.#e=o.runId),o.seq!==void 0&&(this.#o=o.seq),o.kind==="event"){let s=this.#t.runKey?await this.#h(o):o.event;if(!s)continue;if(s.tier&&(this.#s=s.tier),s.usage&&(this.#r=s.usage),e=H(s),yield s,e)return;continue}if(o.kind==="usage"){this.#r=o.usage;continue}this.#m(this.#b(o))}let n=new l({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 n;r=await this.#c(n)}}finally{e||this.#a.abort(new l({code:"canceled",message:"The run ended before this tool finished."})),await Promise.allSettled([...this.#u]),this.#n.abort(),this.#l()}}#m(e){this.#u.add(e),e.finally(()=>this.#u.delete(e)).catch(()=>{})}async#h(e){let r=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 n=await L(r,e.sealed);if(!n||typeof n!="object")throw new Error("not an object");return q({...e.event,...n})}catch(n){return this.#t.onWarning("Dropped an event on an encrypted run that would not open.",n),null}}async#y(e){let r=this.#t.runKey;if(!r)return{value:e};let n=X(e);if(n)try{return{value:await L(r,n)}}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 r=await this.#y(e.input);if(!r){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:r.value});let{input:n,cwd:o}=r.value??{};return this.#g({...e,input:n,...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 r=this.#t.tools.get(e.name),n,o=!1;if(!r)n=`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{n=await r.execute(e.input,i)}catch(a){n=I(a),o=!0}}if(this.#t.local){this.#t.local.deliver({callId:e.callId,result:P(n),isError:o});return}let s=P(n);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 r="deny",n;if(!this.#t.approve)n="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),r=await this.#t.approve(o)==="allow"?"allow":"deny"}catch(o){n=I(o)}await this.#p(`/runs/${encodeURIComponent(this.#e)}/approval`,{approvalId:e.approvalId,decision:r,...n?{reason:n}:{},...this.#t.runKey?{sealed:await N(this.#t.runKey,{approvalId:e.approvalId,decision:r})}:{}})}async#p(e,r){if(!this.#e){this.#t.onWarning("Soba sent a frame before the run had an id, so it could not be answered.",r);return}try{await(await T(this.#t.config,{method:"POST",path:e,body:r})).text()}catch(n){this.#t.onWarning(`Could not deliver an answer to ${e}.`,w(n))}}};var ge="https://api.soba.so/v1",me="https://soba.so/v1",ze=3e4,Qe=2,z=class{#e;#s;#r;#i;#o;fallback;users;usage;connect;plans;runs;ops;terminals;constructor(e={}){let r=e.apiKey??D("SOBA_KEY")??D("SOBA_API_KEY");if(!r)throw new l({code:"unauthorized",message:"No Soba API key. Pass `apiKey`, or set SOBA_KEY. Keys are shaped sk_soba_<id>.<secret> and come from your dashboard."});if(Ve()&&!e.dangerouslyAllowBrowser)throw new l({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.#i=e.encrypt===!0?{}:e.encrypt?e.encrypt:void 0,this.#e={apiKey:r,baseURL:e.baseURL??D("SOBA_BASE_URL")??ge,headers:e.headers??{},fetch:e.fetch??globalThis.fetch,connectTimeoutMs:e.connectTimeoutMs??ze,maxRetries:e.maxRetries??Qe},this.#s={...this.#e,baseURL:e.webBaseURL??D("SOBA_WEB_URL")??me},typeof this.#e.fetch!="function")throw new l({code:"invalid_request",message:"No global fetch. Run on Node 22 or newer, or pass your own `fetch`."});let n=new M({http:this.#e,onWarning:this.#r,off:e.fallback===!1});this.#o=n,this.fallback={prime:()=>n.prime(),flush:()=>n.flush(),get pending(){return n.pending}},this.users={get:o=>this.request("GET",`/users/${encodeURIComponent(o)}`),compute:async o=>(await this.request("GET",`/users/${encodeURIComponent(o)}/compute`)).machines,setQuantity:(o,s,i)=>S(this.#s,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/quantity`,body:{quantity:i}}),check:(o,s,i)=>S(i?.use?{...this.#s,maxRetries:0}:this.#s,{method:"POST",path:`/end_users/${encodeURIComponent(o)}/features/${encodeURIComponent(s)}/check`,body:i?.use?{use:i.use}:{}}),track:(o,s,i=1)=>S({...this.#s,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 l({code:"user_required",status:422,message:"`user` is required."});if(this.#i)throw new l({code:"invalid_request",message:"Detached runs cannot be encrypted end to end yet. Use soba.run() on a client with `encrypt`, or a client without it."});let s=E(o.tools),i={user:o.user,model:o.model??"auto",detached:!0};o.webhook&&(i.webhook=o.webhook),o.prompt&&(i.prompt=o.prompt),o.messages?.length&&(i.messages=o.messages),o.system&&(i.system=o.system),o.runtime&&(i.runtime=o.runtime),s.size&&(i.tools=K(s)),o.route&&(i.route=o.route),o.policy&&(i.policy=o.policy),o.metadata&&(i.metadata=o.metadata),o.task&&(i.task=o.task),o.surface&&(i.surface=o.surface),o.maxDurationMs&&(i.maxDurationMs=o.maxDurationMs),o.title&&(i.title=o.title),o.worktree&&(i.worktree=o.worktree),o.resume&&(i.resume=o.resume);let a=await S(this.#e,{method:"POST",path:"/runs",body:i,retry:"unsent"}),c={id:a.id};return a.stream&&(c.stream={url:a.stream.url,token:a.stream.token,expiresAt:a.stream.expires_at}),o.answerTools==="here"&&(c.answered=(async()=>{let m=await this.runs.attach(a.id,{user:o.user,tools:o.tools??[]});for await(let p of m);})().catch(m=>this.#r("Answering this run's tool calls stopped.",m))),c},attach:async(o,s)=>{if(!s.user)throw new l({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 A({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 l({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 l({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 l({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 l({code:"invalid_request",status:400,message:"A run needs a `prompt` or a non-empty `messages`."});let r=E(e.tools),n={user:e.user,model:e.model??"auto"};e.prompt&&(n.prompt=e.prompt),e.messages?.length&&(n.messages=e.messages),e.system&&(n.system=e.system),e.runtime&&(n.runtime=e.runtime),r.size&&(n.tools=K(r)),e.route&&(n.route=e.route),e.policy&&(n.policy=e.policy),e.metadata&&(n.metadata=e.metadata),e.task&&(n.task=e.task),n.resumable=e.resumable?!0:"restarts",e.maxDurationMs&&(n.maxDurationMs=e.maxDurationMs);let o,s;try{if(this.#i){let i=await this.#t(e.user,e.signal);if(i.length===0)throw new l({code:"no_compute",status:409,message:"None of this person's machines can open an encrypted run, so nothing was sent to Soba. Serve it with your own provider.",retryable:!1});s=await Q(),n.sealed=await V(s,{...n.prompt!==void 0?{prompt:n.prompt}:{},...n.messages!==void 0?{messages:n.messages}:{},...n.system!==void 0?{system:n.system}:{},...n.tools!==void 0?{tools:n.tools}:{}},i),delete n.prompt,delete n.messages,delete n.system,delete n.tools}o=await T(this.#e,{method:"POST",path:"/runs",body:n,accept:"text/event-stream",signal:e.signal,retry:"unsent"})}catch(i){if(!this.#o.canServe(i,e.route))throw i;let a=this.#o.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:K(r),task:e.task},e.signal);return this.#r("Soba could not be reached; your own provider is answering this run.",i),new A({config:this.#e,response:a.response,user:e.user,tools:r,approve:e.approve,onWarning:this.#r,signal:e.signal,local:{deliver:a.deliver,cancel:a.stop}})}return this.#o.refreshSoon(),this.#o.flushSoon(),new A({config:this.#e,response:o,user:e.user,tools:r,approve:e.approve,onWarning:this.#r,signal:e.signal,...s?{runKey:s}:{}})}async#t(e,r){let n=await S(this.#e,{method:"GET",path:"/keys",query:{user:e},...r?{signal:r}:{}}),o=(Array.isArray(n.data)?n.data:[]).filter(Y),s=this.#i?.trust;if(!s)return o;let i=[];for(let a of o)await s({...a,fingerprint:await W(a.publicKey)})&&i.push(a);return i}async request(e,r,n={}){return S(this.#e,{method:e,path:r,...n})}};function D(t){if(typeof process>"u")return;let e=process.env?.[t];return e||void 0}function Ve(){let t=globalThis;return typeof t.window=="object"&&typeof t.window?.document=="object"}var Xe=300;function Ye(t){return[...new Uint8Array(t)].map(e=>e.toString(16).padStart(2,"0")).join("")}function Ze(t,e){if(t.length!==e.length)return!1;let r=0;for(let n=0;n<t.length;n++)r|=t.charCodeAt(n)^e.charCodeAt(n);return r===0}async function et(t,e,r,n={}){let o=Object.fromEntries((e??"").split(",").map(u=>{let d=u.indexOf("=");return[u.slice(0,d).trim(),u.slice(d+1).trim()]})),s=Number(o.t),i=o.v1??"",a=u=>new l({code:"unauthorized",status:401,message:u});if(!Number.isFinite(s)||!i)throw a("Missing or malformed Soba-Signature.");let c=Math.floor((n.now??Date.now())/1e3);if(Math.abs(c-s)>(n.toleranceSeconds??Xe))throw a("This delivery is too old to accept.");let m=await globalThis.crypto.subtle.importKey("raw",new TextEncoder().encode(r),{name:"HMAC",hash:"SHA-256"},!1,["sign"]),p=Ye(await globalThis.crypto.subtle.sign("HMAC",m,new TextEncoder().encode(`${s}.${t}`)));if(!Ze(p,i))throw a("The Soba-Signature does not match.");let g;try{g=JSON.parse(t)}catch{throw new l({code:"invalid_request",message:"The delivery is not JSON."})}let f=g;if(f.type!=="run.event"&&f.type!=="run.tool_call"||typeof f.run_id!="string")throw new l({code:"invalid_request",message:"Not a Soba run delivery."});return f}async function tt(t,e){if(t.type!=="run.tool_call")return null;let{call_id:r,name:n,input:o}=t.data,s=E(e.tools).get(n);if(!s)return{result:`Unknown tool: ${n}`,is_error:!0};try{let i=await s.execute(o??{},{runId:t.run_id,user:e.user??"",callId:r,signal:AbortSignal.timeout(25e3)});return{result:P(i)}}catch(i){return{result:I(i),is_error:!0}}}export{ge as DEFAULT_BASE_URL,me as DEFAULT_WEB_BASE_URL,ae as METERED_CLASSES,A as Run,z as Soba,l as SobaError,Be as TOOL_SLUGS,j as VERSION,W as fingerprint,tt as handleRunWebhook,je as isCostClass,We as isMetered,H as isTerminal,He as tool,et as verifyWebhook};
@@ -130,6 +130,11 @@ export interface RunPolicy {
130
130
  allowNetwork?: string[];
131
131
  /** The owner's own browser, every action approved live. Only if their machine grants it. */
132
132
  browser?: boolean;
133
+ /** Skills the owner added to Soba, by name: `["pdf"]`. Asked for once, on their machine. */
134
+ skills?: string[];
135
+ /** Services the owner signed in to in Soba, with what this run does: `["gmail:read"]`.
136
+ * Every write stops for a yes on their machine. */
137
+ connections?: string[];
133
138
  }
134
139
  /**
135
140
  * WHICH ECONOMICS a run may use. You declare intent, not a runtime, which is
@@ -130,6 +130,14 @@ export interface PlanListItem {
130
130
  /** About how many runs a credit plan's allowance buys at this app's typical
131
131
  * run cost: "About 265 tasks a month". Null when it cannot be said. */
132
132
  estimated_tasks?: number | null;
133
+ /** A credit plan's top-up packs, in order: "1,000 credits for $10".
134
+ * Listed only; nothing sells one yet. Optional for older servers. */
135
+ credit_packs?: {
136
+ credits: number;
137
+ price: number;
138
+ }[];
139
+ /** When bought credits run out: `never` or `month_end`. */
140
+ credit_expiry?: string;
133
141
  /** A plan sold by conversation: "Talk to us" links here. */
134
142
  contact_url?: string | null;
135
143
  /** "Everything in" this plan id; its card lists that, then `features_own`. */
package/dist/run.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { type HttpConfig } from "./http.js";
2
2
  import { type AgentEvent, type CostClass, type RunUsage } from "./protocol.js";
3
+ import { type RunKey } from "./e2e.js";
3
4
  import { type ToolDefinition } from "./tools.js";
4
5
  export type ApprovalDecision = "allow" | "deny";
5
6
  export interface ApprovalRequest {
@@ -22,6 +23,26 @@ export interface RunInit {
22
23
  signal: AbortSignal | undefined;
23
24
  /** Attaching to a resumable run: the last frame already read. */
24
25
  after?: number;
26
+ /**
27
+ * Served on this server because Soba could not be reached (`fallback.ts`):
28
+ * answers go straight to the loop asking for them, and a cancel stops it,
29
+ * with no request to a Soba that is not there.
30
+ */
31
+ local?: {
32
+ deliver: (answer: {
33
+ callId: string;
34
+ result: unknown;
35
+ isError: boolean;
36
+ }) => void;
37
+ cancel: (reason: unknown) => void;
38
+ };
39
+ /**
40
+ * AN END-TO-END RUN'S KEY (`encrypt` on the client). Every event's content is
41
+ * opened with it, every tool call and approval must arrive sealed with it,
42
+ * and every answer leaves sealed with it. Content that arrives unsealed on
43
+ * such a run was written by whoever carried it, and is dropped.
44
+ */
45
+ runKey?: RunKey;
25
46
  }
26
47
  /**
27
48
  * A run in flight.
@@ -44,6 +65,9 @@ export declare class Run implements AsyncIterable<AgentEvent> {
44
65
  * about to hit its time limit, a deploy, a closed tab.
45
66
  */
46
67
  get cursor(): number;
68
+ /** Answered by your own provider because Soba could not be reached. Not
69
+ * resumable, and reported to Soba later (`soba.fallback.flush()`). */
70
+ get servedWithoutSoba(): boolean;
47
71
  /** Whether the gateway is keeping this run's frames, so it can be attached to again. */
48
72
  get resumable(): boolean;
49
73
  /** Empty only until the first frame, if the server omitted the header. */
package/dist/stream.d.ts CHANGED
@@ -9,6 +9,8 @@ export type StreamFrame = ({
9
9
  kind: "event";
10
10
  runId?: string;
11
11
  event: AgentEvent;
12
+ /** An end-to-end run's content, still sealed. `Run` opens it. */
13
+ sealed?: string;
12
14
  } | {
13
15
  kind: "usage";
14
16
  runId?: string;
@@ -32,6 +34,7 @@ export type StreamFrame = ({
32
34
  seq?: number;
33
35
  };
34
36
  export declare function parseStreamFrame(raw: string): StreamFrame | null;
37
+ export declare function parseEvent(o: Record<string, unknown>): AgentEvent | null;
35
38
  /**
36
39
  * Yield frames off a live response body.
37
40
  *
package/dist/version.d.ts CHANGED
@@ -1 +1 @@
1
- export declare const VERSION = "0.0.12";
1
+ export declare const VERSION = "0.0.14";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soba-so/sdk",
3
- "version": "0.0.12",
3
+ "version": "0.0.14",
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",