@zabaca/zbc 0.6.2 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zabaca/zbc",
3
- "version": "0.6.2",
3
+ "version": "0.7.0",
4
4
  "description": "Zabaca stack CLI — scaffold and deploy infrastructure",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -42,7 +42,7 @@ async function resolveBundledDir(name: string): Promise<string> {
42
42
  if (await Bun.file(registry).exists()) return dir
43
43
  }
44
44
  throw new Error(
45
- `"${name}" not found in built-in registry. Available: cloudflare, cloudflare-email, turso, inbox.`,
45
+ `"${name}" not found in built-in registry. Available: cloudflare, cloudflare-email, r2, turso, inbox.`,
46
46
  )
47
47
  }
48
48
 
@@ -159,8 +159,10 @@ async function installApp(
159
159
  }
160
160
  }
161
161
 
162
- // 2. Copy the package, substituting {{PROJECT_NAME}} (worker/bucket names,
163
- // package name). registry.json stays in the CLI — it's not app code.
162
+ // 2. Copy the package verbatim — app templates are placeholder-free (all
163
+ // per-project identity lives in the instance file: workerName,
164
+ // r2Bindings, workerVars). registry.json stays in the CLI — it's not app
165
+ // code. `vars` kept for future templates; a no-op with no {{}} tokens.
164
166
  const { project } = await loadConfig(projectRoot)
