@somewhere-cloud/cli 0.38.154 → 0.38.155

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 (142) hide show
  1. package/CHANGELOG.md +7 -0
  2. package/dist/docs/adopt.md +39 -0
  3. package/dist/docs/analytics.md +161 -0
  4. package/dist/docs/api-reference.md +339 -0
  5. package/dist/docs/api-surface.md +2067 -0
  6. package/dist/docs/app-mcp.md +162 -0
  7. package/dist/docs/architecture-patterns.md +334 -0
  8. package/dist/docs/auth-client.md +531 -0
  9. package/dist/docs/billing.md +76 -0
  10. package/dist/docs/browser.md +639 -0
  11. package/dist/docs/calendar.md +298 -0
  12. package/dist/docs/changes.md +323 -0
  13. package/dist/docs/cli.md +407 -0
  14. package/dist/docs/common-mistakes.md +199 -0
  15. package/dist/docs/connect-agent.md +72 -0
  16. package/dist/docs/cors.md +114 -0
  17. package/dist/docs/cron.md +167 -0
  18. package/dist/docs/database-engine.md +167 -0
  19. package/dist/docs/declared-data.md +1656 -0
  20. package/dist/docs/declared-files.md +475 -0
  21. package/dist/docs/deploy-intelligence.md +188 -0
  22. package/dist/docs/deploy.md +733 -0
  23. package/dist/docs/design-system.md +273 -0
  24. package/dist/docs/dev-environments.md +496 -0
  25. package/dist/docs/domain-ownership.md +31 -0
  26. package/dist/docs/domains.md +370 -0
  27. package/dist/docs/feedback.md +88 -0
  28. package/dist/docs/file-tools.md +116 -0
  29. package/dist/docs/functions.md +489 -0
  30. package/dist/docs/getting-started.md +238 -0
  31. package/dist/docs/github.md +95 -0
  32. package/dist/docs/google-calendar.md +212 -0
  33. package/dist/docs/groups.md +836 -0
  34. package/dist/docs/guarantees.md +58 -0
  35. package/dist/docs/handled-for-you.md +224 -0
  36. package/dist/docs/inspect.md +171 -0
  37. package/dist/docs/limits.md +68 -0
  38. package/dist/docs/live-data.md +197 -0
  39. package/dist/docs/live.md +92 -0
  40. package/dist/docs/local-dev.md +30 -0
  41. package/dist/docs/migration-supabase.md +58 -0
  42. package/dist/docs/payments.md +1102 -0
  43. package/dist/docs/portability.md +194 -0
  44. package/dist/docs/postgres.md +301 -0
  45. package/dist/docs/pricing-comparison.md +42 -0
  46. package/dist/docs/pricing.md +39 -0
  47. package/dist/docs/project-groups.md +107 -0
  48. package/dist/docs/projects.md +380 -0
  49. package/dist/docs/recipe-ai-agent.md +112 -0
  50. package/dist/docs/recipe-ai-features.md +227 -0
  51. package/dist/docs/recipe-ai-receipts.md +783 -0
  52. package/dist/docs/recipe-background-jobs.md +369 -0
  53. package/dist/docs/recipe-booking.md +348 -0
  54. package/dist/docs/recipe-csv-import.md +390 -0
  55. package/dist/docs/recipe-ecommerce.md +127 -0
  56. package/dist/docs/recipe-email.md +282 -0
  57. package/dist/docs/recipe-escalation.md +133 -0
  58. package/dist/docs/recipe-file-uploads.md +159 -0
  59. package/dist/docs/recipe-import-app.md +110 -0
  60. package/dist/docs/recipe-login.md +457 -0
  61. package/dist/docs/recipe-multi-chat.md +198 -0
  62. package/dist/docs/recipe-paid-api.md +161 -0
  63. package/dist/docs/recipe-pdfs.md +205 -0
  64. package/dist/docs/recipe-push-notifications.md +107 -0
  65. package/dist/docs/recipe-seo.md +200 -0
  66. package/dist/docs/recipe-signed-in-app.md +330 -0
  67. package/dist/docs/render.md +99 -0
  68. package/dist/docs/rooms.md +554 -0
  69. package/dist/docs/sdk.md +287 -0
  70. package/dist/docs/sdks.md +24 -0
  71. package/dist/docs/search.md +199 -0
  72. package/dist/docs/security-model.md +168 -0
  73. package/dist/docs/setup.md +212 -0
  74. package/dist/docs/smoke.md +102 -0
  75. package/dist/docs/speed.md +298 -0
  76. package/dist/docs/sql-compatibility.md +96 -0
  77. package/dist/docs/sw.agent.md +248 -0
  78. package/dist/docs/sw.ai.md +1291 -0
  79. package/dist/docs/sw.auth.md +1811 -0
  80. package/dist/docs/sw.billing.md +171 -0
  81. package/dist/docs/sw.db.md +2128 -0
  82. package/dist/docs/sw.email.md +661 -0
  83. package/dist/docs/sw.endpoint.md +187 -0
  84. package/dist/docs/sw.env.md +303 -0
  85. package/dist/docs/sw.fetch.md +115 -0
  86. package/dist/docs/sw.fs.md +424 -0
  87. package/dist/docs/sw.groups.md +836 -0
  88. package/dist/docs/sw.image.md +69 -0
  89. package/dist/docs/sw.jobs.md +520 -0
  90. package/dist/docs/sw.logs.md +61 -0
  91. package/dist/docs/sw.mail.md +106 -0
  92. package/dist/docs/sw.notifications.md +78 -0
  93. package/dist/docs/sw.push.md +161 -0
  94. package/dist/docs/sw.rateLimit.md +67 -0
  95. package/dist/docs/sw.web.md +128 -0
  96. package/dist/docs/tasks.md +269 -0
  97. package/dist/docs/test.md +220 -0
  98. package/dist/docs/tool-reference-account.md +7 -0
  99. package/dist/docs/tool-reference-ai.md +121 -0
  100. package/dist/docs/tool-reference-analytics.md +37 -0
  101. package/dist/docs/tool-reference-api.md +19 -0
  102. package/dist/docs/tool-reference-artifacts.md +35 -0
  103. package/dist/docs/tool-reference-auth.md +163 -0
  104. package/dist/docs/tool-reference-browser.md +114 -0
  105. package/dist/docs/tool-reference-code.md +26 -0
  106. package/dist/docs/tool-reference-connect.md +21 -0
  107. package/dist/docs/tool-reference-cron.md +48 -0
  108. package/dist/docs/tool-reference-db.md +282 -0
  109. package/dist/docs/tool-reference-domains.md +107 -0
  110. package/dist/docs/tool-reference-email.md +55 -0
  111. package/dist/docs/tool-reference-env.md +19 -0
  112. package/dist/docs/tool-reference-feedback.md +56 -0
  113. package/dist/docs/tool-reference-fs.md +265 -0
  114. package/dist/docs/tool-reference-github.md +57 -0
  115. package/dist/docs/tool-reference-groups.md +85 -0
  116. package/dist/docs/tool-reference-help.md +29 -0
  117. package/dist/docs/tool-reference-jobs.md +39 -0
  118. package/dist/docs/tool-reference-live.md +48 -0
  119. package/dist/docs/tool-reference-logs.md +16 -0
  120. package/dist/docs/tool-reference-payments.md +44 -0
  121. package/dist/docs/tool-reference-project.md +706 -0
  122. package/dist/docs/tool-reference-push.md +78 -0
  123. package/dist/docs/tool-reference-rate-limit.md +18 -0
  124. package/dist/docs/tool-reference-search.md +68 -0
  125. package/dist/docs/tool-reference-security.md +42 -0
  126. package/dist/docs/tool-reference-smoke.md +17 -0
  127. package/dist/docs/tool-reference-stock-photos.md +20 -0
  128. package/dist/docs/tool-reference-tasks.md +73 -0
  129. package/dist/docs/tool-reference-telegram.md +32 -0
  130. package/dist/docs/tool-reference-usage.md +9 -0
  131. package/dist/docs/tool-reference-web.md +71 -0
  132. package/dist/docs/tool-reference-webhooks.md +9 -0
  133. package/dist/docs/troubleshooting.md +411 -0
  134. package/dist/docs/typed-functions.md +94 -0
  135. package/dist/docs/verify-before-deploy.md +67 -0
  136. package/dist/docs/vs-supabase.md +75 -0
  137. package/dist/docs/vs-vercel.md +103 -0
  138. package/dist/lib/bundle.js +303 -221
  139. package/dist/lib/bundle.js.map +3 -3
  140. package/dist/types/lib/test-session.d.ts +8 -0
  141. package/npm-shrinkwrap.json +2 -2
  142. package/package.json +3 -2
