@soba-so/mcp 0.0.9 → 0.0.11

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.
Files changed (2) hide show
  1. package/dist/mcp.mjs +9 -546
  2. package/package.json +1 -1
package/dist/mcp.mjs CHANGED
@@ -1,542 +1,5 @@
1
1
  #!/usr/bin/env node
2
- import{readFileSync as Pe}from"node:fs";import Oe from"node:os";import fe from"node:path";var w=class extends Error{constructor(n,r){super(r);this.status=n;this.name="ApiError"}},A=class{constructor(t,n){this.token=t;this.baseUrl=n;this.kind=t.startsWith("mk_soba_")?"setup":"account"}kind;get(t){return this.call("GET",t)}post(t,n){return this.call("POST",t,n)}patch(t,n){return this.call("PATCH",t,n)}put(t,n){return this.call("PUT",t,n)}delete(t){return this.call("DELETE",t)}async call(t,n,r){let o=await fetch(`${this.baseUrl}${n}`,{method:t,headers:{authorization:`Bearer ${this.token}`,...r===void 0?{}:{"content-type":"application/json"}},body:r===void 0?void 0:JSON.stringify(r)}),s=await o.text(),u=null;try{u=s?JSON.parse(s):null}catch{throw new w(o.status,`${t} ${n} did not return json (${s.slice(0,120)})`)}if(!o.ok){let l=u?.error,h=l?.message??l;throw new w(o.status,typeof h=="string"?h:`${t} ${n} failed with ${o.status}`)}return u}};var G=36e5,E=24*G,qe={returnAfterMs:0,expiryMs:30*E,uniquenessMs:365*E},je={returnAfterMs:24*G,expiryMs:30*E,uniquenessMs:365*E};var Je=10*6e4;var we=864e5,ye=30,nt={abandonedAfterMs:ye*we};var st=30*24*60*60*1e3;var it=5*60*1e3;function T(e){return[{upTo:null,microsPerUnit:e}]}var R={hobby:2.5*1e6,starter:2.4*1e6,growth:2.3*1e6,scale:2.2*1e6},gt=5e3*1e6;var Y="lite";var bt=[{id:"hobby",name:"Hobby",feeMicros:19*1e6,includedActivations:20,seatLimit:2,appLimit:3,bands:T(R.hobby),features:["Set your users' free trial: length, usage and features","3 projects","2 seats","Owner and Member roles","Connected user counts","Docs support"]},{id:"starter",seatLimit:null,appLimit:null,name:"Starter",feeMicros:199*1e6,includedActivations:100,bands:T(R.starter),features:["Unlimited projects","Unlimited seats","Admin and Billing roles","Cohort and conversion attribution","Email support"]},{id:"growth",seatLimit:null,appLimit:null,name:"Growth",feeMicros:599*1e6,includedActivations:400,bands:T(R.growth),features:["Soba's approval screen in your colors","Window A/B experimentation","Email support, one business day"]},{id:"scale",seatLimit:null,appLimit:null,name:"Scale",feeMicros:1999*1e6,includedActivations:1500,bands:T(R.scale),features:["Custom roles and audit log","Effective-vs-configured window analytics","Shared channel with an SLA"]}];var wt={hobby:["owner","member"],[Y]:["owner","member"]};var Tt=60*6e4;var _e="https://soba.so/skill",It=`npx skills add ${_e}`;var H=`Soba is the LLM layer for an application whose users bring their own compute.
3
- Requests go to Soba instead of to a model provider; Soba routes each one to the
4
- machine or plan belonging to the user it names, meters it, and bills for it.
5
-
6
- ## How an integration is shaped
7
-
8
- Every app, whatever it is \u2014 a chat, one AI button, a background job with a
9
- page \u2014 gets the same two halves:
10
-
11
- 1. **The server**: every LLM call goes through Soba as the signed-in user, a
12
- session route lets the browser act for that user, and Soba's answer
13
- (including a refusal) reaches the browser intact.
14
- 2. **The browser**: one \`<SobaProvider>\`, and a surface for each moment
15
- somebody meets their compute \u2014 the settings page, every control that
16
- starts a run, the place a run's result appears and, when the app's AI only
17
- works on the user's own compute, the navbar.
18
-
19
- Each surface has a component and a hook. **Mount the component**; build from
20
- the hook only when the person asks for their own markup, and then show
21
- everything the component would (see "Component or hook"). The integration is
22
- finished when every surface in the required list exists, not when the first
23
- request succeeds.
24
-
25
- ## The server
26
-
27
- ### 1. Point every LLM call site at Soba
28
-
29
- baseURL https://api.soba.so/v1
30
- apiKey process.env.SOBA_KEY
31
-
32
- An OpenAI client already speaks this, so on most projects the base URL is the
33
- only line that changes. Prompts, tools, streaming and error handling stay
34
- exactly as they are. Find every call site \u2014 a shared client, a route that
35
- builds its own, a raw \`fetch\` to the provider's REST API \u2014 and move all of them.
36
-
37
- Pass the signed-in user's id as the \`user\` field on every request.
38
-
39
- **Resolve that id on the SERVER, from the session, never from the request
40
- body.** It is what decides whose machine a run may reach, so a value the browser
41
- can choose is a value any user can use to spend any other user's compute. This
42
- is the one line in the integration that must not be guessed at: if the project's
43
- auth is not obvious, read it until it is, or stop and ask. A wrong id here does
44
- not throw \u2014 it silently pairs runs to the wrong person.
45
-
46
- **Derive it from something that outlives the database.** A primary key minted
47
- at sign-up (an autoincrement, a random UUID) is not: reset the database and the
48
- same person arrives as somebody new, stranded from the machine they paired. An
49
- email is not either, if the app lets people change it. \`sobaUserId(stable)\`
50
- from \`@soba-so/sdk/identity\` turns a stable value \u2014 a username, an auth
51
- provider's subject \u2014 into the id; use one helper for it and call it everywhere
52
- the user is named. See \`https://soba.so/docs/identity\`.
53
-
54
- ### 2. Where the key comes from
55
-
56
- If \`.env.local\` already sets \`SOBA_KEY\`, use it. Otherwise sign the terminal in,
57
- from the project root:
58
-
59
- \`\`\`bash
60
- npx -y @soba-so/cli login --no-link
61
- \`\`\`
62
-
63
- It opens the person's browser once, they approve, and the terminal keeps a token
64
- of its own; no key passes through you. Tell the person to approve before you run
65
- it; it waits up to fifteen minutes, so give the command a long timeout or run it
66
- in the background. Add \`--headless\` where no browser can open, and pass the
67
- link it prints on to the person.
68
-
69
- Then find out which app this project is. \`npx -y @soba-so/cli apps\` lists
70
- theirs by workspace. Ask the person which one, or whether to make a new one, and
71
- do not guess from the names; then link it:
72
-
73
- \`\`\`bash
74
- npx -y @soba-so/cli link --workspace "<workspace>" --app "<app>"
75
- npx -y @soba-so/cli link --workspace "<workspace>" --new "<name>" # a new app
76
- \`\`\`
77
-
78
- That writes \`SOBA_KEY\` (a development key, for this machine), \`SOBA_PROD_KEY\`
79
- (production) and \`SOBA_APP_ID\` into \`.env.local\`, adding that file to
80
- \`.gitignore\` if git would commit it. With nobody at the terminal the CLI never
81
- waits on a question: a choice it needs ends the command with the flag to pass.
82
- Every command is on \`https://soba.so/docs/reference/cli\`.
83
-
84
- \`.env.local\` is right for Next.js, Vite and most Node servers. Where the code
85
- that holds the key reads a different file, pass that file with \`--env-file\`
86
- to \`link\` instead, from the project root, so the key lands where the server
87
- will look:
88
-
89
- | Server | File |
90
- |---|---|
91
- | Cloudflare Worker (\`wrangler dev\`) | \`--env-file <worker dir>/.dev.vars\` |
92
- | A server in a subfolder of a monorepo or an extension repo | \`--env-file <server dir>/.env.local\` |
93
-
94
- Find the file by reading how that server loads its environment, not by its
95
- framework's reputation. The CLI adds whatever file it writes to \`.gitignore\`
96
- if git would commit it.
97
-
98
- On a host that keeps secrets itself \u2014 \`wrangler secret put SOBA_KEY\`, Vercel's
99
- or Railway's environment \u2014 production takes \`SOBA_PROD_KEY\`'s value under the
100
- name \`SOBA_KEY\`. That is the person's to paste; tell them the command.
101
-
102
- A development key reaches only the user's own AI \u2014 their machine, their
103
- subscription, their API key. In production, \`SOBA_KEY\` is set to the value of
104
- \`SOBA_PROD_KEY\` in the host's environment; say so to the person rather than
105
- doing it.
106
-
107
- If you cannot run commands but have a \`soba_create_key\` tool, call it: the
108
- secret is returned once and nothing can show it again, so write it into
109
- \`.env.local\` in the same step. Failing both, ask the person to run the command
110
- above themselves. Do not leave \`SOBA_KEY\` empty and do not invent a value; both
111
- fail at the first request, and the first fails as an auth error rather than as
112
- a missing variable.
113
-
114
- Put \`SOBA_KEY\` in \`.env.local\` (or the server's own file, above), and check
115
- that file is gitignored before writing it. Never in \`.env\`, never in
116
- \`.env.example\`, never in anything tracked, and never echoed back to the terminal.
117
-
118
- ### 3. The session route
119
-
120
- \`POST /api/soba/session\`, a route in the app that proxies
121
- \`POST /v1/end_users/session\` with the secret key and the same server-resolved
122
- user id, and returns the body as it came (\`{ session, expires_in }\`). It is
123
- what every surface in the browser runs on, and the browser never sees
124
- \`SOBA_KEY\`. Signed out, it answers 401.
125
-
126
- ### 4. Pass Soba's answer through
127
-
128
- A refused run is not an outage: \`no_compute\` (409) means nothing the run could
129
- use is reachable for this user, \`payment_required\` (402) means the plan's
130
- allowance is spent. The browser surfaces below turn each into the way out \u2014
131
- connect a machine, or upgrade \u2014 but only if the refusal reaches them with its
132
- code. So in every route that calls Soba, return Soba's status and \`error\` body
133
- as they came, instead of letting the client library's exception become a 500 or
134
- a string:
135
-
136
- \`\`\`js
137
- } catch (err) {
138
- if (err instanceof OpenAI.APIError) {
139
- return Response.json({ error: err.error }, { status: err.status });
140
- }
141
- throw err;
142
- }
143
- \`\`\`
144
-
145
- A route that streams has to do this before the first byte is written: create
146
- the completion (or start the run) first, and only then return the stream. In
147
- the browser, keep the parsed body (\`setError(await res.json())\`) rather than
148
- its text; that object is what the surfaces read. Branch on the code, never on
149
- the message.
150
-
151
- ### 5. Which API
152
-
153
- \`chat/completions\` is stateless and the caller owns the loop, so it reaches
154
- models. Reaching a user's own Claude or ChatGPT subscription means letting Soba
155
- own the loop instead:
156
-
157
- \`\`\`js
158
- import { Soba } from "@soba-so/sdk";
159
- import { sobaUserId } from "@soba-so/sdk/identity";
160
-
161
- const soba = new Soba({ apiKey: process.env.SOBA_KEY });
162
-
163
- const run = await soba.run({
164
- user: sobaUserId(session.user.username),
165
- model: "auto",
166
- prompt: "Summarise everything I saved this week",
167
- owners: [session.user.accountId], // whose rows this person may read
168
- tools: [listNotes, readNote], // your code, executed in your app
169
- });
170
- \`\`\`
171
-
172
- Tools passed to a run execute in the app's own process, so they can read the
173
- app's own data. The model asks for data by calling them; the data does not
174
- travel in the prompt.
175
-
176
- Every tool says whose data it returns, and a run with a tool that does not is
177
- refused before it starts. One of three, on each tool:
178
-
179
- - \`owner: (row) => row.accountId\` when it returns rows of the app's data.
180
- Also pass \`owners\` on the run: the ids, in the app's own data, whose rows
181
- this person may read (their account, their team), resolved from the session
182
- the same way as \`user\`. The SDK then drops every row owned by anyone else,
183
- even when a query forgot its filter.
184
- - \`public: true\` when the result belongs to nobody: a catalogue, a search of
185
- public pages.
186
- - \`checksOwner: true\` when the tool writes, or returns a computed answer with
187
- no rows. Its own code must scope by the signed-in user.
188
-
189
- Never read an account id or a user id from a tool's input: derive it from the
190
- session. Give each tool a strict \`inputSchema\` with
191
- \`additionalProperties: false\`; the SDK rejects a call that does not fit it.
192
- The user can read every tool's name, description and result, so return only
193
- what that person may see. To keep a tool out of their sight, mark it
194
- \`private: true\`: it then runs on the app's own provider key and only its
195
- answer reaches the run.
196
-
197
- ## The browser: one provider, a surface for each moment
198
-
199
- Everything below reads from \`<SobaProvider sessionEndpoint="/api/soba/session">\`.
200
- Mount it where a surface is, with \`sessionCacheKey\` set to the signed-in user's
201
- id so reloads, navigations, tabs and other providers on the page share one
202
- session. Never in a root layout that also renders the login page or marketing
203
- pages: there is nobody there to mint a session for. A navbar's provider goes
204
- in the layout that draws the signed-in navbar. All the components raise the
205
- same pairing modal \u2014 the provider mounts exactly one, so an app with every
206
- surface cannot put two pairings on screen at once.
207
-
208
- | Surface | Component | Hook (for your own markup) |
209
- |---|---|---|
210
- | **The settings page** | \`<ComputeSettings />\`, alone | \`useCompute()\` + \`useConnectButton()\` |
211
- | **Above every control that starts a run** | \`<ConnectNudge />\` | \`useConnectNudge()\` |
212
- | **Where a run's result appears**, when it failed | \`<RunLimit error={error} />\` then \`<RunError error={error} />\` | \`useRunLimit(error)\` + \`runErrorMessage(error)\` |
213
- | **The signed-in navbar**, when AI only works on their compute | \`<ConnectButton />\` | \`useConnectButton()\`; its panel from \`useCompute()\` and \`useMachineRuns()\` |
214
- | **The composer**, in an app with one | \`<ModelPicker />\` beside send | \`useModel()\` |
215
- | **Billing and pricing** | \`<SobaBilling />\`, or \`<SobaCurrentPlan />\` + \`<SobaPlans />\`, \`<SobaCheckout />\`, \`<RedeemCode />\` | \`useCurrentPlan()\`, \`usePlans()\`, \`useCheckout()\`, \`useRedeemCode()\` |
216
- | **Anything a plan limits** | \`<SobaGate feature="\u2026" />\` | \`useFeature()\`, plus the server check below |
217
-
218
- **Required in every app: the first three.** The navbar follows from how the
219
- app's AI is paid for (below); the composer, billing and gates follow from what
220
- the app has \u2014 a model choice to offer, plans to sell, features to limit \u2014 and
221
- the plans themselves are the person's to decide, not yours.
222
-
223
- What each surface is for, and the mistakes it exists to prevent:
224
-
225
- - **Navbar, when the AI only works on their compute.** Add \`<ConnectButton />\`
226
- to the signed-in navbar when nothing can run until a user connects \u2014 a
227
- bring-your-own plan, a route that only allows their machine or their
228
- subscription, an app on a development key. There, connecting is a
229
- prerequisite rather than an offer, so the door belongs on every page: it
230
- says "Connect compute" until something is attached, then names the machine
231
- and its state, and once connected it is a pill that opens a popover with the
232
- machines and what they are running. An app whose runs fall back to compute
233
- it pays for does not need it; settings, the nudge and the run limit already
234
- meet the person where connecting matters. Wherever it is used, it lives in
235
- the header and only there \u2014 a popover pill is wrong inside a page.
236
- - **Settings.** A settings page is where somebody checks on a machine they
237
- already attached, not where they decide to attach one. \`<ComputeSettings />\`
238
- draws it as rows of that page in its own type: each machine, which agent the
239
- app's runs go to there, and whether it is awake, asleep or serving, with
240
- "Connect compute" or "Connect another computer". Nothing else from the
241
- package goes on that page \u2014 \`<ConnectButton />\` or \`<ComputeStatus />\` beside
242
- it draws the same machine twice. (\`<ConnectCompute />\` is its older name.) If
243
- there is no settings page, build one, and do not point the connect return URL
244
- at a page that does not render it.
245
- - **Above each run-starting control.** Not only a chat composer: every "Tidy",
246
- "Summarise", "Draft", "Generate", every form that kicks off a job \u2014 find each
247
- call site from step 1 and the control that triggers it. \`<ConnectNudge />\`
248
- stands there before anything is pressed and speaks only when it can help:
249
- nothing connected and nothing else can serve, a paired machine gone quiet, or
250
- an allowance running down that connecting would lift. It draws nothing
251
- otherwise.
252
- - **The result's place.** When a run fails, \`<RunLimit error={error} />\`
253
- renders where the answer was going to be: for \`no_compute\` the way to connect
254
- (or wake the machine), for \`payment_required\` the plan to upgrade to. It goes
255
- quiet by itself once a machine is online, so a refusal from before connecting
256
- is never shown as the answer to connecting. \`<RunError error={error} />\`
257
- beside it says every other failure in a sentence; the two never both speak.
258
-
259
- ### One run-starting control, written both ways
260
-
261
- The same button in any app, as components:
262
-
263
- \`\`\`jsx
264
- "use client";
265
- import { ConnectNudge, RunError, RunLimit } from "@soba-so/react";
266
-
267
- function TidyButton({ noteId }) {
268
- const [error, setError] = useState(null);
269
-
270
- async function tidy() {
271
- setError(null);
272
- const res = await fetch("/api/tidy", { method: "POST", body: JSON.stringify({ noteId }) });
273
- if (!res.ok) return setError(await res.json()); // Soba's body, per step 4
274
- // \u2026read the result as the app already does
275
- }
276
-
277
- return (
278
- <>
279
- <ConnectNudge />
280
- <button onClick={tidy}>Tidy</button>
281
- <RunLimit error={error} />
282
- <RunError error={error} />
283
- </>
284
- );
285
- }
286
- \`\`\`
287
-
288
- And built from the hooks, in the app's own components (\`Your\u2026\` below stands for
289
- whatever the app already draws banners, buttons and cards with), saying
290
- everything the components would:
291
-
292
- \`\`\`jsx
293
- import { runErrorMessage, useConnectNudge, useRunLimit } from "@soba-so/react";
294
-
295
- function TidyButton({ noteId }) {
296
- const [error, setError] = useState(null);
297
- const nudge = useConnectNudge(); // before: is anything in the way?
298
- const limit = useRunLimit(error); // after: the way out of a refusal
299
- const message = runErrorMessage(error); // after: every other failure
300
-
301
- return (
302
- <>
303
- {nudge.visible && (
304
- <YourBanner title={nudge.title} detail={nudge.detail} steps={nudge.steps}
305
- onAction={nudge.open} onDismiss={nudge.dismissible ? nudge.dismiss : undefined} />
306
- )}
307
- <YourButton onClick={tidy}>Tidy</YourButton>
308
- {limit ? (
309
- <YourCard title={limit.title} body={limit.body}
310
- onConnect={limit.connect}
311
- onUpgrade={limit.upgradeTo ? limit.upgrade : undefined} />
312
- ) : message ? (
313
- <p className="error">{message}</p>
314
- ) : null}
315
- </>
316
- );
317
- }
318
- \`\`\`
319
-
320
- Both halves are inside a provider. In a chat, the nudge stands above the
321
- composer and the limit and error render in the message that failed; see "The
322
- chat stays theirs".
323
-
324
- ## Component or hook
325
-
326
- Both halves ship, and **the component is the answer.** Mount it even when the
327
- app already has its own composer, its own billing cards, its own design system
328
- and Tailwind everywhere. Do not look at the repo's styling and decide to
329
- rebuild one of these from its hook.
330
-
331
- The reason is that the components are not just markup. The vendor configures
332
- them in the Soba dashboard: the model picker's layout (by provider, one list,
333
- custom only), which of Automatic, Fast and Best are offered, search, the agents'
334
- marks and the line under each choice, the connect popup's look and theme. The
335
- component reads all of that from the provider and draws it. A hand-built copy
336
- reads none of it, so every setting the vendor changes in the dashboard silently
337
- does nothing in their app, and nobody finds out until they compare the two.
338
-
339
- What that looks like in practice, from a real integration: an app with its own
340
- Tailwind composer took \`useModel()\` and rendered it as a native
341
- \`<select>\` \u2014 no marks, no descriptions, no submenu per agent, a flat list
342
- where the dashboard said "by provider". It worked, and it was wrong.
343
-
344
- The components fit a foreign screen on purpose: \`className\` on each one for
345
- placement and size, \`theme\` on \`<SobaProvider>\` (or the dashboard) for
346
- light and dark, \`<ComputeSettings />\` inherits the page's type, and
347
- \`<ModelPicker />\` is a pill beside a send button, not a card. The header's
348
- pill takes \`--sc-pill-*\` custom properties, set anywhere above it, and
349
- \`<ConnectButton />\` also takes a function as children that draws the whole
350
- control in this app's own markup, still opening the panel when pressed. Use
351
- that when a recoloured pill would not look like it belongs:
352
- https://soba.so/docs/components#the-connect-pill. If one still
353
- clashes, say so to the person and leave the component in.
354
-
355
- **Reach for a hook only when the person asks for their own markup**, or for a
356
- decision no component draws (\`useMachineRuns()\`, \`useOpenSobaConnect()\`,
357
- gating a server action on \`useFeature()\`). Every component is one rendering of
358
- an exported hook and derives nothing of its own, and a surface built from a
359
- hook must still show everything the component shows. Each line in the last
360
- column is something a hand-built copy has dropped:
361
-
362
- | Component | Hook | Built from the hook, it must still show |
363
- |---|---|---|
364
- | \`<ConnectButton />\` | \`useConnectButton()\` | In the header, on every page, when the app needs their compute. \`label\`, which names the machine once one is attached; the state dot from \`state.tone\` with \`state.word\`; disabled when \`canOpen\` is false. Pressing it calls \`open()\`, which raises Soba's connect flow \u2014 never a page of your own. Its panel's machine list and "Running now" with Stop come from \`useCompute()\` and \`useMachineRuns()\` |
365
- | \`<ComputeSettings />\` | \`useCompute()\` + \`useConnectButton()\` | The settings page's section, as rows in the page's own type: each machine's \`name\`, \`hardware\`, \`runsOn.name\` and \`status.text\` with a dot from \`state.tone\`, \`lastSeen\` instead of the hardware while it is asleep; "Connect compute" with nothing connected and "Connect another computer" with something, both calling \`open()\`. No pill and no popover |
366
- | \`<ComputeStatus />\` | \`useCompute()\` | All four of \`view\`: loading, error, empty, machines. Each machine's state in words, and \`stalled\` called out. "Nothing connected" only when \`view\` is \`"empty"\` |
367
- | \`<ConnectNudge />\` | \`useConnectNudge()\` | Nothing unless \`visible\`. \`title\`, \`detail\`, the \`meter\`, the \`steps\` and \`stalled\`; a dismiss only when \`dismissible\`; the action is \`open()\` |
368
- | \`<RunLimit />\` | \`useRunLimit()\` | In the place the answer was going to be. \`title\` and \`body\`; Connect calling \`connect()\`, with \`connectOffer\` as its line when there is one; Upgrade only when \`upgradeTo\` is, calling \`upgrade()\`. Nothing when it returns null, which includes a \`no_compute\` the person has since fixed by connecting |
369
- | \`<RunError />\` | \`runErrorMessage()\` | Its sentence as given, nothing when it is null, and never beside a \`<RunLimit />\` that is speaking |
370
- | \`<ModelPicker />\` | \`useModel()\` | A menu, never a \`<select>\`. Automatic, Fast and Best (the \`auto\` and \`size\` options) each with its \`note\`; the app's models laid out as \`layout\` says (\`providers\`, \`models\`, \`choices\` or \`automatic\`, which is the vendor's dashboard setting); every agent in \`agents\` with its logo, as its own submenu, and an agent with no models (Codex) as a single row; \`providers\` with their marks (\`<ProviderMark />\` draws each), and locked when the plan says so. A search field when \`search\` is on. \`unavailable\` as the reason a stale pick fell back. Nothing at all when \`pickable\` is false. Spread \`run\` onto the request |
371
- | \`<SobaPlans />\` | \`usePlans()\` | Every offer: price, \`allowance\` and \`allowanceNote\`, \`features\`, the compute it runs on, the connect row, and its \`cta\` calling \`take()\`. The current plan and the featured one marked. \`failed\` when it is set |
372
- | \`<SobaCurrentPlan />\` | \`useCurrentPlan()\` | \`summary\`; used and remaining as a meter unless \`unlimited\`; \`trialDaysLeft\`, \`periodEnd\` and the \`reward\` when there are any |
373
- | \`<SobaCheckout />\` | \`useCheckout()\` | \`label\` on the button, \`busy\` and \`error\`, and \`buy()\`. Nothing is granted in the browser |
374
- | \`<SobaGate />\` | \`useFeature()\` | The children while allowed; otherwise the reason it is not and the plans that would allow it |
375
- | \`<RedeemCode />\` | \`useRedeemCode()\` | A field and an Apply that call \`redeem()\`, \`busy\`, \`error\` as given, and the \`reward\` once it lands |
376
-
377
- \`<SobaBilling />\` and \`<ConnectModal />\` are compositions of the above and
378
- have no rule of their own. \`<ConnectPill />\` is the half of \`<ConnectButton />\`
379
- that reports \u2014 the mark, the state and the machine, with no popover under it
380
- and no flow behind it. It is for an app whose person asked for their own panel;
381
- otherwise the header gets \`<ConnectButton />\`, panel included. Pressing the pill
382
- is yours to wire, and it still opens Soba's flow through
383
- \`useSoba().connect.open()\`; everything it says is \`connectSays\`.
384
- \`<SobaProvider>\` is needed either way: the hooks read from it, so a hook with no
385
- provider above it is the one mistake this split invites.
386
-
387
- A gate draws the button; it does not secure the action. On the server, ask
388
- before you create: \`soba.users.check(user, "workspaces", { use: 1 })\` answers
389
- \`{ allowed, reason }\` and counts the use in the same call, so two requests for
390
- the last one cannot both get it. Record use you did not ask about with
391
- \`soba.users.track(user, "workspaces", -1)\` when one is deleted. Prices,
392
- allowances and the connected reward come from the plan objects, so changing
393
- them later is not a deploy. Pass \`showConnect\` to \`<SobaPlans />\` only on a page
394
- with no current-plan card: a bring-your-own plan would otherwise state a
395
- requirement with no way to meet it.
396
-
397
- Three belong to no component of their own. \`useOpenSobaConnect()\` brings the
398
- Soba app forward on this person's machine and hands back the one honest thing a
399
- page can say about having tried \u2014 a browser cannot tell whether a \`soba://\`
400
- link was answered, and a page that claims it worked is guessing.
401
- \`useRun()\` is for a run started in the browser that must outlive the page: a
402
- reload, a page switch or a dropped connection only stops the reading, and it
403
- reads on by itself. It takes your two routes, both returning \`runResponse\`
404
- from \`@soba-so/sdk\`: one around \`soba.run({ resumable: true })\`, one around
405
- \`soba.runs.attach\`.
406
-
407
- \`useMachineRuns()\` is the "Running now" list out of \`<ConnectButton />\`'s
408
- panel with no panel around it: what this person's machines are running FOR THIS
409
- APP, and \`stop(runId)\` to end one as the person whose machine it is on; the app
410
- that started that run sees it finish with \`reason: "stopped_by_user"\`.
411
- \`useRedeemCode()\` is a promo code field's behaviour: \`redeem(code)\` gives the
412
- user what the app's reward hands out and re-reads their plan, so the allowance
413
- on screen moves without a reload; \`<RedeemCode />\` is that field already drawn.
414
-
415
- \`useSoba()\` is the raw provider state. Reach for a named hook first and use
416
- this one for what no hook covers \u2014 \`run()\`, \`connect.open()\`,
417
- \`plan.refresh()\`. A page that reads \`compute.connected\` or \`plan.remaining\`
418
- straight off it is re-deriving a decision that is already exported, and the two
419
- copies are how our own apps drifted.
420
-
421
- ### What not to write yourself
422
-
423
- These are not style preferences. Each one is a judgement this package already
424
- makes, and each has been got wrong in production \u2014 in our own code, which is why
425
- they are exported at all. If you find yourself writing one of them, delete it
426
- and import the answer:
427
-
428
- - **A list of model names.** The names come off the person's own machine, so a
429
- list in your code refuses the model they can see on their own screen.
430
- \`useModel()\` reads it from what they have connected.
431
- - **A model id on a run without its agent.** Soba applies a person's own agent
432
- preference only to a run whose model is blank or a size, so a named model
433
- travelling alone goes to whichever agent is found first. Spread
434
- \`useModel().run\` whole \u2014 it is \`{ model, runtime? }\` \u2014 and have your route
435
- forward both fields.
436
- - **"Nothing connected yet."** That is a claim about somebody's account and it
437
- is only true once the account has been read. Said while the first request is
438
- in flight, or after it failed, it tells a person with a paired laptop that it
439
- has vanished. \`useCompute().view\` is the four-way answer.
440
- - **A match on an error message, or an error line of your own for a refusal.**
441
- \`useRunLimit\` and \`runErrorMessage\` read the CODE. Messages are prose we
442
- rewrite, matching on them breaks on a copy edit, and Soba's own refusal text
443
- names internal ids no user should see.
444
- - **Words for a cost class.** \`tierLabel(tier)\` is the one glossary for the five
445
- economics this product is about. Four hand-written copies in this repo
446
- disagreed with each other, and three reported somebody's own API key as
447
- frontier supply the app had paid for.
448
- - **Where the pick is remembered, or how a stale one is handled.** A model whose
449
- machine is gone falls back to Automatic and stays picked. \`useModel()\` does
450
- that and tells you with \`unavailable\`.
451
-
452
- Read \`https://soba.so/docs/components\` for each hook's full shape.
453
-
454
- ## The chat stays theirs
455
-
456
- There is no chat component, on purpose. An app built on Soba already has its own
457
- composer and its own messages, and they are the product. Keep every line of
458
- that markup. What Soba adds goes INTO it, and these are the things a chat on
459
- Soba has to handle \u2014 check each one against the code, not against memory:
460
-
461
- **In the composer**
462
-
463
- - \`<ModelPicker />\` in the composer's footer, beside the send button. The
464
- component, per the section above, not a copy.
465
- - Spread \`useModel().run\` onto the request, and have the route forward
466
- \`model\` and \`runtime\` both.
467
- - Send becomes Stop while a run is going. Stop aborts the request's
468
- \`signal\`, and a run the person stopped is not an error to show. Neither is
469
- \`reason: "stopped_by_user"\`, which is the machine's owner stopping it
470
- from their side.
471
- - \`<ConnectNudge />\` above the composer. It draws nothing until it has
472
- something to say.
473
- - Images, only if the composer already takes them: forward each message's
474
- \`images\` and the runtimes that can see them will.
475
-
476
- **In the messages**
477
-
478
- - \`delta\` text is appended as it arrives. \`thinking\` is the running total
479
- and REPLACES what is shown \u2014 appending it repeats every sentence. Fold it
480
- away by default.
481
- - \`status\` events are what the agent is doing: show \`message\`, and
482
- \`toolInput\` beside it when there is one. \`state: "interrupted"\` means
483
- the person's machine went offline mid-run and \`"resumed"\` that it came
484
- back; say so in the answer, because the run goes on either way.
485
- - A failed run renders \`<RunLimit />\` where the answer was going to be, and
486
- \`<RunError />\` beside it for everything else. Branch on the \`reason\`
487
- code, never the message. Offer Retry only when \`retryable\` is not false.
488
- - Copy on every answer, on hover, copying the text as written (markdown, not
489
- rendered HTML). Retry on the last one.
490
- - \`done\` carries \`usage\` and \`tier\`. If the app shows what answered,
491
- word the tier with \`tierLabel()\`.
492
-
493
- **Across turns**
494
-
495
- - \`done\` and \`error\` carry a \`session\`. Send it back as \`resume\`
496
- on the next run, and have the route forward it, so a follow-up continues the
497
- agent's conversation instead of starting a new one with the whole transcript
498
- pasted in.
499
-
500
- An app with no chat at all gets one built in its own components and styles,
501
- the same way it would build any other screen \u2014 with everything above in it.
502
-
503
- ## Proving it
504
-
505
- \`soba/echo\` is answered by Soba itself \u2014 no machine, no metered supply,
506
- nothing billed \u2014 and still proves the key, the base URL and the \`user\` field:
507
-
508
- \`\`\`sh
509
- curl https://api.soba.so/v1/chat/completions \\
510
- -H "Authorization: Bearer $SOBA_KEY" \\
511
- -H "Content-Type: application/json" \\
512
- -d '{ "model": "soba/echo", "user": "usr_123",
513
- "messages": [{ "role": "user", "content": "ping" }] }'
514
- \`\`\`
515
-
516
- A curl is evidence the credential works. It is NOT evidence the app is
517
- integrated \u2014 the dashboard's integrate step ticks on a request arriving from the
518
- real call site, and it cannot tell a curl from a deployment. Do not send one to
519
- make a checklist go green. Before calling the integration done, walk the
520
- required surfaces as a signed-in user with nothing connected: settings says
521
- "Connect compute", the nudge stands above each run-starting control when
522
- connecting would help, pressing one shows the limit card where the result
523
- would have been (and the navbar says "Connect compute", where there is one) \u2014
524
- then connect, and each of them goes quiet.
525
-
526
- ## A new project rather than an existing one
527
-
528
- There is no separate procedure for this and no question to ask the person: look
529
- at the directory. If there is no app yet, run \`npx create-soba@latest\` and let
530
- it write one \u2014 it ships a correct \`/api/soba/session\`, which is the security
531
- boundary of the whole integration, and a plausible hand-written one is the
532
- failure mode that matters. Then the server half is already done and what
533
- remains is the key.
534
-
535
- ## What is not yours to do
536
-
537
- Pairing is a person installing the Soba app on their own laptop and approving
538
- it. Pricing, allowances and rewards are decisions about somebody's business.
539
- Do neither on their behalf; say what is left and stop.`;var L=[{name:"set_up",title:"Set Soba up in this repo",description:"Works through Soba's setup checklist one step at a time, editing this repo and showing you each diff.",text:`Set this project up on Soba, working from the real checklist rather than from memory.
2
+ import{readFileSync as Pe}from"node:fs";import Oe from"node:os";import fe from"node:path";var w=class extends Error{constructor(n,r){super(r);this.status=n;this.name="ApiError"}},x=class{constructor(t,n){this.token=t;this.baseUrl=n;this.kind=t.startsWith("mk_soba_")?"setup":"account"}kind;get(t){return this.call("GET",t)}post(t,n){return this.call("POST",t,n)}patch(t,n){return this.call("PATCH",t,n)}put(t,n){return this.call("PUT",t,n)}delete(t){return this.call("DELETE",t)}async call(t,n,r){let o=await fetch(`${this.baseUrl}${n}`,{method:t,headers:{authorization:`Bearer ${this.token}`,...r===void 0?{}:{"content-type":"application/json"}},body:r===void 0?void 0:JSON.stringify(r)}),s=await o.text(),u=null;try{u=s?JSON.parse(s):null}catch{throw new w(o.status,`${t} ${n} did not return json (${s.slice(0,120)})`)}if(!o.ok){let l=u?.error,h=l?.message??l;throw new w(o.status,typeof h=="string"?h:`${t} ${n} failed with ${o.status}`)}return u}};var G=36e5,T=24*G,qe={returnAfterMs:0,expiryMs:30*T,uniquenessMs:365*T},We={returnAfterMs:24*G,expiryMs:30*T,uniquenessMs:365*T};var Je=10*6e4;var we=864e5,ye=30,nt={abandonedAfterMs:ye*we};var st=30*24*60*60*1e3;var it=5*60*1e3;function E(e){return[{upTo:null,microsPerUnit:e}]}var R={hobby:2.5*1e6,starter:2.4*1e6,growth:2.3*1e6,scale:2.2*1e6},gt=5e3*1e6;var Y="lite";var bt=[{id:"hobby",name:"Hobby",feeMicros:19*1e6,includedActivations:20,seatLimit:2,appLimit:3,bands:E(R.hobby),features:["Set your users' free trial: length, usage and features","3 projects","2 seats","Owner and Member roles","Connected user counts","Docs support"]},{id:"starter",seatLimit:null,appLimit:null,name:"Starter",feeMicros:199*1e6,includedActivations:100,bands:E(R.starter),features:["Unlimited projects","Unlimited seats","Admin and Billing roles","Cohort and conversion attribution","Email support"]},{id:"growth",seatLimit:null,appLimit:null,name:"Growth",feeMicros:599*1e6,includedActivations:400,bands:E(R.growth),features:["Soba's approval screen in your colors","Window A/B experimentation","Email support, one business day"]},{id:"scale",seatLimit:null,appLimit:null,name:"Scale",feeMicros:1999*1e6,includedActivations:1500,bands:E(R.scale),features:["Custom roles and audit log","Effective-vs-configured window analytics","Shared channel with an SLA"]}];var wt={hobby:["owner","member"],[Y]:["owner","member"]};var Et=60*6e4;var _e="https://soba.so/skill",It=`npx skills add ${_e}`;var H='Soba is the LLM layer for an application whose users bring their own compute.\nRequests go to Soba instead of to a model provider; Soba routes each one to the\nmachine or plan belonging to the user it names, meters it, and bills for it.\n\n## How an integration is shaped\n\nEvery app, whatever it is \u2014 a chat, one AI button, a background job with a\npage \u2014 gets the same two halves:\n\n1. **The server**: every LLM call goes through Soba as the signed-in user, a\n session route lets the browser act for that user, and Soba\'s answer\n (including a refusal) reaches the browser intact.\n2. **The browser**: one `<SobaProvider>`, and a surface for each moment\n somebody meets their compute \u2014 the settings page, every control that\n starts a run, the place a run\'s result appears and, when the app\'s AI only\n works on the user\'s own compute, the navbar.\n\nEach surface has a component and a hook. **Mount the component**; build from\nthe hook only when the person asks for their own markup, and then show\neverything the component would (see "Component or hook"). The integration is\nfinished when every surface in the required list exists, not when the first\nrequest succeeds.\n\n## The server\n\n### 1. Point every LLM call site at Soba\n\n baseURL https://api.soba.so/v1\n apiKey process.env.SOBA_KEY\n\nAn OpenAI client already speaks this, so on most projects the base URL is the\nonly line that changes. Prompts, tools, streaming and error handling stay\nexactly as they are. Find every call site \u2014 a shared client, a route that\nbuilds its own, a raw `fetch` to the provider\'s REST API \u2014 and move all of them.\n\nPass the signed-in user\'s id as the `user` field on every request.\n\n**Resolve that id on the SERVER, from the session, never from the request\nbody.** It is what decides whose machine a run may reach, so a value the browser\ncan choose is a value any user can use to spend any other user\'s compute. This\nis the one line in the integration that must not be guessed at: if the project\'s\nauth is not obvious, read it until it is, or stop and ask. A wrong id here does\nnot throw \u2014 it silently pairs runs to the wrong person.\n\n**Derive it from something that outlives the database.** A primary key minted\nat sign-up (an autoincrement, a random UUID) is not: reset the database and the\nsame person arrives as somebody new, stranded from the machine they paired. An\nemail is not either, if the app lets people change it. `sobaUserId(stable)`\nfrom `@soba-so/sdk/identity` turns a stable value \u2014 a username, an auth\nprovider\'s subject \u2014 into the id; use one helper for it and call it everywhere\nthe user is named. See `https://soba.so/docs/identity`.\n\n### 2. Where the key comes from\n\nIf `.env.local` already sets `SOBA_KEY`, use it. Otherwise sign the terminal in,\nfrom the project root:\n\n```bash\nnpx -y @soba-so/cli login --no-link\n```\n\nIt opens the person\'s browser once, they approve, and the terminal keeps a token\nof its own; no key passes through you. Tell the person to approve before you run\nit; it waits up to fifteen minutes, so give the command a long timeout or run it\nin the background. Add `--headless` where no browser can open, and pass the\nlink it prints on to the person.\n\nThen find out which app this project is. `npx -y @soba-so/cli apps` lists\ntheirs by workspace. Ask the person which one, or whether to make a new one, and\ndo not guess from the names; then link it:\n\n```bash\nnpx -y @soba-so/cli link --workspace "<workspace>" --app "<app>"\nnpx -y @soba-so/cli link --workspace "<workspace>" --new "<name>" # a new app\n```\n\nThat writes `SOBA_KEY` (a development key, for this machine), `SOBA_PROD_KEY`\n(production) and `SOBA_APP_ID` into `.env.local`, adding that file to\n`.gitignore` if git would commit it. With nobody at the terminal the CLI never\nwaits on a question: a choice it needs ends the command with the flag to pass.\nEvery command is on `https://soba.so/docs/reference/cli`.\n\n`.env.local` is right for Next.js, Vite and most Node servers. Where the code\nthat holds the key reads a different file, pass that file with `--env-file`\nto `link` instead, from the project root, so the key lands where the server\nwill look:\n\n| Server | File |\n|---|---|\n| Cloudflare Worker (`wrangler dev`) | `--env-file <worker dir>/.dev.vars` |\n| A server in a subfolder of a monorepo or an extension repo | `--env-file <server dir>/.env.local` |\n\nFind the file by reading how that server loads its environment, not by its\nframework\'s reputation. The CLI adds whatever file it writes to `.gitignore`\nif git would commit it.\n\nOn a host that keeps secrets itself \u2014 `wrangler secret put SOBA_KEY`, Vercel\'s\nor Railway\'s environment \u2014 production takes `SOBA_PROD_KEY`\'s value under the\nname `SOBA_KEY`. That is the person\'s to paste; tell them the command.\n\nA development key reaches only the user\'s own AI \u2014 their machine, their\nsubscription, their API key. In production, `SOBA_KEY` is set to the value of\n`SOBA_PROD_KEY` in the host\'s environment; say so to the person rather than\ndoing it.\n\nIf you cannot run commands but have a `soba_create_key` tool, call it: the\nsecret is returned once and nothing can show it again, so write it into\n`.env.local` in the same step. Failing both, ask the person to run the command\nabove themselves. Do not leave `SOBA_KEY` empty and do not invent a value; both\nfail at the first request, and the first fails as an auth error rather than as\na missing variable.\n\nPut `SOBA_KEY` in `.env.local` (or the server\'s own file, above), and check\nthat file is gitignored before writing it. Never in `.env`, never in\n`.env.example`, never in anything tracked, and never echoed back to the terminal.\n\n### 3. The session route\n\n`POST /api/soba/session`, a route in the app that proxies\n`POST /v1/end_users/session` with the secret key and the same server-resolved\nuser id, and returns the body as it came (`{ session, expires_in }`). It is\nwhat every surface in the browser runs on, and the browser never sees\n`SOBA_KEY`. Signed out, it answers 401.\n\n### 4. Pass Soba\'s answer through\n\nA refused run is not an outage: `no_compute` (409) means nothing the run could\nuse is reachable for this user, `payment_required` (402) means the plan\'s\nallowance is spent. The browser surfaces below turn each into the way out \u2014\nconnect a machine, or upgrade \u2014 but only if the refusal reaches them with its\ncode. So in every route that calls Soba, return Soba\'s status and `error` body\nas they came, instead of letting the client library\'s exception become a 500 or\na string:\n\n```js\n} catch (err) {\n if (err instanceof OpenAI.APIError) {\n return Response.json({ error: err.error }, { status: err.status });\n }\n throw err;\n}\n```\n\nA route that streams has to do this before the first byte is written: create\nthe completion (or start the run) first, and only then return the stream. In\nthe browser, keep the parsed body (`setError(await res.json())`) rather than\nits text; that object is what the surfaces read. Branch on the code, never on\nthe message.\n\n### 5. Which API\n\n`chat/completions` is stateless and the caller owns the loop, so it reaches\nmodels. Reaching a user\'s own Claude or ChatGPT subscription means letting Soba\nown the loop instead:\n\n```js\nimport { Soba } from "@soba-so/sdk";\nimport { sobaUserId } from "@soba-so/sdk/identity";\n\nconst soba = new Soba({ apiKey: process.env.SOBA_KEY });\n\nconst run = await soba.run({\n user: sobaUserId(session.user.username),\n model: "auto",\n prompt: "Summarise everything I saved this week",\n owners: [session.user.accountId], // whose rows this person may read\n tools: [listNotes, readNote], // your code, executed in your app\n});\n```\n\nTools passed to a run execute in the app\'s own process, so they can read the\napp\'s own data. The model asks for data by calling them; the data does not\ntravel in the prompt.\n\nEvery tool says whose data it returns, and a run with a tool that does not is\nrefused before it starts. One of three, on each tool:\n\n- `owner: (row) => row.accountId` when it returns rows of the app\'s data.\n Also pass `owners` on the run: the ids, in the app\'s own data, whose rows\n this person may read (their account, their team), resolved from the session\n the same way as `user`. The SDK then drops every row owned by anyone else,\n even when a query forgot its filter.\n- `public: true` when the result belongs to nobody: a catalogue, a search of\n public pages.\n- `checksOwner: true` when the tool writes, or returns a computed answer with\n no rows. Its own code must scope by the signed-in user.\n\nNever read an account id or a user id from a tool\'s input: derive it from the\nsession. Give each tool a strict `inputSchema` with\n`additionalProperties: false`; the SDK rejects a call that does not fit it.\nThe user can read every tool\'s name, description and result, so return only\nwhat that person may see. To keep a tool out of their sight, mark it\n`private: true`: it then runs on the app\'s own provider key and only its\nanswer reaches the run. Instructions the user must not read go in\n`privateSystem`, which only those private tools see; `privateTool` names the\none tool that stands in for them. Test the scoping with `assertToolsScoped`\n(or `auditTools`) against two people\'s data:\n`https://soba.so/docs/app-tools#checking-your-tools`.\n\n**A run is end-to-end encrypted by default.** It is sealed to the user\'s own\nmachines, so Soba cannot read it, and supply Soba buys never serves it: a user\nwith no machine connected gets `no_compute`. To answer them on the app\'s own\nkey, catch that `SobaError` around `soba.run()` and call the provider as the app\ndid before; otherwise pass the refusal to the browser (step 4). Or, if the app\'s routes are meant to reach bought models or its own providers\nthrough Soba, make the client with `encrypt: false` and tell the person what\nthat changes: `https://soba.so/docs/data-handling#encrypted-runs`.\n\n### 6. What a run can do\n\nUse what the app needs, and build each from this table rather than around it:\n\n| The app needs | Use |\n|---|---|\n| A cheap job to stay cheap | `model: "small"` (or `"large"`); `"auto"` is the default |\n| The person\'s pick in the picker | Spread `useModel().run` into the request and forward `model`, `runtime`, `route` and `effort` |\n| Harder thinking | `effort`: `"low"` to `"max"` |\n| Pictures | `messages[].images`, base64 |\n| A follow-up in the same conversation | `resume` with the last `session`, or a `thread` (below) |\n| Stop when the person leaves | `signal: request.signal`, and `run.cancel()` |\n| A time limit | `maxDurationMs`; a run stopped there ends with `reason: "run_too_long"` |\n| Longer than the serving function lives, or surviving a reload | `resumable: true`, both routes returning `runResponse`, `useRun()` in the browser; elsewhere `soba.runs.attach(run.runId, { user, tools, after: run.cursor, key: run.key })` |\n| No server holding the stream open | `soba.runs.start`, with `webhook` (`events: "tools"` in production) or `answerTools: "here"` on localhost and long-lived servers; the page reads `stream` with `watchRun` |\n| Receiving those webhooks | `handleRunWebhook`, and `openRunWebhook` for an encrypted run |\n| An answer while Soba itself can\'t be reached | Nothing to write: the person switches it on under Models, and `fallback: false` on `new Soba` turns it off. `soba.fallback.flush()` in `waitUntil` on serverless |\n| A team that pays | `customer`, and `soba.customers.setMembers` so a wrong team id is refused |\n| One task of several runs counted once | `task` |\n| Its own labels on a run | `metadata` |\n| Limits on which compute | `route`, which narrows what the plan allows. Most apps leave it to the plan |\n| Work in a folder on their machine | `policy` (`cwd`, `allowTools`, `askTools`, `permissionMode`) and `approve` to answer what it asks. The machine owner\'s grant always wins |\n| A visible terminal or a git worktree | `surface: "terminal"` with `title`, or `worktree`, on `soba.runs.start`; `soba.ops` and `soba.terminals` act on them. Terminals need `encrypt: false` |\n\n`soba.runs.cancel(id)` stops a detached run. Outside a run, the same client\nreads what a server needs: `soba.users.get` (plan, allowance, what they\nconnected), `soba.users.compute`, `soba.users.setQuantity` for seats,\n`soba.plans.list`, `soba.connect()` (the app\'s name and connect key) and\n`soba.usage.list`. Full shapes:\n`https://soba.so/docs/runs`.\n\n### 7. Conversations kept on the user\'s machine\n\nAn app that has no conversation store, or whose user should keep the\nconversation when they switch AI, gives the run a `thread`: `"new"` the first\ntime, then the id its `done` reported. Send only the new message after that.\n`soba.threads` lists, reads, searches, updates, forks and deletes them. They\nare readable while one of the user\'s computers that has them is online, so an\napp that must show history at any time keeps its own and uses `resume`. A\ndesktop app can also bring in the Claude Code and Codex chats already on the\ncomputer, with `connectThreads` from `@soba-so/sdk/local`.\n`https://soba.so/docs/threads`.\n\n## The browser: one provider, a surface for each moment\n\nEverything below reads from `<SobaProvider sessionEndpoint="/api/soba/session">`.\nMount it where a surface is, with `sessionCacheKey` set to the signed-in user\'s\nid so reloads, navigations, tabs and other providers on the page share one\nsession. Never in a root layout that also renders the login page or marketing\npages: there is nobody there to mint a session for. A navbar\'s provider goes\nin the layout that draws the signed-in navbar. All the components raise the\nsame pairing modal \u2014 the provider mounts exactly one, so an app with every\nsurface cannot put two pairings on screen at once.\n\n| Surface | Component | Hook (for your own markup) |\n|---|---|---|\n| **The settings page** | `<ComputeSettings />`, alone | `useCompute()` + `useConnectButton()` |\n| **Above every control that starts a run** | `<ConnectNudge />` | `useConnectNudge()` |\n| **Where a run\'s result appears**, when it failed | `<RunLimit error={error} />` then `<RunError error={error} />` | `useRunLimit(error)` + `runErrorMessage(error)` |\n| **The signed-in navbar**, when AI only works on their compute | `<ConnectButton />` | `useConnectButton()`; its panel from `useCompute()` and `useMachineRuns()` |\n| **The composer**, in an app with one | `<ModelPicker />` beside send | `useModel()` |\n| **Billing and pricing** | `<SobaBilling />`, or `<SobaCurrentPlan />` + `<SobaPlans />`, `<SobaCheckout />`, `<RedeemCode />` | `useCurrentPlan()`, `usePlans()`, `useCheckout()`, `useRedeemCode()` |\n| **Anything a plan limits** | `<SobaGate feature="\u2026" />` | `useFeature()`, plus the server check below |\n\n**Required in every app: the first three.** The navbar follows from how the\napp\'s AI is paid for (below); the composer, billing and gates follow from what\nthe app has \u2014 a model choice to offer, plans to sell, features to limit \u2014 and\nthe plans themselves are the person\'s to decide, not yours.\n\nWhat each surface is for, and the mistakes it exists to prevent:\n\n- **Navbar, when the AI only works on their compute.** Add `<ConnectButton />`\n to the signed-in navbar when nothing can run until a user connects \u2014 a\n bring-your-own plan, a route that only allows their machine or their\n subscription, an app on a development key. There, connecting is a\n prerequisite rather than an offer, so the door belongs on every page: it\n says "Connect compute" until something is attached, then names the machine\n and its state, and once connected it is a pill that opens a popover with the\n machines and what they are running. An app whose runs fall back to compute\n it pays for does not need it; settings, the nudge and the run limit already\n meet the person where connecting matters. Wherever it is used, it lives in\n the header and only there \u2014 a popover pill is wrong inside a page.\n- **Settings.** A settings page is where somebody checks on a machine they\n already attached, not where they decide to attach one. `<ComputeSettings />`\n draws it as rows of that page in its own type: each machine, which agent the\n app\'s runs go to there, and whether it is awake, asleep or serving, with\n "Connect compute" or "Connect another computer". Nothing else from the\n package goes on that page \u2014 `<ConnectButton />` or `<ComputeStatus />` beside\n it draws the same machine twice. (`<ConnectCompute />` is its older name.) If\n there is no settings page, build one, and do not point the connect return URL\n at a page that does not render it.\n- **Above each run-starting control.** Not only a chat composer: every "Tidy",\n "Summarise", "Draft", "Generate", every form that kicks off a job \u2014 find each\n call site from step 1 and the control that triggers it. `<ConnectNudge />`\n stands there before anything is pressed and speaks only when it can help:\n nothing connected and nothing else can serve, a paired machine gone quiet, or\n an allowance running down that connecting would lift. It draws nothing\n otherwise.\n- **The result\'s place.** When a run fails, `<RunLimit error={error} />`\n renders where the answer was going to be: for `no_compute` the way to connect\n (or wake the machine), for `payment_required` the plan to upgrade to. It goes\n quiet by itself once a machine is online, so a refusal from before connecting\n is never shown as the answer to connecting. `<RunError error={error} />`\n beside it says every other failure in a sentence; the two never both speak.\n\n### One run-starting control, written both ways\n\nThe same button in any app, as components:\n\n```jsx\n"use client";\nimport { ConnectNudge, RunError, RunLimit } from "@soba-so/react";\n\nfunction TidyButton({ noteId }) {\n const [error, setError] = useState(null);\n\n async function tidy() {\n setError(null);\n const res = await fetch("/api/tidy", { method: "POST", body: JSON.stringify({ noteId }) });\n if (!res.ok) return setError(await res.json()); // Soba\'s body, per step 4\n // \u2026read the result as the app already does\n }\n\n return (\n <>\n <ConnectNudge />\n <button onClick={tidy}>Tidy</button>\n <RunLimit error={error} />\n <RunError error={error} />\n </>\n );\n}\n```\n\nAnd built from the hooks, in the app\'s own components (`Your\u2026` below stands for\nwhatever the app already draws banners, buttons and cards with), saying\neverything the components would:\n\n```jsx\nimport { runErrorMessage, useConnectNudge, useRunLimit } from "@soba-so/react";\n\nfunction TidyButton({ noteId }) {\n const [error, setError] = useState(null);\n const nudge = useConnectNudge(); // before: is anything in the way?\n const limit = useRunLimit(error); // after: the way out of a refusal\n const message = runErrorMessage(error); // after: every other failure\n\n return (\n <>\n {nudge.visible && (\n <YourBanner title={nudge.title} detail={nudge.detail} steps={nudge.steps}\n onAction={nudge.open} onDismiss={nudge.dismissible ? nudge.dismiss : undefined} />\n )}\n <YourButton onClick={tidy}>Tidy</YourButton>\n {limit ? (\n <YourCard title={limit.title} body={limit.body}\n onConnect={limit.connect}\n onUpgrade={limit.upgradeTo ? limit.upgrade : undefined} />\n ) : message ? (\n <p className="error">{message}</p>\n ) : null}\n </>\n );\n}\n```\n\nBoth halves are inside a provider. A run the browser starts, in an app with a\npicker, also carries `useModel().run`. In a chat, the nudge stands above the\ncomposer and the limit and error render in the message that failed; see "The\nchat stays theirs".\n\n## Component or hook\n\nBoth halves ship, and **the component is the answer.** Mount it even when the\napp already has its own composer, its own billing cards, its own design system\nand Tailwind everywhere. Do not look at the repo\'s styling and decide to\nrebuild one of these from its hook.\n\nThe reason is that the components are not just markup. The vendor configures\nthem in the Soba dashboard: the model picker\'s layout, which of Automatic, Fast\nand Best are offered, search, Effort, labels, the agents\' marks and the line\nunder each choice, the connect popup\'s look and theme. The\ncomponent reads all of that from the provider and draws it. A hand-built copy\nreads none of it, so every setting the vendor changes in the dashboard silently\ndoes nothing in their app, and nobody finds out until they compare the two.\n\nWhat that looks like in practice, from a real integration: an app with its own\nTailwind composer took `useModel()` and rendered it as a native\n`<select>` \u2014 no marks, no descriptions, no submenu per agent, a flat list\nwhere the dashboard said "by provider". It worked, and it was wrong.\n\nThe components fit a foreign screen on purpose: `className` on each one for\nplacement and size, `theme` on `<SobaProvider>` (or the dashboard) for\nlight and dark, `<ComputeSettings />` inherits the page\'s type, and\n`<ModelPicker />` is a pill beside a send button, not a card. The header\'s\npill takes `--sc-pill-*` custom properties, set anywhere above it, and\n`<ConnectButton />` also takes a function as children that draws the whole\ncontrol in this app\'s own markup, still opening the panel when pressed. Use\nthat when a recoloured pill would not look like it belongs:\nhttps://soba.so/docs/components#the-connect-pill. If one still\nclashes, say so to the person and leave the component in.\n\nWhere the app\'s code should decide how the picker looks, set it on the\ncomponent \u2014 `<ModelPicker layout="tabs" rows={{ fast: false }} />` \u2014 and pass\nthe same props to every `useModel()` call. A prop wins over the dashboard;\nleave out what the person wants to change there.\n\n**Reach for a hook only when the person asks for their own markup**, or for a\ndecision no component draws (`useMachineRuns()`, `useOpenSobaConnect()`,\ngating a server action on `useFeature()`). Every component is one rendering of\nan exported hook and derives nothing of its own, and a surface built from a\nhook must still show everything the component shows. Each line in the last\ncolumn is something a hand-built copy has dropped:\n\n| Component | Hook | Built from the hook, it must still show |\n|---|---|---|\n| `<ConnectButton />` | `useConnectButton()` | In the header, on every page, when the app needs their compute. `label`, which names the machine once one is attached; the state dot from `state.tone` with `state.word`; disabled when `canOpen` is false. Pressing it calls `open()`, which raises Soba\'s connect flow \u2014 never a page of your own. Its panel\'s machine list and "Running now" with Stop come from `useCompute()` and `useMachineRuns()` |\n| `<ComputeSettings />` | `useCompute()` + `useConnectButton()` | The settings page\'s section, as rows in the page\'s own type: each machine\'s `name`, `hardware`, `runsOn.name` and `status.text` with a dot from `state.tone`, `lastSeen` instead of the hardware while it is asleep; "Connect compute" with nothing connected and "Connect another computer" with something, both calling `open()`. No pill and no popover |\n| `<ComputeStatus />` | `useCompute()` | All four of `view`: loading, error, empty, machines. Each machine\'s state in words, and `stalled` called out. "Nothing connected" only when `view` is `"empty"` |\n| `<ConnectNudge />` | `useConnectNudge()` | Nothing unless `visible`. `title`, `detail`, the `meter`, the `steps` and `stalled`; a dismiss only when `dismissible`; the action is `open()` |\n| `<RunLimit />` | `useRunLimit()` | In the place the answer was going to be. `title` and `body`; Connect calling `connect()`, with `connectOffer` as its line when there is one; Upgrade only when `upgradeTo` is, calling `upgrade()`. Nothing when it returns null, which includes a `no_compute` the person has since fixed by connecting |\n| `<RunError />` | `runErrorMessage()` | Its sentence as given, nothing when it is null, and never beside a `<RunLimit />` that is speaking |\n| `<ModelPicker />` | `useModel()` | A menu, never a `<select>`. Automatic, Fast and Best (the `auto` and `size` options, whichever are offered) each with its `note`; the app\'s models laid out as `layout` says (`providers`, `panes`, `tabs`, `list`, `models`, `choices` or `automatic`, normally the vendor\'s dashboard setting); when `effortShown`, the effort levels calling `setEffort()`, drawn as `effortStyle` says, and names beside marks unless `labels` is false; every agent in `agents` with its logo, as its own submenu, and an agent with no models (Codex) as a single row; `providers` with their marks (`<ProviderMark />` draws each), and locked when the plan says so. A search field when `search` is on. `unavailable` as the stale pick it fell back from. Nothing at all when `pickable` is false. Spread `run` onto the request |\n| `<SobaPlans />` | `usePlans()` | Every offer: price, `allowance` and `allowanceNote`, `features`, the compute it runs on, the connect row, and its `cta` calling `take()`. The current plan and the featured one marked. `failed` when it is set |\n| `<SobaCurrentPlan />` | `useCurrentPlan()` | `summary`; used and remaining as a meter unless `unlimited`; `trialDaysLeft`, `periodEnd` and the `reward` when there are any |\n| `<SobaCheckout />` | `useCheckout()` | `label` on the button, `busy` and `error`, and `buy()`. Nothing is granted in the browser |\n| `<SobaGate />` | `useFeature()` | The children while allowed; otherwise the reason it is not and the plans that would allow it |\n| `<RedeemCode />` | `useRedeemCode()` | A field and an Apply that call `redeem()`, `busy`, `error` as given, and the `reward` once it lands |\n\n`<SobaBilling />` and `<ConnectModal />` are compositions of the above and\nhave no rule of their own. `<ConnectPill />` is the half of `<ConnectButton />`\nthat reports \u2014 the mark, the state and the machine, with no popover under it\nand no flow behind it. It is for an app whose person asked for their own panel;\notherwise the header gets `<ConnectButton />`, panel included. Pressing the pill\nis yours to wire, and it still opens Soba\'s flow through\n`useSoba().connect.open()`; everything it says is `connectSays`.\n`<SobaProvider>` is needed either way: the hooks read from it, so a hook with no\nprovider above it is the one mistake this split invites.\n\nA gate draws the button; it does not secure the action. On the server, ask\nbefore you create: `soba.users.check(user, "workspaces", { use: 1 })` answers\n`{ allowed, reason }` and counts the use in the same call, so two requests for\nthe last one cannot both get it. Record use you did not ask about with\n`soba.users.track(user, "workspaces", -1)` when one is deleted. Prices,\nallowances and the connected reward come from the plan objects, so changing\nthem later is not a deploy. Pass `showConnect` to `<SobaPlans />` only on a page\nwith no current-plan card: a bring-your-own plan would otherwise state a\nrequirement with no way to meet it.\n\nThree belong to no component of their own. `useOpenSobaConnect()` brings the\nSoba app forward on this person\'s machine and hands back the one honest thing a\npage can say about having tried \u2014 a browser cannot tell whether a `soba://`\nlink was answered, and a page that claims it worked is guessing.\n`useRun()` is for a run started in the browser that must outlive the page: a\nreload, a page switch or a dropped connection only stops the reading, and it\nreads on by itself. It takes your two routes, both returning `runResponse`\nfrom `@soba-so/sdk`: one around `soba.run({ resumable: true })`, one around\n`soba.runs.attach`. `watchRun(stream)` reads a run your server started with\n`soba.runs.start`, straight from Soba.\n\n`useMachineRuns()` is the "Running now" list out of `<ConnectButton />`\'s\npanel with no panel around it: what this person\'s machines are running FOR THIS\nAPP, and `stop(runId)` to end one as the person whose machine it is on; the app\nthat started that run sees it finish with `reason: "stopped_by_user"`.\n`useRedeemCode()` is a promo code field\'s behaviour: `redeem(code)` gives the\nuser what the app\'s reward hands out and re-reads their plan, so the allowance\non screen moves without a reload; `<RedeemCode />` is that field already drawn.\n\n`useSoba()` is the raw provider state. Reach for a named hook first and use\nthis one for what no hook covers \u2014 `run()`, `connect.open()`,\n`plan.refresh()`. A page that reads `compute.connected` or `plan.remaining`\nstraight off it is re-deriving a decision that is already exported, and the two\ncopies are how our own apps drifted.\n\n### What not to write yourself\n\nThese are not style preferences. Each one is a judgement this package already\nmakes, and each has been got wrong in production \u2014 in our own code, which is why\nthey are exported at all. If you find yourself writing one of them, delete it\nand import the answer:\n\n- **A list of model names.** The names come off the person\'s own machine, so a\n list in your code refuses the model they can see on their own screen.\n `useModel()` reads it from what they have connected.\n- **A model id on a run without its agent.** Soba applies a person\'s own agent\n preference only to a run whose model is blank or a size, so a named model\n travelling alone goes to whichever agent is found first. Spread\n `useModel().run` whole \u2014 it is `{ model, runtime?, route?, effort? }` \u2014 and\n have your route forward all four to `soba.run()`.\n- **"Nothing connected yet."** That is a claim about somebody\'s account and it\n is only true once the account has been read. Said while the first request is\n in flight, or after it failed, it tells a person with a paired laptop that it\n has vanished. `useCompute().view` is the four-way answer.\n- **A match on an error message, or an error line of your own for a refusal.**\n `useRunLimit` and `runErrorMessage` read the CODE. Messages are prose we\n rewrite, matching on them breaks on a copy edit, and Soba\'s own refusal text\n names internal ids no user should see.\n- **Words for a cost class.** `tierLabel(tier)` is the one glossary for the five\n economics this product is about. Four hand-written copies in this repo\n disagreed with each other, and three reported somebody\'s own API key as\n frontier supply the app had paid for.\n- **Where the pick is remembered, or how a stale one is handled.** A model whose\n machine is gone falls back to Automatic and stays picked. `useModel()` does\n that and tells you with `unavailable`.\n\nRead `https://soba.so/docs/components` for each hook\'s full shape.\n\n## The chat stays theirs\n\nThere is no chat component, on purpose. An app built on Soba already has its own\ncomposer and its own messages, and they are the product. Keep every line of\nthat markup. What Soba adds goes INTO it, and these are the things a chat on\nSoba has to handle \u2014 check each one against the code, not against memory:\n\n**In the composer**\n\n- `<ModelPicker />` in the composer\'s footer, beside the send button. The\n component, per the section above, not a copy.\n- Spread `useModel().run` onto the request, and have the route forward\n `model`, `runtime`, `route` and `effort`.\n- Send becomes Stop while a run is going. Stop aborts the request\'s\n `signal`, and a run the person stopped is not an error to show. Neither is\n `reason: "stopped_by_user"`, which is the machine\'s owner stopping it\n from their side.\n- `<ConnectNudge />` above the composer. It draws nothing until it has\n something to say.\n- Images, only if the composer already takes them: forward each message\'s\n `images` and the runtimes that can see them will.\n\n**In the messages**\n\n- `delta` text is appended as it arrives. `thinking` is the running total\n and REPLACES what is shown \u2014 appending it repeats every sentence. Fold it\n away by default.\n- `status` events are what the agent is doing: show `message`, and\n `toolInput` beside it when there is one. `state: "interrupted"` means\n the person\'s machine went offline mid-run and `"resumed"` that it came\n back; say so in the answer, because the run goes on either way.\n- A failed run renders `<RunLimit />` where the answer was going to be, and\n `<RunError />` beside it for everything else. Branch on the `reason`\n code, never the message. Offer Retry only when `retryable` is not false.\n- Copy on every answer, on hover, copying the text as written (markdown, not\n rendered HTML). Retry on the last one.\n- `done` carries `usage` and `tier`. If the app shows what answered,\n word the tier with `tierLabel()`.\n\n**Across turns**\n\n- `done` and `error` carry a `session`. Send it back as `resume`\n on the next run, with the same `runtime`, and have the route forward it, so a\n follow-up continues the agent\'s conversation instead of starting a new one\n with the whole transcript pasted in. A chat on `thread` (step 7) sends the\n thread id and the new message instead, and any AI can carry it on.\n\nAn app with no chat at all gets one built in its own components and styles,\nthe same way it would build any other screen \u2014 with everything above in it.\n\n## Proving it\n\n`soba/echo` is answered by Soba itself \u2014 no machine, no metered supply,\nnothing billed \u2014 and still proves the key, the base URL and the `user` field:\n\n```sh\ncurl https://api.soba.so/v1/chat/completions \\\n -H "Authorization: Bearer $SOBA_KEY" \\\n -H "Content-Type: application/json" \\\n -d \'{ "model": "soba/echo", "user": "usr_123",\n "messages": [{ "role": "user", "content": "ping" }] }\'\n```\n\nA curl is evidence the credential works. It is NOT evidence the app is\nintegrated \u2014 the dashboard\'s integrate step ticks on a request arriving from the\nreal call site, and it cannot tell a curl from a deployment. Do not send one to\nmake a checklist go green. Before calling the integration done, walk the\nrequired surfaces as a signed-in user with nothing connected: settings says\n"Connect compute", the nudge stands above each run-starting control when\nconnecting would help, pressing one shows the limit card where the result\nwould have been (and the navbar says "Connect compute", where there is one) \u2014\nthen connect, and each of them goes quiet.\n\n## Running the app without the dashboard\n\nEverything the dashboard does for an app can be done from the terminal, the SDK\nor the management API, signed in as the person (step 2\'s login, or a workspace\nkey): settings (connect popup, model picker, which AI users may connect,\nlimits), providers and models, plans, rewards, users, runs, keys, people,\nStripe and Soba\'s own billing.\n\n npx -y @soba-so/cli settings set model_picker.menu=tabs --environment development\n npx -y @soba-so/cli plans create --help\n npx -y @soba-so/cli api GET <path> # any management endpoint, any method\n\nIn code it is `SobaManagement` from `@soba-so/sdk`, which never runs anything.\nReference: `https://soba.so/docs/reference/cli` and\n`https://soba.so/docs/reference/http-api`. Do what the person asked for and no\nmore: say which environment a change lands in, and ask before anything in\nproduction.\n\n## A new project rather than an existing one\n\nThere is no separate procedure for this and no question to ask the person: look\nat the directory. If there is no app yet, run `npx create-soba@latest` and let\nit write one \u2014 it ships a correct `/api/soba/session`, which is the security\nboundary of the whole integration, and a plausible hand-written one is the\nfailure mode that matters. Then the server half is already done and what\nremains is the key.\n\n## What is not yours to do\n\nPairing is a person installing the Soba app on their own laptop and approving\nit. Pricing, allowances and rewards are decisions about somebody\'s business,\nas is anything that charges them or their users, or cannot be undone. Cards and\nStripe sign-ins are typed by a person on Stripe\'s page. Do none of it on their\nbehalf; say what is left and stop. Going live needs no plan or card; what Soba\nthen charges the vendor is on `https://soba.so/docs/billing`.';var L=[{name:"set_up",title:"Set Soba up in this repo",description:"Works through Soba's setup checklist one step at a time, editing this repo and showing you each diff.",text:`Set this project up on Soba, working from the real checklist rather than from memory.
540
3
 
541
4
  The loop, and keep to it:
542
5
 
@@ -562,7 +25,7 @@ Three things not to do:
562
25
  - Do not put the secret key anywhere but \`.env.local\`, and check that file is
563
26
  gitignored before you write it. Do not echo it back to the terminal.
564
27
  - Do not guess the connect return URL. It has to be a page that actually renders
565
- \`<ConnectCompute />\`; if there isn't one yet, build it first.
28
+ \`<ComputeSettings />\`; if there isn't one yet, build it first.
566
29
 
567
30
  Start with \`soba_status\`.
568
31
 
@@ -575,15 +38,15 @@ ${H}`}],V=new Map(L.map(e=>[e.name,e]));function m(e){process.stderr.write(`soba
575
38
  `)}function J(e){process.stdout.write(`${JSON.stringify(e)}
576
39
  `)}function z(e){let t="",n=new Set,r=!1,o=s=>{n.add(s),s.finally(()=>{n.delete(s),r&&n.size===0&&process.exit(0)})};process.stdin.setEncoding("utf8"),process.stdin.on("data",s=>{t+=s;let u=t.indexOf(`
577
40
  `);for(;u!==-1;){let l=t.slice(0,u).trim();t=t.slice(u+1),l&&o(ke(l,e)),u=t.indexOf(`
578
- `)}}),process.stdin.on("end",()=>{r=!0,n.size===0&&process.exit(0),setTimeout(()=>process.exit(0),1e4).unref()})}async function ke(e,t){let n;try{n=JSON.parse(e)}catch{m("ignored a line that was not json");return}let r=n.id===void 0||n.id===null;try{let o=await t(n.method,n.params??{});r||J({jsonrpc:"2.0",id:n.id,result:o})}catch(o){if(r)return;let s=o instanceof Error?o.message:String(o),u=s==="method not found"?-32601:-32603;J({jsonrpc:"2.0",id:n.id,error:{code:u,message:s}})}}import{readFileSync as ue,realpathSync as I}from"node:fs";import b from"node:path";import{spawnSync as X}from"node:child_process";import{existsSync as Z}from"node:fs";import{appendFile as ve,chmod as Se,readFile as Q,writeFile as xe}from"node:fs/promises";import M from"node:path";var Ae=e=>new RegExp(`^\\s*(?:export\\s+)?${e}\\s*=`);async function ee(e,t,n){let r=Z(e),o=r?await Q(e,"utf8"):"",s=o===""?[]:o.replace(/\n$/,"").split(`
579
- `),u=[];for(let[l,h]of Object.entries(t)){let f=s.findIndex(g=>Ae(l).test(g));f===-1?u.push(`${l}=${h}`):s[f]=`${l}=${h}`}u.length>0&&(s.length>0&&s[s.length-1].trim()!==""&&s.push(""),n&&s.push(...n.split(`
580
- `).map(l=>`# ${l}`)),s.push(...u)),await xe(e,`${s.join(`
41
+ `)}}),process.stdin.on("end",()=>{r=!0,n.size===0&&process.exit(0),setTimeout(()=>process.exit(0),1e4).unref()})}async function ke(e,t){let n;try{n=JSON.parse(e)}catch{m("ignored a line that was not json");return}let r=n.id===void 0||n.id===null;try{let o=await t(n.method,n.params??{});r||J({jsonrpc:"2.0",id:n.id,result:o})}catch(o){if(r)return;let s=o instanceof Error?o.message:String(o),u=s==="method not found"?-32601:-32603;J({jsonrpc:"2.0",id:n.id,error:{code:u,message:s}})}}import{readFileSync as ue,realpathSync as I}from"node:fs";import b from"node:path";import{spawnSync as X}from"node:child_process";import{existsSync as Z}from"node:fs";import{appendFile as ve,chmod as Se,readFile as Q,writeFile as Ae}from"node:fs/promises";import M from"node:path";var xe=e=>new RegExp(`^\\s*(?:export\\s+)?${e}\\s*=`);async function ee(e,t,n){let r=Z(e),o=r?await Q(e,"utf8"):"",s=o===""?[]:o.replace(/\n$/,"").split(`
42
+ `),u=[];for(let[l,h]of Object.entries(t)){let f=s.findIndex(g=>xe(l).test(g));f===-1?u.push(`${l}=${h}`):s[f]=`${l}=${h}`}u.length>0&&(s.length>0&&s[s.length-1].trim()!==""&&s.push(""),n&&s.push(...n.split(`
43
+ `).map(l=>`# ${l}`)),s.push(...u)),await Ae(e,`${s.join(`
581
44
  `)}
582
45
  `),r||await Se(e,384).catch(()=>{})}async function te(e){let t=M.dirname(e);if(X("git",["rev-parse","--is-inside-work-tree"],{cwd:t}).status!==0||X("git",["check-ignore","-q",M.basename(e)],{cwd:t}).status===0)return null;let o=M.join(t,".gitignore"),s=Z(o)?await Q(o,"utf8"):"",u=s===""||s.endsWith(`
583
46
  `)?"":`
584
47
  `;return await ve(o,`${u}${M.basename(e)}
585
- `),o}var C={type:"string",description:"The app's id, from soba_list_apps."},d={type:"string",enum:["development","production"]},i=e=>({type:"string",...e?{description:e}:{}}),c=(e,t)=>({type:[e,"null"],...t?{description:t}:{}}),p=e=>({type:"boolean",...e?{description:e}:{}}),N={limit:{type:"number",description:"Up to 200."},offset:{type:"number"}},F=(e,t)=>{let n=e[t];if(typeof n!="string"||!n)throw new Error(`${t} is required.`);return n};function a(e,t,n,r,o,s={},u=[],l){let h=[...r.matchAll(/:(\w+)/g)].map(f=>f[1]);return{name:e,title:t,description:o,credentials:["account"],inputSchema:{type:"object",properties:{...h.includes("app")?{app:C}:{},...h.includes("workspace")?{workspace:i("The workspace's id, from soba_list_workspaces.")}:{},...s},required:[...new Set([...h,...u])],additionalProperties:!1},run:async(f,g)=>{let S=`/v1${r.replace(/:(\w+)/g,(K,O)=>encodeURIComponent(F(g,O)))}`,x=Object.fromEntries(Object.entries(g).filter(([K,O])=>!h.includes(K)&&O!==void 0));return JSON.stringify(await $(f,n,S,l?l(x):x),null,2)}}}async function $(e,t,n,r){if(t==="GET"||t==="DELETE"){let o=new URLSearchParams(Object.entries(r).map(([u,l])=>[u,String(l)])).toString(),s=o?`${n}?${o}`:n;return t==="GET"?e.get(s):e.delete(s)}return t==="PUT"?e.put(n,r):t==="PATCH"?e.patch(n,r):e.post(n,r)}function ne({api_key_env:e,env_file:t,...n}){if(e===void 0)return n;let r=String(e),o=process.env[r];if(!o){let s=b.resolve(typeof t=="string"?t:".env.local");try{o=ue(s,"utf8").split(`
586
- `).map(l=>l.trim().replace(/^export\s+/,"")).find(l=>l.startsWith(`${r}=`))?.slice(r.length+1).trim().replace(/^(["'])(.*)\1$/,"$2")}catch{}}if(!o)throw new Error(`${r} is not set here or in ${t??".env.local"}. Ask the person to put the key there; do not ask them to paste it to you.`);return{...n,api_key:o}}function Ee(e){let t=I(b.resolve(e)),n=I(process.cwd());if(!t.startsWith(n+b.sep))throw new Error("That file is outside this project.");return t}function U({file:e,...t}){let n;try{n=ue(Ee(String(e)))}catch(r){throw new Error(`Could not read ${e}: ${r.message}`)}if(n.length>2*1024*1024)throw new Error("That image is over 2MB.");return{...t,data:n.toString("base64")}}function re(e){return{name:e.name,title:e.title,description:e.description,credentials:["account"],inputSchema:{type:"object",properties:{...e.properties,env_file:i("Default .env.local.")},required:e.required,additionalProperties:!1},run:async(t,{env_file:n,...r})=>{let o=typeof n=="string"?n:".env.local";if(!/^(\.env|\.dev\.vars)/.test(b.basename(o)))throw new Error("env_file must be an .env file or .dev.vars.");let s=b.resolve(o),u=I(b.dirname(s)),l=I(process.cwd());if(u!==l&&!u.startsWith(l+b.sep))throw new Error("env_file must be in this project.");await te(s);let h=`/v1${e.route.replace(/:(\w+)/g,(S,x)=>encodeURIComponent(F(r,x)))}`,f=Object.fromEntries(Object.entries(r).filter(([S])=>!e.route.includes(`:${S}`))),g=await t.post(h,f);return await ee(s,{[e.variable(r)]:g.key},"Soba"),`Made ${g.id} and wrote it to ${o} as ${e.variable(r)}. It was not shown.`}}}var Te={api_key_env:i("The environment variable holding the key, e.g. OPENAI_API_KEY. Read from this machine; never pass the key itself."),env_file:i("Where that variable is, if not the environment. Default .env.local.")},oe={name:i(),base_url:i("https, OpenAI-compatible. Not needed with a service."),cost_class:{type:"string",enum:["frontier","open-weights"]},max_cost_per_run:c("number","Dollars."),...Te},y=i("From soba_list_providers."),se={name:i(),kind:{type:"string",enum:["discount","grant","plan"]},discount_type:{type:"string",enum:["percent","fixed"]},amount:c("number","20 is 20%, or dollars when fixed."),duration_months:c("number"),plans:{type:["array","null"],items:{type:"string"}},first_time_only:p(),grants:{type:"array",items:{type:"object",properties:{feature:i(),name:i(),type:{type:"string",enum:["boolean","number","text"]},amount:c("number"),expiry_days:c("number")},required:["feature"]}},plan:i("The plan a plan reward gives, by id."),duration_days:{type:"number"},trigger:{type:"string",enum:["none","signup","first_connect"]},codes:{type:"array",description:"The whole list: one left out is removed.",items:{type:"object",properties:{code:i(),cap:c("number")},required:["code"]}}},ie={type:"string",enum:["admin","member","billing"]};function ae(e,t){let{app:n,environment:r,...o}=t;if(e.kind==="setup")return{path:"/v1/manage/settings",environment:r?{environment:r}:{},rest:o};if(typeof n!="string"||!n)throw new Error("Say which app: pass its id as `app`. soba_list_apps lists them.");if(!r)throw new Error("Say which environment: development or production.");return{path:`/v1/apps/${encodeURIComponent(n)}/settings`,environment:{environment:r},rest:o}}var D={app:{...C,description:`${C.description} Not needed with a setup key.`},environment:{...d,description:"Required with an account; a setup key is development."}},le=[{name:"soba_get_settings",title:"Read the app's settings",description:"Connect popup, model picker, which AI users may connect, and the app's limits, in one environment. The Models, Connect popup, Model picker and Settings pages.",credentials:["setup","account"],inputSchema:{type:"object",properties:D,additionalProperties:!1},run:async(e,t)=>{let n=ae(e,t),r=e.kind==="account"?n.environment:{};return JSON.stringify(await $(e,"GET",n.path,r),null,2)}},{name:"soba_update_settings",title:"Change the app's settings",description:"Changes only what you send. connect_popup, model_picker, own_ai, ask_to_connect and connect_return_url belong to one environment; the rest hold in both and need an account.",credentials:["setup","account"],inputSchema:{type:"object",properties:{...D,connect_popup:{type:"object",properties:{theme:{type:"string",enum:["light","dark","system"]},accent:c("string","Hex, like #4F46E5. Null is the default."),background:c("string","Hex. The whole popup follows it."),logo:{type:"string",enum:["favicon","soba","custom","none"]},logo_url:c("string","https. Makes logo custom."),hosted:p(),show_code:p(),button:{type:"string",enum:["solid","outline"],description:"Continue with Soba: filled in the accent, or outlined."}},additionalProperties:!1},model_picker:{type:"object",properties:{users_choose:p("False is no picker."),menu:{type:"string",enum:["submenus","two_panes","tabs"]},presets:{type:"object",properties:{automatic:p(),fast:p(),best:p()},additionalProperties:!1},search:p(),effort:p("The Effort row under the models."),effort_style:{type:"string",enum:["switch","list"]},labels:p("False: logos alone for the AIs and providers."),suggested:p("False hides the Suggested group; true brings it back.")},additionalProperties:!1},own_ai:{type:["array","null"],items:{type:"string"},description:"AIs users may connect: claude, chatgpt, gemini, local\u2026 Null is all."},ask_to_connect:p("Ask to connect before using AI the app pays for."),connect_return_url:c("string"),name:i(),icon:c("string","An https image address or one emoji."),run_limit_minutes:c("number"),max_cost_per_run:c("number","Dollars, over every plan."),route_allow:{type:["array","null"],items:{type:"string"},description:"Cost classes the app may ever run on, over every plan. Null is all."},provider_failover:p("Try another of the app's providers when one fails."),outage_fallback:p("Use the app's providers while Soba is down. Lets a holder of the secret key fetch the provider keys: only when a person asked."),use_soba:p("Use Soba's compute for now, with no provider of the app's own.")},additionalProperties:!1},run:async(e,t)=>{let n=ae(e,t),r=await $(e,"PATCH",n.path,{...n.environment,...n.rest});return`Saved. Settings are now:
48
+ `),o}var C={type:"string",description:"The app's id, from soba_list_apps."},d={type:"string",enum:["development","production"]},i=e=>({type:"string",...e?{description:e}:{}}),c=(e,t)=>({type:[e,"null"],...t?{description:t}:{}}),p=e=>({type:"boolean",...e?{description:e}:{}}),N={limit:{type:"number",description:"Up to 200."},offset:{type:"number"}},F=(e,t)=>{let n=e[t];if(typeof n!="string"||!n)throw new Error(`${t} is required.`);return n};function a(e,t,n,r,o,s={},u=[],l){let h=[...r.matchAll(/:(\w+)/g)].map(f=>f[1]);return{name:e,title:t,description:o,credentials:["account"],inputSchema:{type:"object",properties:{...h.includes("app")?{app:C}:{},...h.includes("workspace")?{workspace:i("The workspace's id, from soba_list_workspaces.")}:{},...s},required:[...new Set([...h,...u])],additionalProperties:!1},run:async(f,g)=>{let S=`/v1${r.replace(/:(\w+)/g,(K,O)=>encodeURIComponent(F(g,O)))}`,A=Object.fromEntries(Object.entries(g).filter(([K,O])=>!h.includes(K)&&O!==void 0));return JSON.stringify(await $(f,n,S,l?l(A):A),null,2)}}}async function $(e,t,n,r){if(t==="GET"||t==="DELETE"){let o=new URLSearchParams(Object.entries(r).map(([u,l])=>[u,String(l)])).toString(),s=o?`${n}?${o}`:n;return t==="GET"?e.get(s):e.delete(s)}return t==="PUT"?e.put(n,r):t==="PATCH"?e.patch(n,r):e.post(n,r)}function ne({api_key_env:e,env_file:t,...n}){if(e===void 0)return n;let r=String(e),o=process.env[r];if(!o){let s=b.resolve(typeof t=="string"?t:".env.local");try{o=ue(s,"utf8").split(`
49
+ `).map(l=>l.trim().replace(/^export\s+/,"")).find(l=>l.startsWith(`${r}=`))?.slice(r.length+1).trim().replace(/^(["'])(.*)\1$/,"$2")}catch{}}if(!o)throw new Error(`${r} is not set here or in ${t??".env.local"}. Ask the person to put the key there; do not ask them to paste it to you.`);return{...n,api_key:o}}function Te(e){let t=I(b.resolve(e)),n=I(process.cwd());if(!t.startsWith(n+b.sep))throw new Error("That file is outside this project.");return t}function U({file:e,...t}){let n;try{n=ue(Te(String(e)))}catch(r){throw new Error(`Could not read ${e}: ${r.message}`)}if(n.length>2*1024*1024)throw new Error("That image is over 2MB.");return{...t,data:n.toString("base64")}}function re(e){return{name:e.name,title:e.title,description:e.description,credentials:["account"],inputSchema:{type:"object",properties:{...e.properties,env_file:i("Default .env.local.")},required:e.required,additionalProperties:!1},run:async(t,{env_file:n,...r})=>{let o=typeof n=="string"?n:".env.local";if(!/^(\.env|\.dev\.vars)/.test(b.basename(o)))throw new Error("env_file must be an .env file or .dev.vars.");let s=b.resolve(o),u=I(b.dirname(s)),l=I(process.cwd());if(u!==l&&!u.startsWith(l+b.sep))throw new Error("env_file must be in this project.");await te(s);let h=`/v1${e.route.replace(/:(\w+)/g,(S,A)=>encodeURIComponent(F(r,A)))}`,f=Object.fromEntries(Object.entries(r).filter(([S])=>!e.route.includes(`:${S}`))),g=await t.post(h,f);return await ee(s,{[e.variable(r)]:g.key},"Soba"),`Made ${g.id} and wrote it to ${o} as ${e.variable(r)}. It was not shown.`}}}var Ee={api_key_env:i("The environment variable holding the key, e.g. OPENAI_API_KEY. Read from this machine; never pass the key itself."),env_file:i("Where that variable is, if not the environment. Default .env.local.")},oe={name:i(),base_url:i("https, OpenAI-compatible. Not needed with a service."),cost_class:{type:"string",enum:["frontier","open-weights"]},max_cost_per_run:c("number","Dollars."),...Ee},y=i("From soba_list_providers."),se={name:i(),kind:{type:"string",enum:["discount","grant","plan"]},discount_type:{type:"string",enum:["percent","fixed"]},amount:c("number","20 is 20%, or dollars when fixed."),duration_months:c("number"),plans:{type:["array","null"],items:{type:"string"}},first_time_only:p(),grants:{type:"array",items:{type:"object",properties:{feature:i(),name:i(),type:{type:"string",enum:["boolean","number","text"]},amount:c("number"),expiry_days:c("number")},required:["feature"]}},plan:i("The plan a plan reward gives, by id."),duration_days:{type:"number"},trigger:{type:"string",enum:["none","signup","first_connect"]},codes:{type:"array",description:"The whole list: one left out is removed.",items:{type:"object",properties:{code:i(),cap:c("number")},required:["code"]}}},ie={type:"string",enum:["admin","member","billing"]};function ae(e,t){let{app:n,environment:r,...o}=t;if(e.kind==="setup")return{path:"/v1/manage/settings",environment:r?{environment:r}:{},rest:o};if(typeof n!="string"||!n)throw new Error("Say which app: pass its id as `app`. soba_list_apps lists them.");if(!r)throw new Error("Say which environment: development or production.");return{path:`/v1/apps/${encodeURIComponent(n)}/settings`,environment:{environment:r},rest:o}}var D={app:{...C,description:`${C.description} Not needed with a setup key.`},environment:{...d,description:"Required with an account; a setup key is development."}},le=[{name:"soba_get_settings",title:"Read the app's settings",description:"Connect popup, model picker, which AI users may connect, and the app's limits, in one environment. The Models, Connect popup, Model picker and Settings pages.",credentials:["setup","account"],inputSchema:{type:"object",properties:D,additionalProperties:!1},run:async(e,t)=>{let n=ae(e,t),r=e.kind==="account"?n.environment:{};return JSON.stringify(await $(e,"GET",n.path,r),null,2)}},{name:"soba_update_settings",title:"Change the app's settings",description:"Changes only what you send. connect_popup, model_picker, own_ai, ask_to_connect and connect_return_url belong to one environment; the rest hold in both and need an account.",credentials:["setup","account"],inputSchema:{type:"object",properties:{...D,connect_popup:{type:"object",properties:{theme:{type:"string",enum:["light","dark","system"]},accent:c("string","Hex, like #4F46E5. Null is the default."),background:c("string","Hex. The whole popup follows it."),logo:{type:"string",enum:["favicon","soba","custom","none"]},logo_url:c("string","https. Makes logo custom."),hosted:p(),show_code:p(),button:{type:"string",enum:["solid","outline"],description:"Continue with Soba: filled in the accent, or outlined."}},additionalProperties:!1},model_picker:{type:"object",properties:{users_choose:p("False is no picker."),menu:{type:"string",enum:["submenus","two_panes","tabs","single"]},presets:{type:"object",properties:{automatic:p(),fast:p(),best:p()},additionalProperties:!1},search:p(),effort:p("The Effort row under the models."),effort_style:{type:"string",enum:["switch","list"]},labels:p("False: logos alone for the AIs and providers."),suggested:p("False hides the Suggested group; true brings it back.")},additionalProperties:!1},own_ai:{type:["array","null"],items:{type:"string"},description:"AIs users may connect: claude, chatgpt, gemini, local\u2026 Null is the default (claude, chatgpt). [] turns users' own AI off: no run reaches it."},ask_to_connect:p("Ask to connect before using AI the app pays for."),connect_return_url:c("string"),name:i(),icon:c("string","An https image address or one emoji."),run_limit_minutes:c("number"),max_cost_per_run:c("number","Dollars, over every plan."),route_allow:{type:["array","null"],items:{type:"string"},description:"Cost classes the app may ever run on, over every plan. Null is all."},provider_failover:p("Try another of the app's providers when one fails."),outage_fallback:p("Use the app's providers while Soba is down. Lets a holder of the secret key fetch the provider keys: only when a person asked."),use_soba:p("Use Soba's compute for now, with no provider of the app's own.")},additionalProperties:!1},run:async(e,t)=>{let n=ae(e,t),r=await $(e,"PATCH",n.path,{...n.environment,...n.rest});return`Saved. Settings are now:
587
50
  ${JSON.stringify(r,null,2)}`}},a("soba_list_workspaces","List workspaces","GET","/workspaces","Your workspaces."),a("soba_create_app","Create an app","POST","/workspaces/:workspace/apps","Makes an app. Counts against the tier's app limit.",{name:i()},["name"]),a("soba_list_keys","List keys","GET","/apps/:app/keys","The app's keys, as previews, and what each may spend a month."),re({name:"soba_create_app_key",title:"Make a key",description:"Makes a secret key and writes it to the project's env file, never into the conversation. development is SOBA_KEY; production is SOBA_PROD_KEY.",route:"/apps/:app/keys",properties:{app:C,environment:d,replace_idle:p("Replace one never used.")},required:["app","environment"],variable:e=>e.environment==="production"?"SOBA_PROD_KEY":"SOBA_KEY"}),re({name:"soba_create_workspace_key",title:"Make a workspace key",description:"Makes a key that makes apps and mints their keys, and writes it to the env file as SOBA_WORKSPACE_KEY. Only when a person asked for one.",route:"/workspaces/:workspace/keys",properties:{workspace:i("From soba_list_workspaces."),name:i()},required:["workspace"],variable:()=>"SOBA_WORKSPACE_KEY"}),a("soba_set_key_cap","Cap a key","PATCH","/apps/:app/keys/:key","The most a key may spend a month, in dollars. Null is no cap.",{key:i("From soba_list_keys."),monthly_cap:c("number")},["monthly_cap"]),a("soba_list_workspace_keys","List workspace keys","GET","/workspaces/:workspace/keys","By name. Never the keys."),a("soba_revoke_workspace_key","Revoke a workspace key","DELETE","/workspaces/:workspace/keys/:key","Anything using it stops at once. Only when a person asked.",{key:i()}),a("soba_get_billing","Read billing","GET","/workspaces/:workspace/billing","Whether the workspace is on a plan (live), its tier, the tiers and what they cost, card and invoices. No plan is needed to use production."),a("soba_go_live","Buy a plan","POST","/workspaces/:workspace/billing/go_live","Only when a person chooses a plan: production works without one, on the workspace's one-time free connected users. Answers with Stripe's page to pay for the plan. Give the person the link: never ask for card details or fill them in. Then call soba_get_billing until live is true.",{tier:i("The one a person chose, from soba_get_billing.")},["tier"]),a("soba_change_card","Change the card","POST","/workspaces/:workspace/billing/card","Answers with Stripe's page. Give the person the link."),a("soba_change_tier","Change the tier","POST","/workspaces/:workspace/billing/tier","Charges the card on file. Tell the person the fee and get a yes first. An owner only.",{tier:i(),confirm_fee:{type:"number",description:"The fee they agreed to."}},["tier","confirm_fee"]),a("soba_cancel_subscription","Cancel the subscription","POST","/workspaces/:workspace/billing/cancel","Ends with the period. Only when a person asked for exactly this.",{confirm:i("The workspace's name, which the person gave you.")},["confirm"]),a("soba_get_stripe","Read the Stripe connection","GET","/workspaces/:workspace/stripe","Whether the workspace's own Stripe is connected, which its users pay into.",{environment:d},["environment"]),a("soba_connect_stripe","Connect Stripe","POST","/workspaces/:workspace/stripe/connect","Answers with Stripe's screen. The person accepts it, signed in to Soba as themselves. Then call soba_get_stripe until connected is true.",{environment:d},["environment"]),a("soba_disconnect_stripe","Disconnect Stripe","DELETE","/workspaces/:workspace/stripe","Nobody can buy a plan after. Only when a person asked for exactly this.",{environment:d,confirm:i("The workspace's name, which the person gave you.")},["environment","confirm"]),a("soba_list_repricing","Subscribers on old prices","GET","/apps/:app/repricing","People still paying a plan's old price, waiting for a decision."),a("soba_decide_repricing","Keep or move subscribers","POST","/apps/:app/repricing","keep leaves them on the old price; move changes what they pay at their next renewal. Tell the person how many and from what to what, and get a yes first.",{old_price:i("From soba_list_repricing."),decision:{type:"string",enum:["keep","move"]},confirm_subscribers:{type:"number",description:"To move: how many they agreed to."}},["old_price","decision"]),a("soba_check_stripe","Check Stripe","POST","/apps/:app/stripe/check","Compares the app's plans with what is in Stripe."),a("soba_restore_stripe_plan","Restore a plan in Stripe","POST","/apps/:app/plans/:plan/stripe/restore","Puts a plan back where it was changed in Stripe directly.",{plan:i()}),a("soba_accept_stripe_change","Leave a change in Stripe","POST","/apps/:app/plans/:plan/stripe/accept","Leaves a change somebody made in Stripe.",{plan:i(),kind:i("As the check reported it.")},["kind"]),a("soba_try_checkout","Try checkout","POST","/apps/:app/plans/:plan/try_checkout","A checkout link for a plan, as a preview buyer. In live mode paying it takes real money.",{plan:i()}),a("soba_set_seats","Set a seat count","PUT","/apps/:app/plans/:plan/seats","Corrects how many seats one user is billed for. Only with a number a person gave you.",{plan:i(),user:i("Your id for them."),quantity:{type:"number"}},["user","quantity"]),a("soba_set_logo","Set a logo from a file","PUT","/apps/:app/logo","The app's icon, or one environment's connect popup logo. PNG, JPEG, GIF, WebP or SVG, up to 2MB.",{file:i("The image's path in this project."),use:{type:"string",enum:["icon","connect_popup"]},environment:{...d,description:"With connect_popup."}},["file"],U),a("soba_set_custom_model_logo","Set a custom model's logo","PUT","/apps/:app/custom_models/:alias/logo","From an image file.",{alias:i(),file:i("The image's path in this project.")},["file"],U),a("soba_set_workspace_logo","Set the workspace's picture","PUT","/workspaces/:workspace/logo","From an image file.",{file:i("The image's path in this project.")},["file"],U),a("soba_update_workspace","Rename the workspace","PATCH","/workspaces/:workspace/settings","Its name, or its picture as an https address or one emoji.",{name:i(),icon:c("string")}),a("soba_transfer_workspace","Transfer the workspace","POST","/workspaces/:workspace/transfer","Hands it over; the owner becomes an admin. Only when the owner asked for exactly this.",{member:i("Their id or email."),confirm:i("The workspace's name, which they gave you.")},["member","confirm"]),a("soba_delete_workspace","Delete the workspace","POST","/workspaces/:workspace/delete","Deletes every app, user, run and key in it. It cannot come back. Only when the owner asked for exactly this and gave you its name.",{confirm:i("The workspace's name, which they gave you.")},["confirm"]),a("soba_update_app","Rename an app","PATCH","/apps/:app","Its name.",{name:i()},["name"]),a("soba_delete_app","Delete an app","DELETE","/apps/:app","Deletes the app and everything that is its. It cannot come back. Only when a person asked for exactly this."),{name:"soba_pair_machine",title:"Pair your machine",description:"A link that pairs the person's own machine with the app, as its first user. They open it and approve it in the Soba app.",credentials:["setup","account"],inputSchema:{type:"object",properties:{app:D.app},additionalProperties:!1},run:async(e,t)=>{let n=e.kind==="setup"?"/v1/manage/pairing":`/v1/apps/${encodeURIComponent(F(t,"app"))}/pairing`,{url:r}=await e.post(n,{});return`Give the person this link, to open and approve themselves: ${r}`}},a("soba_revoke_key","Revoke a key","DELETE","/apps/:app/keys/:key","Anything using it stops at once. Only when a person asked for it.",{key:i("From soba_list_keys.")}),a("soba_list_providers","List providers","GET","/apps/:app/providers","The AI accounts the app pays for, with their models. Keys are never shown."),a("soba_list_provider_services","List known services","GET","/apps/:app/providers/services","OpenAI, Anthropic, Groq and the rest: what soba_add_provider takes as `service`."),a("soba_add_provider","Add a provider","POST","/apps/:app/providers","Adds an AI account the app pays for, used when a user's own AI can't serve a run. This spends the app's money, so only when a person asked.",{service:i("From soba_list_provider_services."),...oe},[],ne),a("soba_update_provider","Change a provider","PATCH","/apps/:app/providers/:provider","Changes what you send. A different host in base_url needs api_key_env with it.",{provider:y,enabled:p(),...oe},[],ne),a("soba_remove_provider","Remove a provider","DELETE","/apps/:app/providers/:provider","Removes it, its key and its models. Only when a person asked for it.",{provider:y}),a("soba_clear_provider_key","Forget a provider's key","DELETE","/apps/:app/providers/:provider/key","Forgets the stored key and keeps the provider. Only when a person asked for it.",{provider:y}),a("soba_order_providers","Order providers","PUT","/apps/:app/providers/order","The order they are tried in, first tried first.",{providers:{type:"array",items:{type:"string"}}},["providers"]),a("soba_list_available_models","What a provider offers","GET","/apps/:app/providers/:provider/available","Asks the provider which models it serves.",{provider:y}),a("soba_set_provider_model","Add or change a model","PUT","/apps/:app/providers/:provider/models","Adds a model to a provider, or changes how users see it. Prices are looked up unless sent.",{provider:y,model:i("The provider's own id for it."),input_per_mtok:{type:"number"},output_per_mtok:{type:"number"},alias:c("string"),label:c("string","The name users see. Needs an alias."),note:c("string"),shown:p("In the model picker."),is_default:p(),tier:{type:["string","null"],enum:["fast","best",null]}},["model"]),a("soba_remove_provider_model","Remove a model","DELETE","/apps/:app/providers/:provider/models","Takes one model off a provider.",{provider:y,model:i()},["model"]),a("soba_list_custom_models","List custom models","GET","/apps/:app/custom_models","The app's own names over models from its providers."),a("soba_set_custom_model","Make or change a custom model","PUT","/apps/:app/custom_models/:alias","One name users pick over one or more models. With a percent on every model (coming to 100) runs are split; without, they are tried in order.",{alias:i("Lowercase and dashes. Fixed once made."),label:i("The name users see."),note:c("string"),icon:c("string"),is_default:p("What a user who picked nothing starts on."),models:{type:"array",items:{type:"object",properties:{provider:i(),model:i(),percent:c("number")},required:["provider","model"]}}}),a("soba_remove_custom_model","Remove a custom model","DELETE","/apps/:app/custom_models/:alias","Takes the name away. Its models stay.",{alias:i()}),a("soba_list_rewards","List rewards","GET","/apps/:app/rewards","Discounts, grants and free plans, with their codes.",{environment:d}),a("soba_create_reward","Create a reward","POST","/apps/:app/rewards","Only with amounts a person gave you.",{environment:d,...se},["environment","name","kind"]),a("soba_update_reward","Change a reward","PATCH","/apps/:app/rewards/:reward","Changes what you send. Only with amounts a person gave you.",{reward:i("Its id or slug."),environment:d,...se}),a("soba_archive_reward","Archive a reward","DELETE","/apps/:app/rewards/:reward","Its codes stop working; who holds it keeps it. Only when a person asked.",{reward:i(),environment:d}),a("soba_give_user_reward","Give a user a reward","POST","/apps/:app/rewards/:reward/give","Once per user per reward. Only when a person asked for that user to get it.",{reward:i(),user:i("Your id for them, or Soba's."),environment:d},["user"]),a("soba_sync_stripe","Put plans in Stripe","POST","/apps/:app/stripe/sync","Puts the app's paid plans into the workspace's connected Stripe now."),a("soba_list_users","List users","GET","/apps/:app/users","The app's users.",{environment:d,...N}),a("soba_get_user","Read a user","GET","/apps/:app/users/:user","Their plan, usage, machines and latest runs.",{user:i("Your id for them, or Soba's."),environment:d}),a("soba_set_user_plan","Put a user on a plan","PATCH","/apps/:app/users/:user","A paid plan given here is a gift: nothing is billed. Null takes their plan away, which leaves them with no limit. Only when a person asked for that user.",{user:i(),plan:c("string","A plan id, or null."),environment:d},["plan"]),a("soba_list_machines","List machines","GET","/apps/:app/machines","Users' machines.",{environment:d,...N}),a("soba_get_machine","Read a machine","GET","/apps/:app/machines/:machine","One machine and the AI on it.",{machine:i()}),a("soba_list_runs","List runs","GET","/apps/:app/runs","Runs with totals, speed and cost. Never what was said in them.",{environment:d,range:i("1d, 7d, 30d, 90d or all."),status:i(),class:i("A cost class."),model:i(),error:i(),...N}),a("soba_get_run","Read a run","GET","/apps/:app/runs/:run","One run.",{run:i()}),a("soba_get_activations","Read activations","GET","/apps/:app/activations","Users activated this period."),a("soba_get_overview","Read the overview","GET","/apps/:app/overview","Users, runs, what was spent and what was saved.",{environment:d}),a("soba_list_members","List members","GET","/workspaces/:workspace/members","Who is in the workspace, and open invites."),a("soba_invite_member","Invite somebody","POST","/workspaces/:workspace/invites","Emails an invitation. Only when a person named who to invite.",{email:i(),role:ie},["email"]),a("soba_revoke_invite","Revoke an invite","DELETE","/workspaces/:workspace/invites/:invite","Its link stops working.",{invite:i()}),a("soba_set_member_role","Change a member's role","PATCH","/workspaces/:workspace/members/:member","Only when a person asked. Owners are changed in the dashboard.",{member:i("Their id or email."),role:ie},["role"]),a("soba_remove_member","Remove a member","DELETE","/workspaces/:workspace/members/:member","Ends their access. Only when a person asked.",{member:i("Their id or email.")})];var P={type:"object",properties:{},additionalProperties:!1},Re=["user-subscription","user-hardware","user-api-key","open-weights","frontier"],k={app:{type:"string",description:"The app's id, from soba_list_apps. Not needed with a setup key."},environment:{type:"string",enum:["development","production"],description:"Which catalogue. Required to create with an account credential; a setup key is development only."}},ce={type:"string",description:"The plan's id, from soba_list_plans."},pe={name:{type:"string"},description:{type:"string"},price:{type:"number",description:"Dollars a month. 0 is a free plan."},unit:{type:"string",enum:["run","task","token","cost","credit"],description:"What both allowances are counted in. `cost` counts hundredths of a cent (10,000 to the dollar); a token or cost overage price is per 1M tokens or per $1."},included_units:{type:["number","null"],description:"Runs a month on AI the app pays for (open-weights, frontier). Null is unlimited."},trial_days:{type:"number"},route_prefer:{type:"array",items:{type:"string",enum:["user-subscription","user-hardware","user-api-key","open-weights","frontier"]},description:"What a run may use, best first. This is also the ceiling: a class left out can never be billed to this app."},max_cost_per_run:{type:["number","null"],description:"Dollars one run may cost."},own_included_units:{type:["number","null"],description:"Runs a month on the user's own AI (their machine, subscription or key), counted apart from included_units. Null is unlimited."},own_unit:{type:["string","null"],enum:["run","task","token","cost","credit",null],description:"What own_included_units counts, when not unit: a hybrid plan gives 200 runs on the user's own AI and 2,000 credits on yours. Null means the same as unit."},connected_reward:{type:"string",enum:["none","included","credit"]},connected_included_units:{type:["number","null"]},connected_credit:{type:["number","null"]},route_allow:{type:"array",items:{type:"string",enum:Re},description:"Classes allowed but not ranked, on top of route_prefer."},overage_per_unit:{type:["number","null"],description:"Dollars past the allowance, on a cost or credit plan."},meter:{type:"boolean",description:"On a run, task or token plan: keep going past the allowance, at cost plus markup_percent."},byo_overage:{type:"string",enum:["stop","meter"],description:"When the own-AI allowance is spent: stop, or continue on AI the app pays for."},markup_percent:{type:"number"},markup_overrides:{type:"object",additionalProperties:{type:"number"},description:"Percent per model vendor, over markup_percent."},credits_per_dollar:{type:"number",description:"Credits $1 of AI cost uses."},credit_price:{type:["number","null"],description:"Dollars per 1,000 credits."},credit_packs:{type:["array","null"],items:{type:"object",properties:{credits:{type:"number"},price:{type:"number"}},required:["credits","price"],additionalProperties:!1}},credit_expiry:{type:"string",enum:["never","month_end"]},task_noun:{type:["string","null"],description:"What the app calls a run, plural."},contact_url:{type:["string","null"],description:'A "Talk to us" link (https:// or mailto:). The price becomes 0.'},features:{type:"array",description:"What the app itself enforces, shown on the pricing card.",items:{type:"object",properties:{id:{type:"string",description:"snake_case; the app's code reads it."},name:{type:"string"},type:{type:"string",enum:["boolean","number","text"]},value:{type:["boolean","number","string","null"],description:"Null is unlimited, on a number."},unit:{type:"string"},resets:{type:"string",enum:["month"]},price:{type:"object",description:"Per-unit pricing (seats). amountMicros is millionths of a dollar.",properties:{amountMicros:{type:"number"},included:{type:"number"}},required:["amountMicros","included"]}},required:["id","name","type","value"]}}},Me={is_default:{type:"boolean",description:"Where new users start. A free plan only."},is_popular:{type:"boolean",description:'Shown as "Most popular".'}};function v(e,t){let{app:n,environment:r,plan:o,...s}=t;if(e.kind==="account"&&(typeof n!="string"||!n))throw new Error("Say which app: pass its id as `app`. soba_list_apps lists them.");return{path:e.kind==="setup"?"/v1/manage/plans":`/v1/apps/${encodeURIComponent(n)}/plans`,fields:s,plan:()=>{if(typeof o!="string"||!o)throw new Error("Say which plan: pass its id as `plan`. soba_list_plans lists them.");return encodeURIComponent(o)}}}function de(e,t){if(t.environment)return{environment:t.environment};if(e.kind==="setup")return{};throw new Error("Say which environment: development or production.")}function he(e){let t=e.steps.map(r=>`${r.done?"[x]":"[ ]"} ${r.title} \u2014 ${r.state}`),n=e.complete?"Every step is done. Nothing here needs you again.":`Next: ${e.next}. Call soba_next_step for what to do.`;return`${t.join(`
588
51
  `)}
589
52
 
@@ -611,6 +74,6 @@ When you are done, call soba_status to confirm it registered.`:he(t)}},{name:"so
611
74
 
612
75
  SOBA_KEY=${n.key}
613
76
 
614
- This is the only time it exists. Put it in .env.local now.`}},{name:"soba_set_connect_url",title:"Point Connect back at the app",description:"Sets where someone who started pairing in their terminal gets sent to sign in. It must be the public https page that renders <ConnectCompute />. If no such page exists yet, do not guess one \u2014 build the page first.",inputSchema:{type:"object",properties:{url:{type:"string",description:"The https URL of the page. Loopback is allowed in development."}},required:["url"],additionalProperties:!1},run:async(e,t)=>(await e.patch("/v1/manage/app",{connect_return_url:t.url}),`Connect now returns to ${t.url}.`)},{name:"soba_set_model_picker",title:"Set the model picker",description:"Sets the <ModelPicker /> the app's users see, the same card as the dashboard's Model Picker. users_choose false means no picker: every message uses Automatic. menu is how providers are laid out. presets are the rows at the top. Send only what should change; the answer is the whole state after it. A prop in the app's code still wins over this.",inputSchema:{type:"object",properties:{users_choose:{type:"boolean",description:"Whether the app's users get a picker at all."},menu:{type:"string",enum:["submenus","two_panes","tabs"],description:"submenus: each provider opens beside the menu. two_panes: providers left, models right. tabs: a tab per provider."},presets:{type:"object",properties:{automatic:{type:"boolean"},fast:{type:"boolean"},best:{type:"boolean"}},additionalProperties:!1,description:"Which of Automatic, Fast and Best head the menu."},search:{type:"boolean",description:"A search field once the list is long enough to need one."},effort:{type:"boolean",description:"An Effort row (Auto, Low, Medium, High, Extra, Max) for models that take it. On by default."},effort_style:{type:"string",enum:["switch","list"],description:"Effort as a row of steps (switch) or rows with a tick (list). Default: list in two_panes and tabs, switch elsewhere."},suggested:{type:"boolean",description:"False hides the Suggested group (every preset off); true brings it back with all three when none is on."},labels:{type:"boolean",description:"False: the AIs and providers as their logos alone, the name on hover. On by default."}},additionalProperties:!1},run:async(e,t)=>{let r=(await e.patch("/v1/manage/app",{model_picker:t})).model_picker;if(!r.users_choose)return"No picker: every message uses Automatic.";let o=["automatic","fast","best"].filter(s=>r.presets[s]);return`Picker on, ${(r.menu??"submenus").replace("_"," ")}. Presets: ${o.length?o.join(", "):"none"}. Search ${r.search?"on":"off"}. Effort ${r.effort!==!1?"on":"off"}${r.effort_style?` (${r.effort_style})`:""}. Labels ${r.labels!==!1?"on":"off"}.`}},{name:"soba_use_soba",title:"Just use Soba for now",description:"Answers the Providers step: Soba supplies the runs no user's AI serves, and the step ticks. The default unless the person asked to use their own model account. Adding a provider later takes over without undoing this.",inputSchema:P,run:async e=>(await e.patch("/v1/manage/app",{compute_skipped:!0}),"Soba will supply those runs. Call soba_status to confirm the step ticked.")},{name:"soba_list_apps",title:"List apps",description:"Every app you can reach, by workspace, with the id the plan tools take.",credentials:["account"],inputSchema:P,run:async e=>{let{data:t}=await e.get("/v1/workspaces"),n=[];for(let r of t){let o=await e.get(`/v1/workspaces/${r.id}/apps`);n.push(`${r.name}:`,...o.data.map(s=>` ${s.name} \u2014 ${s.id}`))}return n.join(`
77
+ This is the only time it exists. Put it in .env.local now.`}},{name:"soba_set_connect_url",title:"Point Connect back at the app",description:"Sets where someone who started pairing in their terminal gets sent to sign in. It must be the public https page that renders <ConnectCompute />. If no such page exists yet, do not guess one \u2014 build the page first.",inputSchema:{type:"object",properties:{url:{type:"string",description:"The https URL of the page. Loopback is allowed in development."}},required:["url"],additionalProperties:!1},run:async(e,t)=>(await e.patch("/v1/manage/app",{connect_return_url:t.url}),`Connect now returns to ${t.url}.`)},{name:"soba_set_model_picker",title:"Set the model picker",description:"Sets the <ModelPicker /> the app's users see, the same card as the dashboard's Model Picker. users_choose false means no picker: every message uses Automatic. menu is how providers are laid out. presets are the rows at the top. Send only what should change; the answer is the whole state after it. A prop in the app's code still wins over this.",inputSchema:{type:"object",properties:{users_choose:{type:"boolean",description:"Whether the app's users get a picker at all."},menu:{type:"string",enum:["submenus","two_panes","tabs","single"],description:"submenus: each provider opens beside the menu. two_panes: providers left, models right. tabs: a tab per provider."},presets:{type:"object",properties:{automatic:{type:"boolean"},fast:{type:"boolean"},best:{type:"boolean"}},additionalProperties:!1,description:"Which of Automatic, Fast and Best head the menu."},search:{type:"boolean",description:"A search field once the list is long enough to need one."},effort:{type:"boolean",description:"An Effort row (Auto, Low, Medium, High, Extra, Max) for models that take it. On by default."},effort_style:{type:"string",enum:["switch","list"],description:"Effort as a row of steps (switch) or rows with a tick (list). Default: list in two_panes and tabs, switch elsewhere."},suggested:{type:"boolean",description:"False hides the Suggested group (every preset off); true brings it back with all three when none is on."},labels:{type:"boolean",description:"False: the AIs and providers as their logos alone, the name on hover. On by default."}},additionalProperties:!1},run:async(e,t)=>{let r=(await e.patch("/v1/manage/app",{model_picker:t})).model_picker;if(!r.users_choose)return"No picker: every message uses Automatic.";let o=["automatic","fast","best"].filter(s=>r.presets[s]);return`Picker on, ${(r.menu??"submenus").replace("_"," ")}. Presets: ${o.length?o.join(", "):"none"}. Search ${r.search?"on":"off"}. Effort ${r.effort!==!1?"on":"off"}${r.effort_style?` (${r.effort_style})`:""}. Labels ${r.labels!==!1?"on":"off"}.`}},{name:"soba_use_soba",title:"Just use Soba for now",description:"Answers the Providers step: Soba supplies the runs no user's AI serves, and the step ticks. The default unless the person asked to use their own model account. Adding a provider later takes over without undoing this.",inputSchema:P,run:async e=>(await e.patch("/v1/manage/app",{compute_skipped:!0}),"Soba will supply those runs. Call soba_status to confirm the step ticked.")},{name:"soba_list_apps",title:"List apps",description:"Every app you can reach, by workspace, with the id the plan tools take.",credentials:["account"],inputSchema:P,run:async e=>{let{data:t}=await e.get("/v1/workspaces"),n=[];for(let r of t){let o=await e.get(`/v1/workspaces/${r.id}/apps`);n.push(`${r.name}:`,...o.data.map(s=>` ${s.name} \u2014 ${s.id}`))}return n.join(`
615
78
  `)||"No workspaces."}},{name:"soba_list_plans",title:"List plans",description:"The app's live plans with every field, as JSON. Read this before changing one. A setup key sees its own environment, development.",credentials:["setup","account"],inputSchema:{type:"object",properties:{...k},additionalProperties:!1},run:async(e,t)=>{let{path:n}=v(e,t),r=e.kind==="account"&&t.environment,o=r?`?environment=${encodeURIComponent(String(r))}`:"",{data:s}=await e.get(`${n}${o}`);return s.length?JSON.stringify(s,null,2):"No plans yet."}},{name:"soba_create_free_plan",title:"Create the free plan",description:'Adds the free "Bring your own" plan: unlimited runs on the AI each user connects, at no cost to the app, and the plan new users start on. The default for an app with no plans. Refused if the app already has one.',credentials:["setup","account"],inputSchema:{type:"object",properties:{...k},additionalProperties:!1},run:async(e,t)=>{let{path:n}=v(e,t),r=await e.post(n,{...de(e,t),template:"byo"});return e.kind==="setup"?`Created the plan "${r.name}". Call soba_status to confirm the steps ticked.`:`Created the plan "${r.name}".`}},{name:"soba_create_plan",title:"Create a plan",description:"Creates a plan: the price, the allowance, what a run may fall back to, and what connecting a machine earns back. Only call this with numbers a person gave you. Do not invent a price. A production plan is on sale at once.",credentials:["setup","account"],inputSchema:{type:"object",properties:{...k,...pe},required:["name","price","route_prefer"],additionalProperties:!1},run:async(e,t)=>{let{path:n,fields:r}=v(e,t),o=await e.post(n,{...de(e,t),...r}),s=o.environment?` in ${o.environment}`:"";return`Created the plan "${o.name}"${s}${o.id?` (${o.id})`:""}.`}},{name:"soba_update_plan",title:"Change a plan",description:"Changes the fields you send on one plan and leaves the rest. Only with numbers a person gave you. Sending route_prefer also sets the ceiling to it. Sending features replaces the whole list.",credentials:["setup","account"],inputSchema:{type:"object",properties:{app:k.app,plan:ce,...pe,...Me},required:["plan"],additionalProperties:!1},run:async(e,t)=>{let{path:n,fields:r,plan:o}=v(e,t),s=await e.patch(`${n}/${o()}`,r);return`Updated. The plan is now:
616
- ${JSON.stringify(s,null,2)}`}},{name:"soba_archive_plan",title:"Archive a plan",description:"Takes a plan off sale. Users already on it keep it, and its history stays. Only when a person asked for this plan to go: there is no tool to bring it back.",credentials:["setup","account"],inputSchema:{type:"object",properties:{app:k.app,plan:ce},required:["plan"],additionalProperties:!1},run:async(e,t)=>{let{path:n,plan:r}=v(e,t);return await e.delete(`${n}/${r()}`),"Archived."}},{name:"soba_give_reward",title:"Give a user a reward",description:"Gives one user a reward the app already has \u2014 money off, extra AI usage, or a plan for some days. Once per user per reward. Only call this when a person asked for that user to get it.",inputSchema:{type:"object",properties:{reward:{type:"string",description:"The reward's ID, e.g. early_bird."},user:{type:"string",description:"The app's own id for the user."}},required:["reward","user"],additionalProperties:!1},run:async(e,t)=>(await e.post("/v1/manage/rewards/give",t),`Gave ${t.user} the reward ${t.reward}.`)}],me=e=>[...Ce,...le].filter(t=>(t.credentials??["setup"]).includes(e));var Le="https://soba.so",Ne="2025-06-18",Ue="0.0.9";function De(e){let t={token:process.env.SOBA_MANAGEMENT_KEY??null,baseUrl:process.env.SOBA_MANAGE_URL??Le},n=!1,r=!!process.env.SOBA_MANAGE_URL;for(let o=0;o<e.length;o++){let s=e[o];s==="--token"?t.token=e[++o]??null:s?.startsWith("--token=")?t.token=s.slice(8):s==="--account"?n=!0:s==="--url"?(t.baseUrl=e[++o]??t.baseUrl,r=!0):s?.startsWith("--url=")&&(t.baseUrl=s.slice(6),r=!0)}if(t.token||(t.token=process.env.SOBA_ACCESS_TOKEN||process.env.SOBA_WORKSPACE_KEY||null),!t.token&&n)try{let o=process.env.SOBA_CONFIG_DIR||fe.join(Oe.homedir(),".soba"),s=JSON.parse(Pe(fe.join(o,"cli.json"),"utf8")),u=new URL(s.url).origin;r&&new URL(t.baseUrl).origin!==u&&(m(`this terminal is signed in to ${u}, not ${t.baseUrl}.`),process.exit(2)),t.token=s.token??null,t.baseUrl=u}catch{m("this terminal is not signed in. Run `npx @soba-so/cli login` first."),process.exit(2)}return t.baseUrl=t.baseUrl.replace(/\/+$/,""),t}var q=De(process.argv.slice(2)),j=q.token;j||(m("no management key. Pass --token mk_soba_\u2026 or set SOBA_MANAGEMENT_KEY."),m("Mint one in your Soba dashboard, on the Set up page. Or pass --account to use"),m("this terminal's `soba login`, for plans in any app and environment."),process.exit(2));/^(mk|pat|wk)_soba_/.test(j)||(m("that is not a management key. It starts with mk_soba_ (or pat_/wk_soba_), and sk_soba_ is a"),m("different credential \u2014 your app's secret key. Do not paste that here."),process.exit(2));var _=new A(j,q.baseUrl),W=me(_.kind),$e=new Map(W.map(e=>[e.name,e])),ge=_.kind==="setup"?L:[];z(async(e,t)=>{switch(e){case"initialize":return{protocolVersion:Ne,capabilities:{tools:{},prompts:{}},serverInfo:{name:"soba",version:Ue},instructions:_.kind==="account"?"Soba, in any app you can reach: settings, models, plans, users. Call soba_list_apps for the app, and read what is there before changing it. Prices are a person's to decide, and a production plan is on sale at once: confirm it with them first.":"Soba's setup checklist. Call soba_status first, then soba_next_step, and do what it says with your own tools \u2014 the repo is yours to edit, not this server's. Call soba_status again afterwards to confirm the step registered rather than assuming it did."};case"notifications/initialized":case"notifications/cancelled":return{};case"ping":return{};case"prompts/list":return{prompts:ge.map(n=>({name:n.name,title:n.title,description:n.description}))};case"prompts/get":{let n=typeof t.name=="string"?t.name:"",r=_.kind==="setup"?V.get(n):void 0;if(!r)throw new Error(`no such prompt: ${n}`);return{description:r.description,messages:[{role:"user",content:{type:"text",text:r.text}}]}}case"tools/list":return{tools:W.map(n=>({name:n.name,title:n.title,description:n.description,inputSchema:n.inputSchema}))};case"tools/call":{let n=typeof t.name=="string"?t.name:"",r=$e.get(n);if(!r)return B(`no such tool: ${n}`);let o=t.arguments??{};try{return{content:[{type:"text",text:await r.run(_,o)}]}}catch(s){return s instanceof w?B(Fe(s)):B(s instanceof Error?s.message:String(s))}}default:throw new Error("method not found")}});function B(e){return{content:[{type:"text",text:e}],isError:!0}}function Fe(e){return e.status===401?_.kind==="account"?"Soba refused the credential. It expired or was revoked: run `npx @soba-so/cli login`.":"Soba refused the management key. It may have been revoked, or it may belong to a different app. Mint a new one on the Set up page.":e.message}m(`ready \u2014 ${W.length} tools, ${ge.length} prompt against ${q.baseUrl}`);
79
+ ${JSON.stringify(s,null,2)}`}},{name:"soba_archive_plan",title:"Archive a plan",description:"Takes a plan off sale. Users already on it keep it, and its history stays. Only when a person asked for this plan to go: there is no tool to bring it back.",credentials:["setup","account"],inputSchema:{type:"object",properties:{app:k.app,plan:ce},required:["plan"],additionalProperties:!1},run:async(e,t)=>{let{path:n,plan:r}=v(e,t);return await e.delete(`${n}/${r()}`),"Archived."}},{name:"soba_give_reward",title:"Give a user a reward",description:"Gives one user a reward the app already has \u2014 money off, extra AI usage, or a plan for some days. Once per user per reward. Only call this when a person asked for that user to get it.",inputSchema:{type:"object",properties:{reward:{type:"string",description:"The reward's ID, e.g. early_bird."},user:{type:"string",description:"The app's own id for the user."}},required:["reward","user"],additionalProperties:!1},run:async(e,t)=>(await e.post("/v1/manage/rewards/give",t),`Gave ${t.user} the reward ${t.reward}.`)}],me=e=>[...Ce,...le].filter(t=>(t.credentials??["setup"]).includes(e));var Le="https://soba.so",Ne="2025-06-18",Ue="0.0.11";function De(e){let t={token:process.env.SOBA_MANAGEMENT_KEY??null,baseUrl:process.env.SOBA_MANAGE_URL??Le},n=!1,r=!!process.env.SOBA_MANAGE_URL;for(let o=0;o<e.length;o++){let s=e[o];s==="--token"?t.token=e[++o]??null:s?.startsWith("--token=")?t.token=s.slice(8):s==="--account"?n=!0:s==="--url"?(t.baseUrl=e[++o]??t.baseUrl,r=!0):s?.startsWith("--url=")&&(t.baseUrl=s.slice(6),r=!0)}if(t.token||(t.token=process.env.SOBA_ACCESS_TOKEN||process.env.SOBA_WORKSPACE_KEY||null),!t.token&&n)try{let o=process.env.SOBA_CONFIG_DIR||fe.join(Oe.homedir(),".soba"),s=JSON.parse(Pe(fe.join(o,"cli.json"),"utf8")),u=new URL(s.url).origin;r&&new URL(t.baseUrl).origin!==u&&(m(`this terminal is signed in to ${u}, not ${t.baseUrl}.`),process.exit(2)),t.token=s.token??null,t.baseUrl=u}catch{m("this terminal is not signed in. Run `npx @soba-so/cli login` first."),process.exit(2)}return t.baseUrl=t.baseUrl.replace(/\/+$/,""),t}var q=De(process.argv.slice(2)),W=q.token;W||(m("no management key. Pass --token mk_soba_\u2026 or set SOBA_MANAGEMENT_KEY."),m("Mint one in your Soba dashboard, on the Set up page. Or pass --account to use"),m("this terminal's `soba login`, for plans in any app and environment."),process.exit(2));/^(mk|pat|wk)_soba_/.test(W)||(m("that is not a management key. It starts with mk_soba_ (or pat_/wk_soba_), and sk_soba_ is a"),m("different credential \u2014 your app's secret key. Do not paste that here."),process.exit(2));var _=new x(W,q.baseUrl),j=me(_.kind),$e=new Map(j.map(e=>[e.name,e])),ge=_.kind==="setup"?L:[];z(async(e,t)=>{switch(e){case"initialize":return{protocolVersion:Ne,capabilities:{tools:{},prompts:{}},serverInfo:{name:"soba",version:Ue},instructions:_.kind==="account"?"Soba, in any app you can reach: settings, models, plans, users. Call soba_list_apps for the app, and read what is there before changing it. Prices are a person's to decide, and a production plan is on sale at once: confirm it with them first.":"Soba's setup checklist. Call soba_status first, then soba_next_step, and do what it says with your own tools \u2014 the repo is yours to edit, not this server's. Call soba_status again afterwards to confirm the step registered rather than assuming it did."};case"notifications/initialized":case"notifications/cancelled":return{};case"ping":return{};case"prompts/list":return{prompts:ge.map(n=>({name:n.name,title:n.title,description:n.description}))};case"prompts/get":{let n=typeof t.name=="string"?t.name:"",r=_.kind==="setup"?V.get(n):void 0;if(!r)throw new Error(`no such prompt: ${n}`);return{description:r.description,messages:[{role:"user",content:{type:"text",text:r.text}}]}}case"tools/list":return{tools:j.map(n=>({name:n.name,title:n.title,description:n.description,inputSchema:n.inputSchema}))};case"tools/call":{let n=typeof t.name=="string"?t.name:"",r=$e.get(n);if(!r)return B(`no such tool: ${n}`);let o=t.arguments??{};try{return{content:[{type:"text",text:await r.run(_,o)}]}}catch(s){return s instanceof w?B(Fe(s)):B(s instanceof Error?s.message:String(s))}}default:throw new Error("method not found")}});function B(e){return{content:[{type:"text",text:e}],isError:!0}}function Fe(e){return e.status===401?_.kind==="account"?"Soba refused the credential. It expired or was revoked: run `npx @soba-so/cli login`.":"Soba refused the management key. It may have been revoked, or it may belong to a different app. Mint a new one on the Set up page.":e.message}m(`ready \u2014 ${j.length} tools, ${ge.length} prompt against ${q.baseUrl}`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@soba-so/mcp",
3
- "version": "0.0.9",
3
+ "version": "0.0.11",
4
4
  "description": "Sets Soba up from inside your coding agent: it reads the checklist, does the next step, and reads it back.",
5
5
  "license": "UNLICENSED",
6
6
  "homepage": "https://soba.so/docs/quickstart",