165
167
  await copyTemplateDir(sourceDir, destDir, {
166
168
  vars: { PROJECT_NAME: project },
@@ -181,7 +183,7 @@ export const addCommand = defineCommand({
181
183
  args: {
182
184
  module: {
183
185
  type: 'positional',
184
- description: 'Module or app name (e.g. turso, cloudflare, cloudflare-email, inbox)',
186
+ description: 'Module or app name (e.g. turso, cloudflare, cloudflare-email, r2, inbox)',
185
187
  required: true,
186
188
  },
187
189
  },
@@ -13,7 +13,7 @@ This project uses [zbc](https://github.com/Zabaca/zbc) for infrastructure scaffo
13
13
  ## Common commands
14
14
 
15
15
  - `bun install` — install dependencies
16
- - `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`) or scaffold an app template (`inbox` — an agent-accessible email inbox; auto-vendors its module dependencies)
16
+ - `bunx @zabaca/zbc add <module>` — vendor an infra module (`turso`, `cloudflare`, `cloudflare-email`, `r2`) or scaffold an app template (`inbox` — an agent-accessible email inbox; auto-vendors its module dependencies)
17
17
  - `bunx @zabaca/zbc apply <env>` — apply infrastructure for an environment
18
18
  - `bunx @zabaca/zbc destroy <env>` — tear down an ephemeral environment
19
19
 
@@ -1,5 +1,5 @@
1
1
  {
2
- "name": "@{{PROJECT_NAME}}/inbox",
2
+ "name": "@zbc/inbox",
3
3
  "version": "0.0.1",
4
4
  "private": true,
5
5
  "type": "module",
@@ -9,7 +9,11 @@
9
9
  "typecheck": "tsc --noEmit"
10
10
  },
11
11
  "dependencies": {
12
- "postal-mime": "^2.4.4"
12
+ "@hono/mcp": "^0.3.1",
13
+ "@modelcontextprotocol/sdk": "^1.29.0",
14
+ "hono": "^4.12.30",
15
+ "postal-mime": "^2.4.4",
16
+ "zod": "^4.4.3"
13
17
  },
14
18
  "devDependencies": {
15
19
  "@cloudflare/workers-types": "^4.20250101.0",
@@ -3,7 +3,7 @@
3
3
  <head>
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
- <title>{{PROJECT_NAME}} inbox</title>
6
+ <title>Inbox</title>
7
7
  <style>
8
8
  /* Prose design system tokens (mirrored from packages/design-system/src/tokens.css;
9
9
  the inbox UI is a self-contained static page, so no Tailwind pipeline). */
@@ -156,7 +156,7 @@
156
156
  </head>
157
157
  <body>
158
158
  <header>
159
- <h1>{{PROJECT_NAME}} inbox</h1>
159
+ <h1>Inbox</h1>
160
160
  <span class="domain"></span>
161
161
  <span class="spacer"></span>
162
162
  <div class="actions">
@@ -174,7 +174,7 @@
174
174
  <h3 id="compose-title">New message</h3>
175
175
  <form class="compose" id="compose-form" method="dialog">
176
176
  <input name="to" placeholder="To" required>
177
- <input name="from" placeholder="From (default inbox)">
177
+ <input name="from" placeholder="From (optional, defaults to DEFAULT_FROM)">
178
178
  <input name="subject" placeholder="Subject" required>
179
179
  <input name="inReplyTo" type="hidden">
180
180
  <textarea name="text" placeholder="Message" required></textarea>
@@ -1,9 +1,9 @@
1
1
  {
2
2
  "name": "inbox",
3
3
  "kind": "app",
4
- "description": "Agent-accessible email inbox: a Cloudflare Worker that receives routed mail (SQLite DO metadata + R2 raw MIME), sends via Email Sending, and exposes a bearer-authed JSON API plus a minimal web UI",
4
+ "description": "Agent-accessible email inbox: a Cloudflare Worker that receives routed mail (SQLite DO metadata + R2 raw MIME), sends via Email Sending, and exposes a bearer-authed JSON API, an MCP server at /mcp (same token), and a minimal web UI",
5
5
  "targetDir": "packages/inbox",
6
- "modules": ["cloudflare-email"],
6
+ "modules": ["cloudflare", "cloudflare-email", "r2"],
7
7
  "secrets": ["INBOX_TOKEN", "CLOUDFLARE_API_TOKEN"],
8
- "instructions": "1) Edit packages/inbox/wrangler.jsonc: set DEFAULT_FROM to an address on your email domain (e.g. inbox@mail.example.com).\n2) Create two instance files in packages/infra/environments/<env>/:\n\n // inbox.ts\n import { cloudflareModule } from '../../modules/cloudflare'\n export default cloudflareModule.instance({\n name: 'inbox',\n config: { workdir: 'packages/inbox', accountId: '<account id>', workerSecrets: ['INBOX_TOKEN'] },\n })\n\n // email.ts\n import { cloudflareEmailModule } from '../../modules/cloudflare-email'\n import inbox from './inbox'\n export default cloudflareEmailModule.instance({\n name: 'email',\n imports: [inbox],\n config: {\n accountId: '<account id>', zoneId: '<zone id>', domain: 'mail.<your-domain>',\n enableSending: true, enableRouting: true,\n catchAll: { action: 'worker', workerName: { from: 'inbox', output: 'workerName' } },\n },\n })\n\n3) Add INBOX_TOKEN (any long random string, e.g. `openssl rand -hex 32`) to secrets.yaml, and make sure CLOUDFLARE_API_TOKEN has the scopes the cloudflare-email module documents.\n4) `zbc apply <env>`. Create the R2 bucket if wrangler asks for it (`wrangler r2 bucket create <project>-inbox-raw`).\nNote: Cloudflare holds newly onboarded sending domains in a preview sandbox (verified recipients only) for a short period after DNS validates; arbitrary-recipient sending starts working once it drops."
8
+ "instructions": "The scaffolded package is generic — all per-project identity (worker name, R2 bucket, default From address) lives in the instance files, not in wrangler.jsonc.\n\nCreate three instance files in packages/infra/environments/<env>/:\n\n // inbox-raw.ts — the R2 bucket for raw MIME\n import { r2Module } from '../../modules/r2'\n export default r2Module.instance({\n name: 'inbox-raw',\n config: { accountId: '<account id>', bucketName: '<project>-inbox-raw' },\n })\n\n // inbox.ts — the worker\n import { cloudflareModule } from '../../modules/cloudflare'\n import inboxRaw from './inbox-raw'\n export default cloudflareModule.instance({\n name: 'inbox',\n imports: [inboxRaw],\n config: {\n workdir: 'packages/inbox',\n accountId: '<account id>',\n workerName: '<project>-inbox',\n workerSecrets: ['INBOX_TOKEN'],\n workerVars: [{ name: 'DEFAULT_FROM', value: 'inbox@mail.<your-domain>' }],\n r2Bindings: [{ binding: 'RAW', from: 'inbox-raw', output: 'bucketName' }],\n },\n })\n\n // email.ts — sending + routing for the domain\n import { cloudflareEmailModule } from '../../modules/cloudflare-email'\n import inbox from './inbox'\n export default cloudflareEmailModule.instance({\n name: 'email',\n imports: [inbox],\n config: {\n accountId: '<account id>', zoneId: '<zone id>', domain: 'mail.<your-domain>',\n enableSending: true, enableRouting: true,\n catchAll: { action: 'worker', workerName: { from: 'inbox', output: 'workerName' } },\n },\n })\n\nAdd INBOX_TOKEN (any long random string, e.g. `openssl rand -hex 32`) to secrets.yaml. CLOUDFLARE_API_TOKEN needs the scopes the cloudflare-email module documents PLUS Account → Workers R2 Storage: Edit (for the r2 module).\n\n`zbc apply <env>` provisions the bucket, deploys the worker, and onboards the domain.\nNote: Cloudflare holds newly onboarded sending domains in a preview sandbox (verified recipients only) for a short period after DNS validates; arbitrary-recipient sending starts working once it drops."
9
9
  }
@@ -1,4 +1,5 @@
1
1
  import { DurableObject } from 'cloudflare:workers'
2
+ import { type MailEnv, emitWebhook, sendMail } from './shared'
2
3
 
3
4
  /**
4
5
  * Inbox — a single SQLite-backed Durable Object holding message metadata and
@@ -20,6 +21,21 @@ export interface MessageMeta {
20
21
  created_at: string
21
22
  direction: 'inbound' | 'outbound'
22
23
  thread_id: string
24
+ /**
25
+ * 'sent' for everything visible in the inbox (inbound rows included);
26
+ * 'draft' = unsent draft, 'scheduled' = queued for the alarm,
27
+ * 'failed' = a scheduled send the alarm could not dispatch (see send_error
28
+ * in the scheduled listing).
29
+ */
30
+ status: 'draft' | 'scheduled' | 'sent' | 'failed'
31
+ /** Classifier label ('' until/unless labeling runs). */
32
+ label: string
33
+ }
34
+
35
+ /** A scheduled/failed row as returned by listScheduled. */
36
+ export interface ScheduledMeta extends MessageMeta {
37
+ scheduled_at: string
38
+ send_error: string
23
39
  }
24
40
 
25
41
  export interface ThreadMeta extends MessageMeta {
@@ -50,6 +66,13 @@ export interface InsertMessage {
50
66
  size: number
51
67
  direction: 'inbound' | 'outbound'
52
68
  in_reply_to: string
69
+ /**
70
+ * 'draft'/'scheduled' skip thread resolution (resolved at actual send
71
+ * time). Default 'sent'.
72
+ */
73
+ status?: 'draft' | 'scheduled' | 'sent'
74
+ /** Required when status is 'scheduled': ISO time the alarm should send at. */
75
+ scheduled_at?: string
53
76
  }
54
77
 
55
78
  /** Strip Re:/Fwd: prefixes + whitespace so replies fall into the same thread. */
@@ -61,11 +84,11 @@ function normalizeSubject(subject: string): string {
61
84
  .toLowerCase()
62
85
  }
63
86
 
64
- export class Inbox extends DurableObject {
87
+ export class Inbox extends DurableObject<MailEnv> {
65
88
  private sql: SqlStorage
66
89
 
67
- constructor(ctx: DurableObjectState, env: unknown) {
68
- super(ctx, env as never)
90
+ constructor(ctx: DurableObjectState, env: MailEnv) {
91
+ super(ctx, env)
69
92
  this.sql = ctx.storage.sql
70
93
  this.sql.exec(`
71
94
  CREATE TABLE IF NOT EXISTS messages (
@@ -107,6 +130,16 @@ export class Inbox extends DurableObject {
107
130
  )
108
131
  this.sql.exec(`UPDATE messages SET thread_id = id WHERE thread_id = ''`)
109
132
  }
133
+ if (!names.has('status')) {
134
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN status TEXT NOT NULL DEFAULT 'sent'`)
135
+ }
136
+ if (!names.has('label')) {
137
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN label TEXT NOT NULL DEFAULT ''`)
138
+ }
139
+ if (!names.has('scheduled_at')) {
140
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN scheduled_at TEXT NOT NULL DEFAULT ''`)
141
+ this.sql.exec(`ALTER TABLE messages ADD COLUMN send_error TEXT NOT NULL DEFAULT ''`)
142
+ }
110
143
  this.sql.exec(`CREATE INDEX IF NOT EXISTS idx_messages_thread ON messages (thread_id, id)`)
111
144
  }
112
145
 
@@ -126,7 +159,10 @@ export class Inbox extends DurableObject {
126
159
  ): string {
127
160
  if (inReplyTo) {
128
161
  const byRef = this.sql
129
- .exec(`SELECT thread_id FROM messages WHERE message_id = ? LIMIT 1`, inReplyTo)
162
+ .exec(
163
+ `SELECT thread_id FROM messages WHERE message_id = ? AND status = 'sent' LIMIT 1`,
164
+ inReplyTo,
165
+ )
130
166
  .toArray()[0] as unknown as { thread_id: string } | undefined
131
167
  if (byRef?.thread_id) return byRef.thread_id
132
168
  }
@@ -135,7 +171,7 @@ export class Inbox extends DurableObject {
135
171
  const participants = [fromAddr, toAddr].map((a) => a.toLowerCase())
136
172
  const rows = this.sql
137
173
  .exec(
138
- `SELECT thread_id, subject, from_addr, to_addr FROM messages ORDER BY id DESC LIMIT 200`,
174
+ `SELECT thread_id, subject, from_addr, to_addr FROM messages WHERE status = 'sent' ORDER BY id DESC LIMIT 200`,
139
175
  )
140
176
  .toArray() as unknown as Array<{
141
177
  thread_id: string
@@ -154,19 +190,19 @@ export class Inbox extends DurableObject {
154
190
  }
155
191
 
156
192
  insert(msg: InsertMessage): { threadId: string } {
157
- const threadId = this.resolveThreadId(
158
- msg.id,
159
- msg.in_reply_to,
160
- msg.subject,
161
- msg.from_addr,
162
- msg.to_addr,
163
- )
193
+ const status = msg.status ?? 'sent'
194
+ // Drafts/scheduled get no thread until they're actually sent — resolving
195
+ // early could anchor a thread to a message that never goes out.
196
+ const threadId =
197
+ status === 'sent'
198
+ ? this.resolveThreadId(msg.id, msg.in_reply_to, msg.subject, msg.from_addr, msg.to_addr)
199
+ : ''
164
200
  this.sql.exec(
165
201
  `INSERT INTO messages
166
202
  (id, message_id, from_addr, to_addr, subject, date, snippet,
167
203
  text_body, html_body, r2_key, attachments_json, size, created_at,
168
- direction, in_reply_to, thread_id)
169
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
204
+ direction, in_reply_to, thread_id, status, scheduled_at)
205
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
170
206
  msg.id,
171
207
  msg.message_id,
172
208
  msg.from_addr,
@@ -183,29 +219,247 @@ export class Inbox extends DurableObject {
183
219
  msg.direction,
184
220
  msg.in_reply_to,
185
221
  threadId,
222
+ status,
223
+ msg.scheduled_at ?? '',
186
224
  )
225
+ if (status === 'scheduled') this.armAlarm()
187
226
  return { threadId }
188
227
  }
189
228
 
190
- /** Newest-first page. `cursor` is the last-seen id (ids are time-ordered). */
191
- list(limit = 50, cursor?: string): { messages: MessageMeta[]; nextCursor: string | null } {
229
+ /**
230
+ * (Re)arm the DO alarm for the earliest pending scheduled send. Safe to
231
+ * call any time — a DO has ONE alarm, so we always point it at MIN(
232
+ * scheduled_at); alarm() re-arms for the next one after each batch.
233
+ */
234
+ private armAlarm(): void {
235
+ const next = this.sql
236
+ .exec(`SELECT MIN(scheduled_at) AS next FROM messages WHERE status = 'scheduled'`)
237
+ .toArray()[0] as unknown as { next: string | null } | undefined
238
+ if (next?.next) {
239
+ void this.ctx.storage.setAlarm(new Date(next.next).getTime())
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Dispatch every due scheduled send. Handles past-due backlogs (missed
245
+ * alarms after redeploys/hibernation): everything with scheduled_at <= now
246
+ * goes out in this pass, then the alarm re-arms for the next future one.
247
+ * A failed dispatch marks the row 'failed' with send_error rather than
248
+ * blocking the rest of the batch.
249
+ */
250
+ async alarm(): Promise<void> {
251
+ const now = new Date().toISOString()
252
+ const due = this.sql
253
+ .exec(
254
+ `SELECT id, from_addr, to_addr, subject, text_body, html_body, in_reply_to, snippet
255
+ FROM messages WHERE status = 'scheduled' AND scheduled_at <= ? ORDER BY scheduled_at ASC`,
256
+ now,
257
+ )
258
+ .toArray() as unknown as Array<{
259
+ id: string
260
+ from_addr: string
261
+ to_addr: string
262
+ subject: string
263
+ text_body: string
264
+ html_body: string
265
+ in_reply_to: string
266
+ snippet: string
267
+ }>
268
+ for (const row of due) {
269
+ try {
270
+ await sendMail(this.env, {
271
+ from: row.from_addr,
272
+ to: row.to_addr,
273
+ subject: row.subject,
274
+ text: row.text_body || undefined,
275
+ html: row.html_body || undefined,
276
+ inReplyTo: row.in_reply_to,
277
+ })
278
+ const threadId = this.resolveThreadId(
279
+ row.id,
280
+ row.in_reply_to,
281
+ row.subject,
282
+ row.from_addr,
283
+ row.to_addr,
284
+ )
285
+ const sentAt = new Date().toISOString()
286
+ this.sql.exec(
287
+ `UPDATE messages SET status = 'sent', thread_id = ?, date = ? WHERE id = ?`,
288
+ threadId,
289
+ sentAt,
290
+ row.id,
291
+ )
292
+ await emitWebhook(this.env, 'message.sent', {
293
+ id: row.id,
294
+ threadId,
295
+ from: row.from_addr,
296
+ to: row.to_addr,
297
+ subject: row.subject,
298
+ snippet: row.snippet,
299
+ direction: 'outbound',
300
+ scheduled: true,
301
+ })
302
+ } catch (err) {
303
+ this.sql.exec(
304
+ `UPDATE messages SET status = 'failed', send_error = ? WHERE id = ?`,
305
+ (err as Error).message ?? 'send failed',
306
+ row.id,
307
+ )
308
+ }
309
+ }
310
+ this.armAlarm()
311
+ }
312
+
313
+ /** Scheduled + failed rows, soonest first (failed sort by original slot). */
314
+ listScheduled(limit = 50): ScheduledMeta[] {
192
315
  const capped = Math.min(Math.max(limit, 1), 200)
193
- const rows = (cursor
194
- ? this.sql
195
- .exec(
196
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id
197
- FROM messages WHERE id < ? ORDER BY id DESC LIMIT ?`,
198
- cursor,
199
- capped + 1,
200
- )
201
- .toArray()
202
- : this.sql
203
- .exec(
204
- `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id
205
- FROM messages ORDER BY id DESC LIMIT ?`,
206
- capped + 1,
207
- )
208
- .toArray()) as unknown as MessageMeta[]
316
+ return this.sql
317
+ .exec(
318
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction,
319
+ thread_id, status, label, scheduled_at, send_error
320
+ FROM messages WHERE status IN ('scheduled', 'failed')
321
+ ORDER BY scheduled_at ASC LIMIT ?`,
322
+ capped,
323
+ )
324
+ .toArray() as unknown as ScheduledMeta[]
325
+ }
326
+
327
+ /**
328
+ * Cancel a pending scheduled send (deletes the row). Failed rows can be
329
+ * cancelled too — that's how they're dismissed. Returns false if the id
330
+ * isn't a scheduled/failed row.
331
+ */
332
+ cancelScheduled(id: string): boolean {
333
+ const row = this.sql
334
+ .exec(`SELECT status FROM messages WHERE id = ?`, id)
335
+ .toArray()[0] as unknown as { status: string } | undefined
336
+ if (!row || (row.status !== 'scheduled' && row.status !== 'failed')) return false
337
+ this.sql.exec(`DELETE FROM messages WHERE id = ?`, id)
338
+ this.armAlarm()
339
+ return true
340
+ }
341
+
342
+ /** Update an unsent draft's editable fields. Returns false if not a draft. */
343
+ updateDraft(
344
+ id: string,
345
+ fields: Partial<
346
+ Pick<
347
+ InsertMessage,
348
+ 'from_addr' | 'to_addr' | 'subject' | 'text_body' | 'html_body' | 'in_reply_to' | 'snippet'
349
+ >
350
+ >,
351
+ ): boolean {
352
+ const row = this.sql
353
+ .exec(`SELECT status FROM messages WHERE id = ?`, id)
354
+ .toArray()[0] as unknown as { status: string } | undefined
355
+ if (!row || row.status !== 'draft') return false
356
+ const cols = Object.keys(fields) as Array<keyof typeof fields>
357
+ if (cols.length === 0) return true
358
+ this.sql.exec(
359
+ `UPDATE messages SET ${cols.map((c) => `${c} = ?`).join(', ')} WHERE id = ?`,
360
+ ...cols.map((c) => fields[c] ?? ''),
361
+ id,
362
+ )
363
+ return true
364
+ }
365
+
366
+ /**
367
+ * Flip a draft to sent: resolve its thread NOW (against what actually
368
+ * exists at send time) and stamp the send date. Returns null if the row
369
+ * isn't an unsent draft.
370
+ */
371
+ markDraftSent(id: string, date: string): { threadId: string } | null {
372
+ const row = this.sql
373
+ .exec(
374
+ `SELECT status, in_reply_to, subject, from_addr, to_addr FROM messages WHERE id = ?`,
375
+ id,
376
+ )
377
+ .toArray()[0] as unknown as
378
+ | { status: string; in_reply_to: string; subject: string; from_addr: string; to_addr: string }
379
+ | undefined
380
+ if (!row || row.status !== 'draft') return null
381
+ const threadId = this.resolveThreadId(
382
+ id,
383
+ row.in_reply_to,
384
+ row.subject,
385
+ row.from_addr,
386
+ row.to_addr,
387
+ )
388
+ this.sql.exec(
389
+ `UPDATE messages SET status = 'sent', thread_id = ?, date = ? WHERE id = ?`,
390
+ threadId,
391
+ date,
392
+ id,
393
+ )
394
+ return { threadId }
395
+ }
396
+
397
+ /** Newest-first drafts (metadata only). */
398
+ listDrafts(limit = 50): MessageMeta[] {
399
+ const capped = Math.min(Math.max(limit, 1), 200)
400
+ return this.sql
401
+ .exec(
402
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
403
+ FROM messages WHERE status = 'draft' ORDER BY id DESC LIMIT ?`,
404
+ capped,
405
+ )
406
+ .toArray() as unknown as MessageMeta[]
407
+ }
408
+
409
+ /**
410
+ * Case-insensitive keyword search over subject + text_body. Plain LIKE —
411
+ * fine at this table's scale; revisit with an FTS index if volume grows.
412
+ * Drafts included; newest first.
413
+ */
414
+ search(q: string, limit = 50): MessageMeta[] {
415
+ const capped = Math.min(Math.max(limit, 1), 200)
416
+ const term = `%${q.replace(/[\\%_]/g, (c) => `\\${c}`)}%`
417
+ return this.sql
418
+ .exec(
419
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
420
+ FROM messages
421
+ WHERE subject LIKE ? ESCAPE '\\' OR text_body LIKE ? ESCAPE '\\'
422
+ ORDER BY id DESC LIMIT ?`,
423
+ term,
424
+ term,
425
+ capped,
426
+ )
427
+ .toArray() as unknown as MessageMeta[]
428
+ }
429
+
430
+ /** Set the classifier label. No-op if the row is gone (delete raced it). */
431
+ setLabel(id: string, label: string): void {
432
+ this.sql.exec(`UPDATE messages SET label = ? WHERE id = ?`, label, id)
433
+ }
434
+
435
+ /**
436
+ * Newest-first page (drafts excluded — see listDrafts). `cursor` is the
437
+ * last-seen id (ids are time-ordered). `label` filters to one label.
438
+ */
439
+ list(
440
+ limit = 50,
441
+ cursor?: string,
442
+ label?: string,
443
+ ): { messages: MessageMeta[]; nextCursor: string | null } {
444
+ const capped = Math.min(Math.max(limit, 1), 200)
445
+ const where = [`status = 'sent'`]
446
+ const params: unknown[] = []
447
+ if (cursor) {
448
+ where.push('id < ?')
449
+ params.push(cursor)
450
+ }
451
+ if (label) {
452
+ where.push('label = ?')
453
+ params.push(label)
454
+ }
455
+ const rows = this.sql
456
+ .exec(
457
+ `SELECT id, from_addr, to_addr, subject, date, snippet, size, created_at, direction, thread_id, status, label
458
+ FROM messages WHERE ${where.join(' AND ')} ORDER BY id DESC LIMIT ?`,
459
+ ...params,
460
+ capped + 1,
461
+ )
462
+ .toArray() as unknown as MessageMeta[]
209
463
  const hasMore = rows.length > capped
210
464
  const page = hasMore ? rows.slice(0, capped) : rows
211
465
  return { messages: page, nextCursor: hasMore ? page[page.length - 1]!.id : null }
@@ -219,10 +473,11 @@ export class Inbox extends DurableObject {
219
473
  const capped = Math.min(Math.max(limit, 1), 200)
220
474
  const base = `
221
475
  SELECT m.id, m.from_addr, m.to_addr, m.subject, m.date, m.snippet, m.size,
222
- m.created_at, m.direction, m.thread_id,
476
+ m.created_at, m.direction, m.thread_id, m.status, m.label,
223
477
  (SELECT COUNT(*) FROM messages c WHERE c.thread_id = m.thread_id) AS thread_count
224
478
  FROM messages m
225
- WHERE m.id = (SELECT MAX(id) FROM messages x WHERE x.thread_id = m.thread_id)`
479
+ WHERE m.status = 'sent'
480
+ AND m.id = (SELECT MAX(id) FROM messages x WHERE x.thread_id = m.thread_id)`
226
481
  const rows = (cursor
227
482
  ? this.sql
228
483
  .exec(`${base} AND m.id < ? ORDER BY m.id DESC LIMIT ?`, cursor, capped + 1)
@@ -241,7 +496,7 @@ export class Inbox extends DurableObject {
241
496
  .exec(
242
497
  `SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
243
498
  text_body, html_body, r2_key, attachments_json, size, created_at,
244
- direction, in_reply_to, thread_id
499
+ direction, in_reply_to, thread_id, status, label
245
500
  FROM messages WHERE thread_id = ? ORDER BY id ASC`,
246
501
  threadId,
247
502
  )
@@ -257,7 +512,7 @@ export class Inbox extends DurableObject {
257
512
  .exec(
258
513
  `SELECT id, message_id, from_addr, to_addr, subject, date, snippet,
259
514
  text_body, html_body, r2_key, attachments_json, size, created_at,
260
- direction, in_reply_to, thread_id
515
+ direction, in_reply_to, thread_id, status, label
261
516
  FROM messages WHERE id = ?`,
262
517
  id,
263
518
  )