@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,369 @@
1
+ # Recipe — A background job with a status the user sees
2
+
3
+ A signed-in user starts work that shouldn't hold up their request, checks its
4
+ status from the page, and the result is stored for that user. This job counts
5
+ the user's notes and saves a summary. A retried start with the same
6
+ `operationId` and a repeated delivery each leave exactly one summary.
7
+
8
+ Jobs work on every plan with no queue server to run. The platform signs each
9
+ delivery and retries failed runs. The start request takes the user from the
10
+ session and stores it in the job's payload. The handler verifies the delivery,
11
+ then reads and writes with server authority, scoped by hand to that user.
12
+ Sections 6 to 9 add a live result on the page, many items at once, work that
13
+ starts later, and failures.
14
+
15
+ ## 1. db/schema.ts
16
+
17
+ ```ts
18
+ // db/schema.ts
19
+ import { id, integer, owner, schema, table, text, timestamp } from 'somewhere/db';
20
+
21
+ export default schema({
22
+ notes: table(
23
+ { id: id(), title: text(), body: text({ default: '' }), created_at: timestamp({ default: 'now' }) },
24
+ { scope: owner(), client: { read: ['id', 'title', 'body', 'created_at'], create: ['title', 'body'], update: ['title', 'body'], delete: true } },
25
+ ),
26
+ note_summaries: table(
27
+ { id: id(), summary_id: text({ unique: true }), note_count: integer(), created_at: timestamp({ default: 'now' }) },
28
+ { scope: owner(), client: { read: ['id', 'note_count', 'created_at'] } },
29
+ ),
30
+ });
31
+ ```
32
+
33
+ ## 2. Start the job and report it
34
+
35
+ ```ts
36
+ // api/summaries.ts — POST { operation_id } starts a summary; GET ?id=<job_id> reports it
37
+ export default sw.endpoint({
38
+ auth: 'none', // the handler applies its own access check below
39
+ handler: async ({ request }, sw) => {
40
+ const user = await sw.auth.fromRequest(request);
41
+ if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
42
+
43
+ if (request.method === 'GET') {
44
+ const id = new URL(request.url).searchParams.get('id');
45
+ if (!id) return Response.json({ error: 'Pass ?id=<job_id>.' }, { status: 400 });
46
+ let job: Awaited<ReturnType<typeof sw.jobs.status>>;
47
+ try {
48
+ job = await sw.jobs.status(id); // only the user who created the job can read it
49
+ } catch (error) {
50
+ if (error instanceof Error && 'status' in error && error.status === 404) {
51
+ return Response.json({ error: 'No such summary for this account.' }, { status: 404 });
52
+ }
53
+ throw error;
54
+ }
55
+ const recoveryError = job.recovery?.recovery_error ?? null;
56
+ const failure = { error: job.error ?? null, error_code: job.error_code ?? null };
57
+ const summaryId = (job.payload as { summary_id?: unknown } | null)?.summary_id;
58
+ if (job.status !== 'complete' || typeof summaryId !== 'string') {
59
+ return Response.json({ status: job.status, recovery_error: recoveryError, note_count: null, ...failure });
60
+ }
61
+ const { data } = await sw.db.from('note_summaries', { where: { summary_id: summaryId }, limit: 1 });
62
+ return Response.json({ status: job.status, recovery_error: recoveryError, note_count: data[0]?.note_count ?? null, ...failure });
63
+ }
64
+ if (request.method !== 'POST') return new Response('Use GET or POST.', { status: 405, headers: { Allow: 'GET, POST' } });
65
+
66
+ const input: unknown = await request.json().catch(() => null);
67
+ const operationId = typeof input === 'object' && input !== null && 'operation_id' in input ? input.operation_id : undefined;
68
+ if (typeof operationId !== 'string' || !/^[A-Za-z0-9_-]{8,64}$/.test(operationId)) {
69
+ return Response.json({ error: 'Send an operation_id of 8–64 letters, digits, _ or -.' }, { status: 400 });
70
+ }
71
+ // 10 per hour per user is this example's choice.
72
+ const allowance = await sw.rateLimit.check(`summaries:${user.id}`, 10, 3600);
73
+ if (!allowance.allowed) return Response.json({ error: 'Try again later.' }, { status: 429 });
74
+
75
+ // Same user + operation_id → same key and payload → the same job, never a second one.
76
+ // user_id comes from the verified session, never from the request body.
77
+ const job = await sw.jobs.create({
78
+ handler: '/api/jobs/summarize-notes',
79
+ idempotency_key: `summary:${user.id}:${operationId}`,
80
+ payload: { summary_id: `${user.id}:${operationId}`, user_id: user.id },
81
+ });
82
+ return Response.json({ job_id: job.job_id }, { status: 202 });
83
+ },
84
+ });
85
+ ```
86
+
87
+ ## 3. The handler
88
+
89
+ ```ts
90
+ // api/jobs/summarize-notes.ts — runs only when the platform delivers the job
91
+ export default async function summarizeNotes(request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
92
+ // First, before reading the payload or any data.
93
+ if (!(await sw.jobs.verifyInvocation(request))) return Response.json({ error: 'forbidden' }, { status: 403 });
94
+
95
+ const payload: unknown = await request.json().catch(() => null);
96
+ const fields = typeof payload === 'object' && payload !== null ? payload : {};
97
+ const summaryId = 'summary_id' in fields ? fields.summary_id : undefined;
98
+ const userId = 'user_id' in fields ? fields.user_id : undefined;
99
+ if (typeof summaryId !== 'string' || !summaryId || typeof userId !== 'string' || !userId) {
100
+ return Response.json({ error: 'Invalid payload.' }, { status: 400 });
101
+ }
102
+
103
+ // Server authority, scoped by hand to the user the start request put in the payload.
104
+ const { data: noteCount } = await sw.db.server.count('notes', { where: { user_id: userId } });
105
+ await sw.db.server.insert(
106
+ 'note_summaries',
107
+ { summary_id: summaryId, note_count: noteCount, user_id: userId },
108
+ { onConflict: 'ignore' },
109
+ );
110
+ return Response.json({ ok: true });
111
+ }
112
+ ```
113
+
114
+ `verifyInvocation` is true only for a platform-signed delivery of this job;
115
+ anything else gets 403 before it can touch data. The delivery carries the
116
+ payload your start request stored, and that payload carries the
117
+ creator's verified identity, so the handler names `user_id` on every read and
118
+ write. A browser can't reach this handler with its own payload: a direct call
119
+ fails verification. Plain `sw.db` calls here are refused with
120
+ `ROW_JOB_REQUIRED`, because a job acts as its user on managed data only
121
+ through a row binding (`sw.jobs` → `act-on-one-row-for-the-signed-in-user`),
122
+ and this job reads many rows. The platform can run a handler more than once;
123
+ the unique `summary_id` makes a repeat insert nothing.
124
+
125
+ ## 4. The page
126
+
127
+ Two small calls: one starts the summary, one reads its status.
128
+
129
+ ```ts
130
+ // src/services/summaries.ts
131
+ import { auth } from './auth';
132
+
133
+ export type SummaryState = {
134
+ status: string;
135
+ note_count: number | null;
136
+ recovery_error: string | null;
137
+ error: string | null;
138
+ error_code: string | null;
139
+ };
140
+
141
+ /** Start one summary, or reach it again with the same operationId. Returns its job id. */
142
+ export async function startSummary(operationId: string): Promise<string> {
143
+ const response = await auth.fetch('/api/summaries', {
144
+ method: 'POST',
145
+ headers: { 'content-type': 'application/json' },
146
+ body: JSON.stringify({ operation_id: operationId }),
147
+ });
148
+ const result: unknown = await response.json().catch(() => null);
149
+ const jobId = typeof result === 'object' && result !== null && 'job_id' in result ? result.job_id : undefined;
150
+ if (!response.ok || typeof jobId !== 'string') throw new Error(`Could not start the summary (${response.status}).`);
151
+ return jobId;
152
+ }
153
+
154
+ /** Read one summary's current state. */
155
+ export async function readSummary(jobId: string): Promise<SummaryState> {
156
+ const response = await auth.fetch(`/api/summaries?id=${encodeURIComponent(jobId)}`);
157
+ if (response.status === 404) throw new Error('No such summary for this account.');
158
+ const result = (await response.json().catch(() => null)) as Partial<SummaryState> | null;
159
+ if (!response.ok || typeof result?.status !== 'string') throw new Error(`Could not read the summary (${response.status}).`);
160
+ return {
161
+ status: result.status,
162
+ note_count: result.note_count ?? null,
163
+ recovery_error: result.recovery_error ?? null,
164
+ error: result.error ?? null,
165
+ error_code: result.error_code ?? null,
166
+ };
167
+ }
168
+ ```
169
+
170
+ ```tsx
171
+ // src/pages/SummaryPanel.tsx
172
+ import { useState } from 'react';
173
+ import { readSummary, startSummary, type SummaryState } from '../services/summaries';
174
+
175
+ const FINISHED = ['complete', 'failed', 'cancelled'];
176
+
177
+ export function SummaryPanel() {
178
+ const [operationId, setOperationId] = useState<string | null>(null);
179
+ const [jobId, setJobId] = useState<string | null>(null);
180
+ const [state, setState] = useState<SummaryState | null>(null);
181
+ const [error, setError] = useState<string | null>(null);
182
+ const [busy, setBusy] = useState(false);
183
+
184
+ async function run(work: () => Promise<void>) {
185
+ setBusy(true);
186
+ setError(null);
187
+ try { await work(); } catch (e) { setError(e instanceof Error ? e.message : String(e)); } finally { setBusy(false); }
188
+ }
189
+ // One click is one operation: retrying a failed start reuses its id.
190
+ const start = () => run(async () => {
191
+ const id = operationId ?? crypto.randomUUID();
192
+ setOperationId(id);
193
+ setJobId(await startSummary(id));
194
+ });
195
+ const check = () => run(async () => { if (jobId) setState(await readSummary(jobId)); });
196
+ const reset = () => { setOperationId(null); setJobId(null); setState(null); setError(null); };
197
+ const finished = state !== null && FINISHED.includes(state.status);
198
+
199
+ return (
200
+ <section className="panel">
201
+ <button className="button" onClick={start} disabled={busy || jobId !== null}>
202
+ {operationId && !jobId ? 'Retry start' : 'Start summary'}
203
+ </button>
204
+ <button className="button" onClick={check} disabled={busy || !jobId}>Check status</button>
205
+ {finished && <button className="button" onClick={reset} disabled={busy}>Start another</button>}
206
+ {state && <p>Status: {state.status}{state.status === 'complete' ? (state.note_count === null ? ' — result unavailable' : ` — ${state.note_count} notes`) : ''}</p>}
207
+ {state && (state.status === 'failed' || state.status === 'cancelled') && (
208
+ <p role="alert">{state.error ?? `The summary was ${state.status}.`}{state.error_code ? ` (${state.error_code})` : ''}</p>
209
+ )}
210
+ {state && !finished && <p className="muted">Not finished yet{state.recovery_error ? ` (${state.recovery_error})` : ''}. Check again later.</p>}
211
+ {error && <p role="alert">{error}</p>}
212
+ </section>
213
+ );
214
+ }
215
+ ```
216
+
217
+ The page starts nothing on its own: **Start summary** creates one
218
+ `operationId` per click and keeps it, so **Retry start** after a failed start
219
+ reaches the job that may already exist. Both buttons are disabled while a call
220
+ is in flight, and the job id survives a failed **Check status**. The page
221
+ treats only `complete`, `failed` and `cancelled` as finished. Any other
222
+ status, `indeterminate` included, means check again; read `sw.jobs` →
223
+ `recovery-status-what-a-job-handle-can-tell-you` before starting new work
224
+ for it.
225
+
226
+ ## 5. Check it
227
+
228
+ ```bash
229
+ somewhere typecheck && somewhere deploy
230
+ somewhere db rows note_summaries
231
+ ```
232
+
233
+ Click **Start summary**, then **Check status** until it shows `complete`
234
+ and the note count. The rows include one summary for that user and operation. A
235
+ second user's summary counts only their own notes. Checking the first user's
236
+ job id from that second account returns 404.
237
+
238
+ A job outlives the request that started it, but each run of the handler is one
239
+ function request under the same time limits (`limits`). Keep one run's work
240
+ small enough to finish and safe to repeat. A side effect nobody reads back is
241
+ a job you never check; work on a clock belongs in `cron`.
242
+
243
+ ## 6. Show progress automatically
244
+
245
+ The job's structured write lands in that user's `note_summaries`, so a live
246
+ view over their summaries refreshes automatically when it changes. No **Check
247
+ status** clicks and no polling loop. Declare the view in a function:
248
+
249
+ ```ts
250
+ // api/recent-summaries.ts — the signed-in user's latest summaries, as a live view
251
+ export default async function recentSummaries(request: Request, sw: SomewhereRuntimeContext): Promise<Response> {
252
+ const user = await sw.auth.fromRequest(request);
253
+ if (!user) return Response.json({ error: 'Sign in.' }, { status: 401 });
254
+ return Response.json(await sw.rooms.live('summaries.recent', sw.db.from('note_summaries', {
255
+ columns: ['id', 'note_count', 'created_at'],
256
+ order: [['created_at', 'desc'], ['id', 'desc']],
257
+ limit: 5,
258
+ })));
259
+ }
260
+ ```
261
+
262
+ The page loads through that function and re-loads whenever the view may have
263
+ changed:
264
+
265
+ ```js
266
+ import { watchLive } from '/__sw/rooms/client.js'
267
+
268
+ const stop = watchLive(
269
+ () => fetch('/api/recent-summaries', { credentials: 'include' }).then((r) => r.json()),
270
+ (rows) => renderSummaries(rows), // your render function: newest summary first
271
+ )
272
+ ```
273
+
274
+ `owner()` keeps each user's view to their own rows. The job status from
275
+ section 2 still answers what the view can't show: a job that failed or is
276
+ still running. Declaration rules and the refresh policy: `live`.
277
+
278
+ ## 7. Many items at once
279
+
280
+ Give each item its own job and its own key, derived from the user action and
281
+ the item, so a retried request reaches the same jobs. This is a sketch:
282
+ `/api/jobs/summarize-note` is your own one-note handler, not published here.
283
+ Write it like section 3's handler, reading the note named by the payload's
284
+ `note_id` and scoping its server reads and writes to the payload's
285
+ `user_id`:
286
+
287
+ ```ts
288
+ // Fragment, inside the signed-in POST handler of section 2: one job per selected note.
289
+ for (const noteId of noteIds) {
290
+ await sw.jobs.create({
291
+ handler: '/api/jobs/summarize-note',
292
+ idempotency_key: `summary:${user.id}:${operationId}:${noteId}`,
293
+ payload: { note_id: noteId, user_id: user.id },
294
+ });
295
+ }
296
+ ```
297
+
298
+ Each account can have at most 100 jobs queued, scheduled or running at
299
+ once, on every plan, and create 600 a minute. At the
300
+ limit, `sw.jobs.create` throws `JOB_QUOTA_EXCEEDED` or `RATE_LIMITED`
301
+ (429). For more items than that, create one job per batch of items instead.
302
+ This is also a sketch: `/api/jobs/summarize-batch` is your own handler, not
303
+ published here. Write it like section 3's handler, looping over the payload's
304
+ `note_ids` and scoping every server read and write to the payload's
305
+ `user_id`. A run is one function request under the usual time limits
306
+ (`limits`), so keep each batch small enough to finish in one run:
307
+
308
+ ```ts
309
+ // Fragment, inside the signed-in POST handler of section 2: one job per batch of notes.
310
+ const BATCH = 10; // size it so one run finishes within the function time limit
311
+ for (let i = 0; i < noteIds.length; i += BATCH) {
312
+ await sw.jobs.create({
313
+ handler: '/api/jobs/summarize-batch',
314
+ idempotency_key: `summary:${user.id}:${operationId}:batch-${i / BATCH}`,
315
+ payload: { note_ids: noteIds.slice(i, i + BATCH), user_id: user.id },
316
+ });
317
+ }
318
+ ```
319
+
320
+ Have the batch handler record each item's result in your table and skip items
321
+ already recorded, so a repeated run does not redo finished work. A live view
322
+ (section 6) shows progress.
323
+
324
+ ## 8. Work that starts later
325
+
326
+ A job starts as soon as it's created. To run something later, such as a
327
+ reminder two hours after sign-up, give it a `run_at`:
328
+
329
+ ```ts
330
+ // Fragment, inside a signed-in handler.
331
+ await sw.jobs.create({
332
+ handler: '/api/jobs/send-reminder',
333
+ payload: { reminder_id: reminderId },
334
+ idempotency_key: `reminder:${reminderId}`,
335
+ run_at: new Date(Date.now() + 2 * 60 * 60 * 1000).toISOString(),
336
+ });
337
+ ```
338
+
339
+ `run_at` is an ISO-8601 time with an explicit offset and can be any future
340
+ time; a past time gets `RUN_AT_NOT_IN_FUTURE`. The job reports `scheduled`
341
+ until then and holds one of the account's job slots while it waits
342
+ (`sw.jobs` → `start-once-at-a-future-time`). The handler verifies with
343
+ `sw.jobs.verifyInvocation(request)` (`sw.jobs` → `job-handler-function`).
344
+
345
+ ## 9. When a job fails
346
+
347
+ The platform retries a failed run on its own. A run that keeps failing ends
348
+ as `failed`, and `sw.jobs.status` carries `error` and `error_code`. To try
349
+ again, start a new job with a new `operationId`; reusing the old one reaches
350
+ the failed job. `indeterminate` is different: the job may still be
351
+ recovering, so read `recovery` before starting new work (`sw.jobs` →
352
+ `recovery-status-what-a-job-handle-can-tell-you`).
353
+
354
+ For a job started by a signed-in user, call `sw.jobs.cancel(jobId)` from a
355
+ handler that requires sign-in. The platform uses the request's verified user;
356
+ another user's job returns `JOB_NOT_FOUND`. The result reports
357
+ `status: 'cancelled'`. A job that is complete, failed, cancelled or
358
+ indeterminate returns `JOB_ALREADY_COMPLETE`.
359
+
360
+ `job_cancel({ job_id })` is the developer-tool path for project-owned work,
361
+ such as a scheduled run. It keeps refusing user-owned jobs. Without a
362
+ signed-in user, `sw.jobs.cancel` also acts on project-owned work: only
363
+ expose that call behind your own authorization check. Cancelling queued work
364
+ prevents it from starting. An ordinary handler already running finishes, and
365
+ its side effects remain; keep those effects idempotent. An agent run stops
366
+ at its next step boundary.
367
+
368
+ To test a forced redelivery in a test project, see
369
+ `somewhere docs sw.jobs --section job-handler-function`.