@@ -0,0 +1,282 @@
1
+ # Recipe — Email the signed-in user
2
+
3
+ A signed-in user asks for an email, your function sends it to their own
4
+ address once they have verified it, and the page shows what the platform
5
+ answered. No sender account or domain is needed to start. Then add your own
6
+ sender domain, receiving, bounces or many recipients when the app needs them.
7
+
8
+ ## 1. The function: verified recipient, one send per action
9
+
10
+ A password sign-up can name any address. This function sends custom content
11
+ only after the account's owner has verified that address: it checks that
12
+ `user.email_verified` is true, which a sign-in link or the verification
13
+ code sets (`sw.auth` → `email-verification`, `magic-links`).
14
+
15
+ ```ts
16
+ // api/email-me.ts — POST { title, body, request_id }
17
+ export default sw.endpoint({
18
+ auth: 'none', // the handler applies its own access check below
19
+ handler: async ({ request }, sw) => {
20
+ if (request.method !== 'POST') {
21
+ return new Response('Use POST.', { status: 405, headers: { Allow: 'POST' } });
22
+ }
23
+ const refuse = (error: string, status: number, code?: string) =>
24
+ Response.json({ outcome: 'request-refused', error, code }, { status });
25
+
26
+ const user = await sw.auth.fromRequest(request);
27
+ if (!user) return refuse('Sign in to email yourself.', 401);
28
+ if (user.email_verified !== true) return refuse('Verify your email address first.', 403);
29
+
30
+ const input: unknown = await request.json().catch(() => null);
31
+ const fields = typeof input === 'object' && input !== null ? input : {};
32
+ const title = 'title' in fields ? fields.title : undefined;
33
+ const body = 'body' in fields ? fields.body : undefined;
34
+ const requestId = 'request_id' in fields ? fields.request_id : undefined;
35
+ if (typeof title !== 'string' || !title.trim() || title.length > 120
36
+ || typeof body !== 'string' || body.length > 10000
37
+ || typeof requestId !== 'string' || !/^[\w-]{8,64}$/.test(requestId)) {
38
+ return refuse('Send a title, a body and a request_id.', 400);
39
+ }
40
+
41
+ // 10 per hour per user is this example's choice.
42
+ const allowance = await sw.rateLimit.check(`email-me:${user.id}`, 10, 3600);
43
+ if (!allowance.allowed) return refuse('Too many requests. Try again later.', 429);
44
+
45
+ try {
46
+ const sent = await sw.email.send({
47
+ to: user.email,
48
+ subject: `Your note: ${title.trim()}`,
49
+ text: body,
50
+ // Reuse this key when checking the outcome of the same action.
51
+ idempotency_key: `email-me:${user.id}:${requestId}`,
52
+ });
53
+ return Response.json({ id: sent.id, status: sent.status });
54
+ } catch (error) {
55
+ const code = error instanceof Error && 'code' in error ? String(error.code) : 'EMAIL_FAILED';
56
+ const status = error instanceof Error && 'status' in error ? Number(error.status) : 0;
57
+ // The email service refused this request (422 or 429). Anything else is unconfirmed.
58
+ if (status === 422 || status === 429) return refuse('The email service refused this request.', status, code);
59
+ return Response.json({ outcome: 'unconfirmed', error: 'Could not confirm the email.', code }, { status: 502 });
60
+ }
61
+ },
62
+ });
63
+ ```
64
+
65
+ The recipient is the session's own address, never one from the request body,
66
+ and the checks run before the send. Every refusal says only that this request
67
+ was refused; it says nothing about an earlier request with the same
68
+ `request_id`.
69
+
70
+ ## 2. Call it from the page
71
+
72
+ ```ts
73
+ // src/services/email-me.ts
74
+ import { auth } from './auth';
75
+
76
+ export type EmailResult =
77
+ | { kind: 'status'; status: string } // the platform's state for this message
78
+ | { kind: 'request-refused'; error: string } // this request was refused
79
+ | { kind: 'unconfirmed' }; // nothing settled the outcome
80
+
81
+ /** One request_id per user action. Check again with the same id, title and body. */
82
+ export async function emailMe(title: string, body: string, requestId: string): Promise<EmailResult> {
83
+ let response: Response;
84
+ try {
85
+ response = await auth.fetch('/api/email-me', {
86
+ method: 'POST',
87
+ headers: { 'content-type': 'application/json' },
88
+ body: JSON.stringify({ title, body, request_id: requestId }),
89
+ });
90
+ } catch {
91
+ return { kind: 'unconfirmed' }; // the request may have arrived
92
+ }
93
+ const result: unknown = await response.json().catch(() => null);
94
+ const fields = typeof result === 'object' && result !== null ? result : {};
95
+ if (response.ok && 'status' in fields && typeof fields.status === 'string') {
96
+ return { kind: 'status', status: fields.status };
97
+ }
98
+ if ('outcome' in fields && fields.outcome === 'request-refused') {
99
+ const error = 'error' in fields && typeof fields.error === 'string' ? fields.error : 'This request was refused.';
100
+ return { kind: 'request-refused', error };
101
+ }
102
+ return { kind: 'unconfirmed' };
103
+ }
104
+ ```
105
+
106
+ Create the id when the user acts, for example
107
+ `const requestId = crypto.randomUUID()`, and keep it with that action's title
108
+ and body. Reuse that id to check the same message; create a new id for a
109
+ new note.
110
+
111
+ - **`status`**: show it. `sent` means the provider accepted the message,
112
+ and `captured` that it is in the test inbox, not delivered. A repeat
113
+ shows the message's later state: `delivered`, `opened` or `clicked`
114
+ happened. `bounced` reports a delivery failure; `complained` reports
115
+ a spam complaint. `suppressed`, `preference_blocked` and `failed`
116
+ report that the send was blocked or failed. `pending`,
117
+ `claimed` or `delivery_unknown` mean the platform could not confirm it
118
+ yet.
119
+ - **`request-refused`**: show "This request was refused" and the error. It
120
+ covers this request only; a repeat keeps the same `request_id`.
121
+ - **`unconfirmed`**: show "We couldn't confirm the email" and offer **Check
122
+ again**, which calls `emailMe` with the same `requestId`, title and body.
123
+ Nothing is sent automatically. A check can stay unconfirmed; `sw.email` →
124
+ `result-and-errors` explains the states.
125
+
126
+ ## 3. Check it with the test inbox
127
+
128
+ ```bash
129
+ somewhere deploy
130
+ # Replace my-app with your app's subdomain.
131
+ somewhere email test-inbox ana@my-app.test.somewhere.site
132
+ ```
133
+
134
+ Sign in to your app with a sign-in link sent to
135
+ `ana@<project>.test.somewhere.site` (`sw.auth` → `magic-links`): run the
136
+ second command, open the link it prints, and the account's address is
137
+ verified. Then send yourself a note and run the command again: it prints the
138
+ captured message, and the page shows `captured`. An account that signed up
139
+ with a password and never verified gets 403 from the function. Test-inbox
140
+ messages are never delivered and don't count toward your email allowance.
141
+
142
+ ## 4. Going further
143
+
144
+ | Need | Section |
145
+ |---|---|
146
+ | Invite someone who isn't a user yet, into a team | `recipe-login` → `7-team-invites` |
147
+ | Mail to people who aren't your users, from your own address | **Your own sender domain** below |
148
+ | Receive mail and act on it | **Receive email** below |
149
+ | Know whether a message arrived; bounces and complaints | **Delivery status and bounces** below |
150
+ | One message to many users | **Send to a list** below |
151
+ | Every result state and error code | `sw.email` → `result-and-errors` |
152
+
153
+ Your plan's email allowance and send rate are in `pricing`.
154
+
155
+ ## Your own sender domain
156
+
157
+ The platform's sender reaches this project's users and its owner. To email
158
+ anyone else, or to send from your own address, pass `from` on a verified
159
+ sender domain of the project:
160
+
161
+ ```ts
162
+ // Fragment, inside a function, once the domain is verified.
163
+ await sw.email.send({ to: 'alice@example.com', from: 'hello@yourapp.com', subject: 'Welcome', text: 'Thanks for joining.' });
164
+ ```
165
+
166
+ - A domain bought through the platform is set up for sending automatically.
167
+ - For a domain registered elsewhere, [add and verify a sender domain](https://somewhere.cloud/docs/sw.email.txt#your-own-sender-domain).
168
+ Sender domains need a paid plan. On Free the call answers `UPGRADE_REQUIRED` (402).
169
+ - A send with that `from` returns `SENDER_DOMAIN_NOT_FOUND` if the
170
+ domain has not been added, or `SENDER_DOMAIN_NOT_VERIFIED` while verification
171
+ is pending. Once verified, sign-in emails use your domain too.
172
+
173
+ ## Receive email
174
+
175
+ Mail arrives at addresses on a custom domain of the project:
176
+
177
+ 1. Turn on inbound mail for a domain claimed on the project:
178
+ `domain_enable_email({ id })`, with the domain id from `domain_owned`. Its
179
+ `receiving_host` is the domain itself, or reply.<domain> when the domain
180
+ already has a mail provider (whose records stay unchanged).
181
+ 2. Register addresses on that `receiving_host` and read the mail they
182
+ receive through the mail API (`/v1/mail`).
183
+
184
+ Inbound addresses need a custom domain; the test inbox captures mail your
185
+ project sends and receives no outside mail.
186
+
187
+ ## A follow-up that sends once and stops on reply
188
+
189
+ A day-two nudge takes a schedule, a query on your own data, and two options on
190
+ `sw.mail.project.send`. It needs no workflow engine.
191
+
192
+ - **`once: '<step>'`** sends this step to this person at most once. A second
193
+ call for the same step and recipient returns the first result with
194
+ `duplicate: true` and sends nothing, so a schedule that runs twice is safe.
195
+ The first attempt counts whatever its outcome: a refused or waiting first
196
+ attempt is not retried for that person. `once` needs exactly one address in
197
+ `to`.
198
+ - **`unless_replied: true`** sends nothing to someone the project mailbox has
199
+ already received mail from. The answer is then `status: 'skipped'` with
200
+ `skipped: 'replied'`.
201
+
202
+ A reply already recorded stops the next nudge. A reply still in transit while
203
+ the nudge goes out cannot stop it.
204
+
205
+ ```ts
206
+ // api/jobs/day-two.ts: runs daily and nudges people who signed up the day before yesterday
207
+ export default sw.endpoint({
208
+ auth: 'none', // The platform invocation signature authorizes this route.
209
+ handler: async ({ request: req }, sw) => {
210
+ if (!(await sw.jobs.verifyInvocation(req))) return new Response('forbidden', { status: 403 });
211
+ const day = 24 * 60 * 60 * 1000;
212
+ const { data } = await sw.db.server.from('signups', {
213
+ where: { created_at: [{ gte: new Date(Date.now() - 3 * day).toISOString() }, { lt: new Date(Date.now() - 2 * day).toISOString() }] },
214
+ limit: 500,
215
+ });
216
+ let sent = 0;
217
+ for (const person of data) {
218
+ const r = await sw.mail.project.send({
219
+ from: 'hello@example.com', // an address of this project on a verified sending domain
220
+ to: String(person.email),
221
+ subject: 'Did it work for you?',
222
+ text: 'If anything got in the way, reply to this email and I will help.',
223
+ once: 'day-two',
224
+ unless_replied: true,
225
+ });
226
+ if (r.status !== 'skipped' && !r.duplicate) sent += 1;
227
+ }
228
+ return { sent };
229
+ },
230
+ });
231
+ ```
232
+
233
+ ```bash
234
+ somewhere deploy
235
+ somewhere cron create "0 16 * * *" /api/jobs/day-two --project <project> --name day-two
236
+ somewhere cron run day-two --project <project> --wait # run it once now
237
+ ```
238
+
239
+ The sending address must be on a domain the project has verified for
240
+ sending. Replies come back to the same address and are recorded in the
241
+ project mailbox, which is what `unless_replied` reads.
242
+
243
+ ## Delivery status and bounces
244
+
245
+ `status: 'sent'` means the provider accepted the message. What happened next
246
+ is on the message:
247
+
248
+ - `sw.email.status(id)` returns one message's timeline: delivered, opened,
249
+ clicked, bounced or complained.
250
+ - A permanent bounce pauses that address for 30 days, a temporary one for
251
+ 24 hours, and a spam complaint permanently. Sends to a paused address throw
252
+ `EMAIL_SUPPRESSED` before anything is sent.
253
+ - `sw.email.checkSuppression(address)` checks one address before you send;
254
+ `sw.email.bounces({ days })` returns the list to skip for a mailing.
255
+ - A project whose mail bounces or draws complaints too often is paused for
256
+ every send until the rate recovers: `sw.email` → `sending-reputation`.
257
+
258
+ ## Send to a list
259
+
260
+ There is no batch send call: each recipient is one `sw.email.send`. These
261
+ rules keep a mailing fast, repeat-safe and out of spam folders:
262
+
263
+ - **Start sends together in small groups, never one awaited send after
264
+ another.** Each send waits for the provider, so a loop of awaited sends
265
+ takes as many round trips as there are recipients.
266
+ - **One `idempotency_key` per recipient per mailing**, such as
267
+ `` `digest-${digestId}-${user.id}` ``, so a retried batch never emails
268
+ anyone twice.
269
+ - **Skip bounced and opted-out addresses first.** Remove
270
+ `sw.email.bounces()` addresses, and keep an opt-out column of your own that
271
+ a link in every mailing sets.
272
+ - **Escape every value you put into `html`.** A user's name is user input.
273
+ - **Stay under the send rate.** It's counted per account across its
274
+ projects; above it a send throws `RATE_LIMITED` (429). For a list longer
275
+ than one minute's worth, create one job per batch, each with a later
276
+ `run_at`, and send that batch in its handler
277
+ (`recipe-background-jobs` → `8-work-that-starts-later`).
278
+ - **Use your own sender domain for newsletters and announcements.** The
279
+ platform's sender is for transactional mail.
280
+
281
+ The send-rate number and a grouped-send example: `sw.email` →
282
+ `sending-to-many-recipients`.
@@ -0,0 +1,133 @@
1
+ # Recipe — Cheap model escalates to smart model when stuck
2
+
3
+ Run your chatbot on a cheap fast model (Haiku, GPT-4o-mini) for the
4
+ 90% of turns that are easy — navigation, simple lookups, short
5
+ answers. When a turn is actually hard (a real bug, architecture
6
+ advice, a code review), the cheap model hands the hard question, restated with the code, errors
7
+ and constraints it needs, to a smarter model in one call. The application receives the final
8
+ answer from the same agent run.
9
+
10
+ ## The pattern
11
+
12
+ Add one tool — `ask_expert` — to a `sw.agent.run` call. The cheap model
13
+ calls it with the question restated in full; the tool sends that to the
14
+ smart model in one `sw.ai.chat` call and returns the answer as the tool
15
+ result. The cheap model relays it. The run's conversation is stored for the
16
+ signed-in user automatically, so the next request continues it with the same
17
+ `conversation_id`.
18
+
19
+ ## Code
20
+
21
+ `SomewhereRuntimeContext` is supplied by the current generated runtime types.
22
+
23
+ ```ts
24
+ // api/chat.ts — POST { message, conversation_id? } → { reply, conversation_id }
25
+ export default async (req: Request, sw: SomewhereRuntimeContext): Promise<Response> => {
26
+ if (req.method !== 'POST') return new Response('Method not allowed', { status: 405 })
27
+ const user = await sw.auth.requireUser(req)
28
+ // Every message is a paid model call, so throttle each verified user before
29
+ // the run starts. Sample policy: 20 messages per hour.
30
+ const turns = await sw.rateLimit.check(`chat:${user.id}`, 20, 3600)
31
+ if (!turns.allowed) {
32
+ return Response.json({ error: 'rate_limited', retry_at: turns.reset }, { status: 429 })
33
+ }
34
+ let body: unknown
35
+ try { body = await req.json() } catch { return new Response('Invalid JSON', { status: 400 }) }
36
+ if (!body || typeof body !== 'object' || Array.isArray(body)
37
+ || !('message' in body) || typeof body.message !== 'string' || !body.message.trim()) {
38
+ return new Response('message required', { status: 400 })
39
+ }
40
+ const message = body.message
41
+ const conversation_id = 'conversation_id' in body && typeof body.conversation_id === 'string' && body.conversation_id
42
+ ? body.conversation_id
43
+ : crypto.randomUUID()
44
+
45
+ const askExpert = {
46
+ name: 'ask_expert',
47
+ description: 'Ask a more capable model. Use for real debugging help (stack traces, "why does this fail"), architecture advice, code review and genuine unknowns. Do NOT use for simple lookups, navigation or status questions.',
48
+ input_schema: {
49
+ type: 'object',
50
+ properties: {
51
+ question: { type: 'string', description: 'The question restated in full, with the code, errors and constraints the expert needs.' },
52
+ },
53
+ required: ['question'],
54
+ },
55
+ execute: async (input: { [key: string]: unknown }) => {
56
+ // Throttle escalations per user before calling the smart model. The
57
+ // count is approximate under concurrency, not a spend guarantee.
58
+ const quota = await sw.rateLimit.check(`escalate:${user.id}`, 3, 86400)
59
+ if (!quota.allowed) return 'Expert limit reached for this 24-hour window.'
60
+ const question = typeof input.question === 'string' && input.question.trim() ? input.question : message
61
+ const expert = await sw.ai.chat({
62
+ provider: 'anthropic',
63
+ model: 'claude-sonnet-4-6',
64
+ system: 'You are an expert assistant. Be precise and thorough.',
65
+ messages: [{ role: 'user', content: question }],
66
+ })
67
+ return expert.text
68
+ },
69
+ }
70
+
71
+ const r = await sw.agent.run({
72
+ provider: 'anthropic',
73
+ model: 'claude-haiku-4-5',
74
+ conversation_id,
75
+ system: 'You are a helpful assistant. When a user asks for real debugging help, architecture advice or a code review, call ask_expert with the full question. Otherwise answer directly.',
76
+ messages: [{ role: 'user', content: message }],
77
+ tools: [askExpert],
78
+ })
79
+ return Response.json({ reply: r.text, conversation_id })
80
+ }
81
+ ```
82
+
83
+ Two per-user limits run before paid calls: 20 messages an hour for the
84
+ cheap model, then 3 escalations a day for the smart one. Over the first, the
85
+ request answers 429 with `retry_at`. Both are sample values. `sw.rateLimit`
86
+ is a request throttle: concurrent requests can pass slightly more than the
87
+ limit, so it is not exact spend accounting. To bound what one run may spend,
88
+ set `maxSpendCents` on `sw.agent.run` (`docs({ topic: 'sw.agent' })`).
89
+
90
+ ## When the cheap model should escalate
91
+
92
+ Four typical escalation signals:
93
+
94
+ - **Debugging** — user pastes a stack trace, error, or asks "why
95
+ doesn't X work?". The cheap model is usually wrong on these; the
96
+ smart model spots the missing `await` / wrong destructure / off-by-
97
+ one.
98
+ - **Architecture / design advice** — "how should I structure my
99
+ database for…", "where should this logic live…". The cheap model
100
+ picks one option confidently; the smart model weighs trade-offs.
101
+ - **Code review** — user pastes 30+ lines of code asking for feedback.
102
+ - **Genuine unknown** — the user is asking about a domain the cheap
103
+ model hasn't been taught (your product, a niche library).
104
+
105
+ Typical non-escalation signals:
106
+ - Navigation ("where do I find X?").
107
+ - Project status ("am I healthy?", "what's my usage?").
108
+ - Simple how-to questions answered in your existing system prompt.
109
+
110
+ ## Cost math
111
+
112
+ See /v1/pricing for current per-model rates. Cheap and smart models
113
+ typically differ by an order of magnitude or more on per-turn cost.
114
+
115
+ If 10% of turns escalate, your blended cost is roughly 6× the
116
+ cheap-model-only rate — but your bot now gets the hard questions right.
117
+ Cheap-everywhere costs less per turn and gets half the hard answers wrong.
118
+
119
+ ## Tier gating
120
+
121
+ Don't expose the same cap to every user. Pick the limits passed to
122
+ `sw.rateLimit.check` from the plan you store for the user. These are
123
+ approximate throttles, not billing limits. A reasonable starting shape for
124
+ escalations:
125
+
126
+ - **Free** — 3 escalations / day.
127
+ - **Paid** — 20 / day.
128
+ - **Top tier** — unlimited.
129
+
130
+ When the cap is hit, the tool result reports that the daily expert quota was
131
+ reached. The application retains authority over how that state is presented.
132
+
133
+ Related topics: `sw.ai`, `recipe-ai-agent`, `recipe-multi-chat`.
@@ -0,0 +1,159 @@
1
+ # Recipe — File uploads: each user's own files
2
+
3
+ Users upload, list, open and delete their own files from the page. Declare a
4
+ file collection; the generated `somewhere:files` client sends each file
5
+ straight from the browser to storage, and the platform checks your rules on
6
+ every request. You write no upload endpoint.
7
+
8
+ ## 1. Declare the collection
9
+
10
+ ```ts
11
+ // db/schema.ts
12
+ import { files, owner, schema } from 'somewhere/db';
13
+
14
+ export default schema({}, {
15
+ files: {
16
+ uploads: files({
17
+ path: '/uploads',
18
+ scope: owner(),
19
+ client: { read: true, upload: true, delete: true },
20
+ limits: { maxSize: '20MB', types: ['image/*', 'application/pdf', 'text/plain'] },
21
+ }),
22
+ },
23
+ });
24
+ ```
25
+
26
+ `owner()` gives each signed-in user their own files. `'20MB'` and the type
27
+ list are this example's choices; the client checks them before sending and the
28
+ platform enforces them. Your plan's per-file ceiling is in `limits`. If the
29
+ schema already declares tables, keep them in the first argument.
30
+
31
+ ## 2. Upload, list and delete from the page
32
+
33
+ ```tsx
34
+ // src/ui/Uploads.tsx — the signed-in user's own files
35
+ import { useEffect, useState, type ChangeEvent } from 'react';
36
+ import { files, type FileMeta } from 'somewhere:files';
37
+
38
+ type Listing = { status: 'loading' } | { status: 'error'; message: string } | { status: 'ready'; items: FileMeta[]; more: boolean };
39
+
40
+ export function Uploads() {
41
+ const [listing, setListing] = useState<Listing>({ status: 'loading' });
42
+ const [actionError, setActionError] = useState<string | null>(null);
43
+ const [busy, setBusy] = useState(false);
44
+
45
+ async function refresh() {
46
+ // The first 50 files; has_more says whether there are more to page through.
47
+ const { data, error } = await files.uploads.list({ limit: 50 });
48
+ setListing(error ? { status: 'error', message: error.message } : { status: 'ready', items: data.items, more: data.has_more });
49
+ }
50
+
51
+ useEffect(() => { void refresh(); }, []);
52
+
53
+ async function onPick(event: ChangeEvent<HTMLInputElement>) {
54
+ const file = event.target.files?.[0];
55
+ event.target.value = '';
56
+ if (!file) return;
57
+ setBusy(true);
58
+ setActionError(null);
59
+ const { error } = await files.uploads.upload(file);
60
+ setBusy(false);
61
+ if (error) return setActionError(error.message);
62
+ await refresh();
63
+ }
64
+
65
+ async function remove(id: string) {
66
+ const { error } = await files.uploads.delete(id);
67
+ if (error) return setActionError(error.message);
68
+ await refresh();
69
+ }
70
+
71
+ return (
72
+ <section className="panel">
73
+ <label htmlFor="upload-file">Add a file</label>
74
+ <input id="upload-file" type="file" onChange={(event) => void onPick(event)} disabled={busy} />
75
+ {actionError ? <p className="error" role="alert">{actionError}</p> : null}
76
+ {listing.status === 'loading' ? <p role="status">Loading your files…</p> : null}
77
+ {listing.status === 'error' ? (
78
+ <p className="error" role="alert">
79
+ {listing.message} <button type="button" className="button button--quiet" onClick={() => void refresh()}>Try again</button>
80
+ </p>
81
+ ) : null}
82
+ {listing.status === 'ready' && listing.items.length === 0 ? <p id="uploads-empty">No files yet.</p> : null}
83
+ {listing.status === 'ready' && listing.items.length > 0 ? (
84
+ <ul>
85
+ {listing.items.map((item) => (
86
+ <li key={item.id}>
87
+ <a className="upload__name" href={files.uploads.url(item.id)}>{item.name}</a>
88
+ <button type="button" className="button button--quiet" onClick={() => void remove(item.id)}>Delete</button>
89
+ </li>
90
+ ))}
91
+ </ul>
92
+ ) : null}
93
+ {listing.status === 'ready' && listing.more ? <p className="hint">Showing your first 50 files.</p> : null}
94
+ </section>
95
+ );
96
+ }
97
+ ```
98
+
99
+ Render `<Uploads />` on a signed-in page, such as the starter's
100
+ `src/pages/HomePage.tsx`. "No files yet." appears only after the list has
101
+ loaded successfully; while it loads or after a failed list, the page says so
102
+ instead. The list shows the first 50 files (`has_more` tells you there are
103
+ more; pass its `next` as `cursor` to page). Every call resolves to
104
+ `{ data, error }` and none throws for a refusal: a type outside `limits`, a file that is too large, a
105
+ signed-out caller or a lost connection (`NETWORK_ERROR`) arrives in `error`
106
+ with a `code`, `status` and `message`. `url(id)` is checked against the session
107
+ on every request, so a link only opens for its owner. Large files are sent in
108
+ parts by the same `upload` call; pass `onProgress` to show progress.
109
+
110
+ ## 3. Check it with two users
111
+
112
+ ```bash
113
+ somewhere typecheck && somewhere deploy
114
+ somewhere verify --project <project> --flow uploads-flow.json
115
+ ```
116
+
117
+ ```json
118
+ {
119
+ "actors": { "alice": {}, "bob": {} },
120
+ "journey": [
121
+ { "as": "alice", "path": "/", "actions": [
122
+ { "fill": "#auth-email", "value": "alice@<project>.test.somewhere.site" },
123
+ { "fill": "#auth-password", "value": "alice-password-1" },
124
+ { "click": "[data-sw-auth='sign-up']" },
125
+ { "wait": "#upload-file" },
126
+ { "upload": "#upload-file", "file": "data:text/plain;base64,aGVsbG8=", "name": "alice.txt" },
127
+ { "expect": { "selector": ".upload__name", "text": "alice.txt" } }
128
+ ] },
129
+ { "as": "bob", "path": "/", "actions": [
130
+ { "fill": "#auth-email", "value": "bob@<project>.test.somewhere.site" },
131
+ { "fill": "#auth-password", "value": "bob-password-1" },
132
+ { "click": "[data-sw-auth='sign-up']" },
133
+ { "expect": { "selector": "#uploads-empty", "text": "No files yet." } }
134
+ ] }
135
+ ]
136
+ }
137
+ ```
138
+
139
+ Alice uploads a file and sees it; Bob signs up and sees none of hers. Bob's
140
+ check passes only on the loaded, empty list, never on the loading message.
141
+ `upload` puts a file into a file input from a local path, data URL or base64,
142
+ or from a stored project file with `fs_path` (up to 50 MB per call);
143
+ `somewhere verify --schema` lists every action. A journey needs a claimed
144
+ account and a CLI login for all your projects: `browser` →
145
+ `several-users-in-one-run`.
146
+
147
+ ## 4. Other file jobs
148
+
149
+ | Need | Use |
150
+ |---|---|
151
+ | Teams, shared files, public images, replace, share links | `declared-files` → `declare`, `share-links` |
152
+ | A file your function creates, such as an export | `sw.fs.server.write`, then `sw.fs.server.signedUrl(path, { expiresIn })` (`declared-files` → `files-outside-a-collection`) |
153
+ | A large upload to a path your function chooses | `sw.fs` → `swfsuploadurl-path-maxsize-contenttype-expiresin-` |
154
+ | Reading files in a function | `sw.fs` acts as the signed-in caller under the same rules (`declared-files` → `in-your-functions`) |
155
+
156
+ `sw.fs.server` has your project's authority over every file. Authorize the
157
+ caller in your function before using it. Developer tools such as
158
+ `sw.fs.dev.*` and the integrity check are for agents and scripts, not app code:
159
+ `sw.fs` → `swfsdev-project-wide-file-view-runcode-only`.