@lupinum/better-convex-agents 0.1.0 → 0.2.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.
Files changed (54) hide show
  1. package/dist/agent/AGENTS.md +6 -3
  2. package/dist/agent/pages/docs/build/application-behavior/error-handling.md +40 -1
  3. package/dist/agent/pages/docs/build/authentication/account-deletion.md +73 -0
  4. package/dist/agent/pages/docs/build/authentication/backend-authorization.md +6 -1
  5. package/dist/agent/pages/docs/build/authentication/better-auth-setup.md +3 -1
  6. package/dist/agent/pages/docs/build/authentication/sign-in-and-sign-out.md +3 -0
  7. package/dist/agent/pages/docs/build/authentication/transactional-email.md +45 -10
  8. package/dist/agent/pages/docs/build/files/private-downloads.md +126 -0
  9. package/dist/agent/pages/docs/build/files/storage-urls.md +8 -3
  10. package/dist/agent/pages/docs/build/files/upload-files.md +2 -2
  11. package/dist/agent/pages/docs/build/functions/limits-and-audit.md +142 -4
  12. package/dist/agent/pages/docs/build/functions/testing.md +24 -0
  13. package/dist/agent/pages/docs/build/queries/loading-and-stale-data.md +1 -1
  14. package/dist/agent/pages/docs/build/queries/pagination.md +2 -2
  15. package/dist/agent/pages/docs/build/queries/reactive-arguments.md +46 -0
  16. package/dist/agent/pages/docs/build/server/server-convex.md +16 -1
  17. package/dist/agent/pages/docs/build/write-data/concurrent-operations.md +1 -1
  18. package/dist/agent/pages/docs/build/write-data/forms.md +1 -1
  19. package/dist/agent/pages/docs/build/write-data/multi-step-operations.md +1 -1
  20. package/dist/agent/pages/docs/build/write-data/optimistic-updates.md +1 -1
  21. package/dist/agent/pages/docs/get-started/add-authentication.md +13 -3
  22. package/dist/agent/pages/docs/get-started/complete-and-delete.md +2 -0
  23. package/dist/agent/pages/docs/get-started/first-realtime-page.md +3 -1
  24. package/dist/agent/pages/docs/get-started/installation.md +3 -0
  25. package/dist/agent/pages/docs/get-started/next-steps.md +30 -0
  26. package/dist/agent/pages/docs/get-started/plain-vue.md +143 -41
  27. package/dist/agent/pages/docs/operations/before-launch.md +1 -1
  28. package/dist/agent/pages/docs/operations/log-streams.md +128 -0
  29. package/dist/agent/pages/docs/recipes/dynamic-query-list.md +1 -1
  30. package/dist/agent/pages/docs/recipes/error-messages.md +1 -1
  31. package/dist/agent/pages/docs/recipes/guest-users.md +67 -15
  32. package/dist/agent/pages/docs/recipes/multiple-file-uploads.md +1 -1
  33. package/dist/agent/pages/docs/recipes/optimistic-todo-list.md +1 -1
  34. package/dist/agent/pages/docs/recipes/realtime-feed.md +1 -1
  35. package/dist/agent/pages/docs/recipes/sign-in-link.md +129 -0
  36. package/dist/agent/pages/docs/reference/api-surface.md +11 -0
  37. package/dist/agent/pages/docs/reference/error-types.md +12 -2
  38. package/dist/agent/pages/docs/reference/operation-error-codes.md +15 -1
  39. package/dist/agent/pages/docs/reference/package-exports.md +3 -2
  40. package/dist/agent/pages/docs/reference/server-api.md +5 -1
  41. package/dist/index.d.mts +1 -1
  42. package/dist/index.d.ts +1 -1
  43. package/dist/index.mjs +1 -1
  44. package/dist/internal.d.mts +1 -1
  45. package/dist/internal.d.ts +1 -1
  46. package/dist/internal.mjs +1 -1
  47. package/dist/mcp.mjs +4 -2
  48. package/dist/shared/{better-convex-agents.DWStY2mj.mjs → better-convex-agents.BAvd6ID4.mjs} +475 -393
  49. package/dist/shared/{better-convex-agents.Jrci7p3C.d.mts → better-convex-agents.l5qUkNCR.d.mts} +14 -2
  50. package/dist/shared/{better-convex-agents.Jrci7p3C.d.ts → better-convex-agents.l5qUkNCR.d.ts} +14 -2
  51. package/dist/test.d.mts +1 -1
  52. package/dist/test.d.ts +1 -1
  53. package/dist/test.mjs +1 -1
  54. package/package.json +3 -3
@@ -0,0 +1,128 @@
1
+ ---
2
+ title: "Log streams and PostHog"
3
+ description: "Send call events and Convex logs to PostHog, find a failed call by its request ID, and follow work across scheduled jobs."
4
+ url: "https://better-convex.lupinum.com/docs/operations/log-streams"
5
+ route: "/docs/operations/log-streams"
6
+ locale: "en"
7
+ section: "Documentation"
8
+ collection: "docs"
9
+ source: "ginko-content"
10
+ ---
11
+
12
+ # Log streams and PostHog
13
+
14
+ > Send call events and Convex logs to PostHog, find a failed call by its request ID, and follow work across scheduled jobs.
15
+
16
+ A Convex log stream sends every log record of a deployment to a log service.
17
+ With [call events](../build/functions/limits-and-audit.md#call-events) turned
18
+ on, you can then answer, after the fact, who ran which action in which tenant,
19
+ and why it failed. This page uses PostHog Logs. Other log services work the
20
+ same way, but their search differs.
21
+
22
+ ## What the stream sends
23
+
24
+ | Record | Content |
25
+ | --- | --- |
26
+ | Call event (`console` topic) | One line for each call with `observe: true` (a query only when it fails): action, actor, tenant, outcome, code and trace. |
27
+ | Function execution | Convex's own record for each call: function path, duration, status, request ID, and the error text with its stack trace. |
28
+ | Console lines | Every `console.log` of your Convex functions, as it was written. |
29
+
30
+ The call event and Convex's record of the same call have the same request ID.
31
+
32
+ ## Before you start
33
+
34
+ - Use the Convex Pro plan. Log streams are not available on the free plan.
35
+ - Turn on call events: `defineFunctions({ …, observe: true })`.
36
+ - Create a PostHog project in the region of your users' data, for example
37
+ PostHog EU Cloud for users in the EU.
38
+
39
+ <warning>
40
+ The stream copies error texts and console lines to PostHog as they are. Before
41
+ you connect it, check that your error messages and `console.log` calls do not
42
+ contain values that a person typed, such as names, amounts or email addresses.
43
+ Put such values in neither `fail()` messages nor `why` and `fix`. Write IDs.
44
+ </warning>
45
+
46
+ ## Connect PostHog Logs
47
+
48
+ 1. In PostHog, open **Settings > Project > General** and copy the project
49
+ token. It starts with `phc_`.
50
+ 2. In the Convex dashboard, open the deployment, then **Settings >
51
+ Integrations**.
52
+ 3. Add **PostHog Logs**.
53
+ 4. Paste the project token.
54
+ 5. Set **Host** to the host of your PostHog region, for example
55
+ `https://eu.i.posthog.com`. Without a host, Convex sends to the US region.
56
+ 6. Set **Service name** to a name for this deployment, for example `myapp-prod`.
57
+ Use a different name for each deployment.
58
+ 7. Under **Topics**, select `console` and `function_execution`. Leave the
59
+ other topics off until you need them.
60
+ 8. Save. Convex sends a verification record to PostHog.
61
+
62
+ The **PostHog Error Tracking** integration is a separate integration. It sends
63
+ each failed call as an exception, with the full error text. Add it if you want
64
+ failures grouped as issues.
65
+
66
+ ## Find a call
67
+
68
+ Open **Logs** in PostHog. Filter on the `service.name` resource attribute to
69
+ see one deployment. Then use the **Message** filter with `contains`:
70
+
71
+ | To find | Message contains |
72
+ | --- | --- |
73
+ | One call that a user reported | The request ID that the user quoted, for example `c80d6e0f0e0198a1` |
74
+ | All call events | `better-convex.call` |
75
+ | Refused calls | `better-convex.call`, and in a second filter `FORBIDDEN` |
76
+ | Everything one call started | The `trace` of its event, for example `5123956460443c3b` |
77
+ | Everything one agent did | The agent's key, for example `mcp:k57…:claude-desktop` |
78
+ | Calls of revoked agents | `better-convex.call`, and in a second filter `AGENT_DISABLED` |
79
+
80
+ A search for a request ID shows the call event and Convex's record of the same
81
+ call. The call event says who acted and with which code. Convex's record has
82
+ the duration, the final status and the error text.
83
+
84
+ A search for an agent's key finds its tool calls, where it is the `actor`,
85
+ and the decisions of people on its requests, where it is the `agent`.
86
+
87
+ A search for a `trace` shows the events of each call in the chain: the call
88
+ itself and the internal operations, internal actions and jobs it scheduled or
89
+ ran, also those that ran hours later. Convex gives each scheduled call a new
90
+ request ID, so only the `trace` connects them.
91
+
92
+ To see the calls of one function, filter on the `convex.function.path`
93
+ attribute, for example `clients:create`.
94
+
95
+ Search for a word, a code or an ID, not for a part of the JSON line such as
96
+ `"code":"FORBIDDEN"`. PostHog stores Convex's record as the message, and the
97
+ call event is a quoted string inside it, so each quotation mark of the call
98
+ event has a backslash before it.
99
+
100
+ Each field of a call event is text in the message, not an attribute of its
101
+ own. You can filter by words and IDs, but you cannot group or count by `actor`
102
+ or `code` in the filter bar.
103
+
104
+ ## Get an alert
105
+
106
+ Save a filter as a view, for example `better-convex.call` and `FORBIDDEN`. Add
107
+ a PostHog alert on that view to get a message when the number of matching
108
+ lines goes over a limit. A sudden rise in refused calls can show a broken
109
+ client or someone who tries to read data of other tenants. A rise in
110
+ `AGENT_DISABLED` or `RATE_LIMITED` can show a stolen agent token that is still
111
+ in use.
112
+
113
+ ## Protect the logs
114
+
115
+ Call events contain user IDs and tenant IDs. Under the GDPR, these are personal
116
+ data, even without a name.
117
+
118
+ - Sign a data processing agreement with PostHog.
119
+ - Check how long your PostHog plan keeps logs, and keep them no longer than you need.
120
+ - Give access to the PostHog project only to the people who need it. They see
121
+ the activity of every user in every tenant.
122
+ - Set a volume limit or a billing limit in PostHog. Anyone can make queries
123
+ fail, and failed queries write call events without a rate limit.
124
+
125
+ The project token can only send data, but anyone who has it can send false
126
+ records. Use the logs to find problems. Use the
127
+ [audit log](../build/functions/limits-and-audit.md#audit-log) in your own
128
+ database as the record of who changed which rows.
@@ -23,7 +23,7 @@ A component calls `useConvexQuery` in `<script setup>`, which runs once, so one
23
23
 
24
24
  ```vue [app/components/ProjectCard.vue]
25
25
  <script setup lang="ts">
26
- import type { Id } from '~~/convex/_generated/dataModel'
26
+ import type { Id } from '#convex/dataModel'
27
27
  import { api } from '#convex/api'
28
28
 
29
29
  const props = defineProps<{ projectId: Id<'projects'> }>()
@@ -83,7 +83,7 @@ export function isCancelled(cause: unknown) {
83
83
  ```vue [app/components/ArchiveButton.vue]
84
84
  <script setup lang="ts">
85
85
  import { api } from '#convex/api'
86
- import type { Id } from '~~/convex/_generated/dataModel'
86
+ import type { Id } from '#convex/dataModel'
87
87
 
88
88
  const props = defineProps<{ projectId: Id<'projects'> }>()
89
89
  const toast = useToast() // Nuxt UI; use your own notification component
@@ -75,6 +75,54 @@ Better Auth rejects another anonymous sign-in while the visitor has a guest
75
75
  session. Better Convex exchanges that session for a Convex session token.
76
76
  No separate guest session store is needed.
77
77
 
78
+ ## Allow guests in an invite-only app
79
+
80
+ `beforeUserCreate` also runs for each new guest. A guest has a generated
81
+ address that nobody proved, so a check of `emailVerified` refuses every guest.
82
+ Read `user.isAnonymous` to let guests through and check everyone else:
83
+
84
+ ```ts [convex/auth.ts]
85
+ export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
86
+ experimental: { anonymous: true },
87
+ beforeUserCreate: async ({ ctx, user }) => {
88
+ if (user.isAnonymous) return { allowed: true }
89
+ if (!user.emailVerified) return { allowed: false }
90
+ const invite = await ctx.runQuery(internal.members.findInvite, { email: user.email })
91
+ return invite ? { allowed: true } : { allowed: false }
92
+ },
93
+ })
94
+ ```
95
+
96
+ Never give a guest access because of its address. Give it access in your Convex
97
+ functions only after `user.isAnonymous === true` is checked.
98
+
99
+ ## Limit new guests per address
100
+
101
+ Each guest sign-in creates a user and a session. Better Convex gives each
102
+ client address a bucket of 10 new guests that refills one every 6 minutes (10
103
+ per hour over time). Better Auth's own limit of 3 sign-ins per 10 seconds per
104
+ address still applies, so even a full bucket lets guests in at that pace. The
105
+ address is the verified client address that the auth proxy
106
+ signs. A visitor over the limit gets `429`. Change the
107
+ limit with `rateLimit`:
108
+
109
+ ```ts [convex/auth.ts]
110
+ export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
111
+ experimental: { anonymous: { rateLimit: { window: 60 * 60, max: 30 } } },
112
+ })
113
+ ```
114
+
115
+ `window` is in seconds, from 60 to 86,400. `max` is from 1 to 1,000. The bucket
116
+ holds `max` sign-ins and refills one every `window / max` seconds, so it is not
117
+ a fixed window: with the example, the bucket holds 30 guests and refills one
118
+ every 2 minutes. Better Auth's limit of 3 sign-ins per 10 seconds still applies
119
+ on top. Each guest
120
+ sign-in writes the counter of its address in the component's `rateLimit` table. An IPv6
121
+ address counts by its /64 network, as in Better Auth's own limits, because one
122
+ connection usually owns a whole /64. Many visitors behind one network address,
123
+ for example at a school or an office, share one budget. The limit covers sign-in requests through `/api/auth`, not
124
+ `auth.api` calls from your own Convex code.
125
+
78
126
  ## Preserve profile data when the guest signs in
79
127
 
80
128
  Better Auth calls `onLinkAccount` with the authenticated guest and the new
@@ -149,15 +197,22 @@ to retain that identity. That option does not expire old guests.
149
197
  ## Remove old guests
150
198
 
151
199
  Choose a retention period before enabling cleanup. This example deletes guests
152
- created more than 30 days ago, including guests with active sessions. It processes
153
- at most 100 guests per page and deletes their auth records through the component
154
- API. It does not delete documents in application tables.
200
+ created more than 30 days ago, including guests with active sessions. It deletes
201
+ each one with `auth.deleteUser`, the same way as
202
+ [deleting another user](../build/authentication/account-deletion.md#delete-another-user-from-a-convex-function).
203
+ Your `onDelete` triggers run, so a user projection deletes the guest's app user
204
+ row and runs its `erase` hook.
205
+
206
+ All of this happens in one mutation per page, so the page is small: 25 guests.
207
+ A larger page can exceed Convex's transaction limits, and then the whole page
208
+ fails. Use fewer guests per page when your `erase` hook deletes many rows.
155
209
 
156
210
  ```ts [convex/guests.ts]
157
211
  import { v } from 'convex/values'
158
212
 
159
213
  import { components, internal } from './_generated/api'
160
214
  import { internalMutation } from './_generated/server'
215
+ import { auth } from './auth'
161
216
 
162
217
  export const pruneGuests = internalMutation({
163
218
  args: {
@@ -166,21 +221,17 @@ export const pruneGuests = internalMutation({
166
221
  },
167
222
  handler: async (ctx, args): Promise<null> => {
168
223
  const cutoff = args.cutoff ?? Date.now() - 30 * 24 * 60 * 60 * 1000
169
- const where = [
170
- { field: 'isAnonymous', value: true },
171
- { field: 'createdAt', operator: 'lt' as const, value: cutoff },
172
- ]
173
224
  const users = await ctx.runQuery(components.betterAuth.adapter.findMany, {
174
225
  model: 'user',
175
- where,
176
- paginationOpts: { cursor: args.cursor ?? null, numItems: 100 },
226
+ where: [
227
+ { field: 'isAnonymous', value: true },
228
+ { field: 'createdAt', operator: 'lt', value: cutoff },
229
+ ],
230
+ paginationOpts: { cursor: args.cursor ?? null, numItems: 25 },
177
231
  })
178
232
  for (const user of users.page) {
179
233
  if (typeof user.id !== 'string') throw new Error('Invalid auth user ID')
180
- await ctx.runMutation(components.betterAuth.adapter.deleteOne, {
181
- model: 'user',
182
- where: [{ field: 'id', value: user.id }, ...where],
183
- })
234
+ await auth.deleteUser(ctx, user.id)
184
235
  }
185
236
  if (!users.isDone) {
186
237
  await ctx.scheduler.runAfter(0, internal.guests.pruneGuests, {
@@ -204,5 +255,6 @@ export default crons
204
255
  ```
205
256
 
206
257
  Deletion removes the user's sessions and related auth records. Queries that
207
- read those component records become current. Add cleanup for application data
208
- in the same internal Convex mutation if your application stores guest documents.
258
+ read those component records become current. Without a user projection, add
259
+ cleanup for application data in the same internal Convex mutation if your
260
+ application stores guest documents.
@@ -65,7 +65,7 @@ Both functions check the user and the entry. `attachImages` also claims the two
65
65
  <script setup lang="ts">
66
66
  import { useConvexOperation } from '@lupinum/better-convex-nuxt/experimental'
67
67
  import { api } from '#convex/api'
68
- import type { Id } from '~~/convex/_generated/dataModel'
68
+ import type { Id } from '#convex/dataModel'
69
69
 
70
70
  const props = defineProps<{ entryId: Id<'entries'> }>()
71
71
 
@@ -22,7 +22,7 @@ This recipe uses the `todos` table and functions from [Protect data](../get-star
22
22
  ## Create
23
23
 
24
24
  ```ts
25
- import type { Id } from '~~/convex/_generated/dataModel'
25
+ import type { Id } from '#convex/dataModel'
26
26
  import { api } from '#convex/api'
27
27
 
28
28
  const { user } = useConvexAuth()
@@ -99,7 +99,7 @@ The same `CHANNEL_NOT_FOUND` error for a missing channel and for a channel the u
99
99
 
100
100
  ```vue [app/components/ChannelFeed.vue]
101
101
  <script setup lang="ts">
102
- import type { Id } from '~~/convex/_generated/dataModel'
102
+ import type { Id } from '#convex/dataModel'
103
103
  import { api } from '#convex/api'
104
104
 
105
105
  const props = defineProps<{ channelId: Id<'channels'> }>()
@@ -0,0 +1,129 @@
1
+ ---
2
+ title: "Sign-in link"
3
+ description: "Put a one-tap sign-in link next to the email code, without a magic-link plugin."
4
+ url: "https://better-convex.lupinum.com/docs/recipes/sign-in-link"
5
+ route: "/docs/recipes/sign-in-link"
6
+ locale: "en"
7
+ section: "Documentation"
8
+ collection: "docs"
9
+ source: "ginko-content"
10
+ ---
11
+
12
+ # Sign-in link
13
+
14
+ > Put a one-tap sign-in link next to the email code, without a magic-link plugin.
15
+
16
+ Add a link to the [email code](../build/authentication/sign-in-and-sign-out.md#email-code-sign-in)
17
+ email. The person taps the link, then taps one button, and is signed in. The
18
+ link carries the same code, so it is as strong as the code: it has the same
19
+ expiry (five minutes by default) and the same attempt limit (three wrong
20
+ codes by default). The typed code still works.
21
+
22
+ This recipe needs `emailOTP` and an `email` hook. Better Convex does not
23
+ support Better Auth's magic-link plugin.
24
+
25
+ ## Put the code in the link fragment
26
+
27
+ Put the code and the address after `#` in the URL. The browser does not send
28
+ this part (the fragment) to any server. So the code does not appear in the URL
29
+ that server logs, proxies and the `Referer` header of the next page record. The
30
+ confirming tap sends the code in a request body, as the typed code does. Do not
31
+ log the bodies of auth requests.
32
+
33
+ ```ts [convex/auth.ts]
34
+ import {
35
+ createBetterConvexAuth,
36
+ requireAuthOrigin,
37
+ } from '@lupinum/better-convex-nuxt/better-auth/server'
38
+
39
+ import { components, internal } from './_generated/api'
40
+ import type { DataModel } from './_generated/dataModel'
41
+
42
+ export const auth = createBetterConvexAuth<DataModel>(components.betterAuth, {
43
+ emailOTP: {},
44
+ email: async (ctx, message) => {
45
+ if (message.type === 'email-otp' && message.purpose === 'sign-in') {
46
+ const fragment = new URLSearchParams({ code: message.otp, email: message.to })
47
+ await ctx.runMutation(internal.authMail.submitSignInCode, {
48
+ recipient: message.to,
49
+ code: message.otp,
50
+ url: `${requireAuthOrigin('SITE_URL')}/sign-in#${fragment}`,
51
+ })
52
+ return
53
+ }
54
+ // Keep the cases for the other messages that your hook already sends.
55
+ throw new Error(`Unsupported auth email: ${message.type}`)
56
+ },
57
+ })
58
+ ```
59
+
60
+ `internal.authMail.submitSignInCode` is your own internal mutation. It queues
61
+ the email with the code and the link. See
62
+ [Transactional auth email](../build/authentication/transactional-email.md#submit-durable-work).
63
+ Show the code in the email too, for a person who reads mail on another device.
64
+
65
+ ## Ask for one tap
66
+
67
+ Mail scanners and link previews open links before the person does. Do not sign
68
+ in when the page loads. Read the fragment, remove it from the address bar, and
69
+ wait for the person to tap the button.
70
+
71
+ Show the email address before the tap. An attacker can send a victim a link
72
+ with the attacker's own code. Without the address on the page, the victim would
73
+ sign in to the attacker's account and put private data there.
74
+
75
+ ```vue [app/pages/sign-in.vue]
76
+ <script setup lang="ts">
77
+ definePageMeta({ convexAuth: 'guest' })
78
+
79
+ const { client } = useConvexAuth()
80
+ const link = ref<{ code: string; email: string } | null>(null)
81
+ const busy = ref(false)
82
+ const formError = ref('')
83
+
84
+ function readLink() {
85
+ const params = new URLSearchParams(window.location.hash.slice(1))
86
+ const code = params.get('code') ?? ''
87
+ const email = params.get('email') ?? ''
88
+ if (window.location.hash) {
89
+ // Remove the code from the address bar and from the browser history entry.
90
+ history.replaceState(history.state, '', window.location.pathname + window.location.search)
91
+ }
92
+ // Six digits is the default `emailOTP.otpLength`.
93
+ if (/^\d{6}$/.test(code) && email.includes('@')) link.value = { code, email }
94
+ }
95
+
96
+ onMounted(() => {
97
+ readLink()
98
+ // The link can open in a tab that already shows this page.
99
+ window.addEventListener('hashchange', readLink)
100
+ })
101
+ onBeforeUnmount(() => window.removeEventListener('hashchange', readLink))
102
+
103
+ async function confirmLink() {
104
+ if (!link.value) return
105
+ busy.value = true
106
+ const { code, email } = link.value
107
+ const result = await client.signIn.emailOtp({ email, otp: code })
108
+ busy.value = false
109
+ if (result.error) {
110
+ formError.value = 'The link has expired. Ask for a new code.'
111
+ link.value = null
112
+ return
113
+ }
114
+ await navigateTo('/')
115
+ }
116
+ </script>
117
+
118
+ <template>
119
+ <section v-if="link">
120
+ <p>Sign in as {{ link.email }}?</p>
121
+ <button type="button" :disabled="busy" @click="confirmLink">Sign in</button>
122
+ <button type="button" @click="link = null">Type the code instead</button>
123
+ </section>
124
+ <section v-else>
125
+ <p v-if="formError" role="alert">{{ formError }}</p>
126
+ <!-- Your email and code form from the email code sign-in example. -->
127
+ </section>
128
+ </template>
129
+ ```
@@ -25,6 +25,7 @@ request that changes one of them.
25
25
  | Alias | Points to | Use it in |
26
26
  | --- | --- | --- |
27
27
  | `#convex/api` | Your app's `convex/_generated/api` | Vue components, composables, route middleware, Nitro server routes, tests |
28
+ | `#convex/dataModel` | Your app's `convex/_generated/dataModel`, types only | The same places, with `import type` |
28
29
  | `#convex/server` | The `@lupinum/better-convex-nuxt/server` exports | Nitro server routes and server utilities |
29
30
  | `#convex/auth-client` | The Better Auth client definition from `convex.auth.client` | Auth-enabled builds only |
30
31
 
@@ -36,6 +37,16 @@ import { api } from '#convex/api'
36
37
 
37
38
  Before Convex creates `convex/_generated/api`, this alias points to a placeholder. Imports still compile. Reading a function from it throws an error that tells you to run Convex codegen.
38
39
 
40
+ Use `#convex/dataModel` for the generated document types, such as `Id` and `Doc`:
41
+
42
+ ```ts
43
+ import type { Id } from '#convex/dataModel'
44
+ ```
45
+
46
+ This alias has no placeholder. Run Convex codegen before you import from it; until `convex/_generated/dataModel` exists, the import fails type-checking.
47
+
48
+ Convex generates only type declarations for the data model, so import it with `import type`. Code in `convex/` imports it by a path relative to the file (`./_generated/dataModel` in `convex/`, `../_generated/dataModel` in `convex/lib/`), because Convex bundles those files without Nuxt aliases.
49
+
39
50
  ## Published package entries
40
51
 
41
52
  ### Nuxt package
@@ -58,14 +58,21 @@ The kind never depends on the message text.
58
58
  | `functionName` | `string \| undefined` |
59
59
  | `outcome` | `ConvexCallOutcome \| undefined` |
60
60
  | `phase` | `ConvexUploadPhase \| undefined` |
61
+ | `why` | `string \| undefined` |
62
+ | `fix` | `string \| undefined` |
63
+ | `requestId` | `string \| undefined` |
61
64
 
62
65
  `functionName` is the Convex function path, for example `notes:create`. Composables, `serverConvex`, server-rendered queries, and uploads set it.
63
66
 
64
67
  `code` is a `ConvexCallErrorCode` for a failure that Better Convex raises itself. For a Convex application error, it is the application's `data.code`.
65
68
 
69
+ `why` and `fix` are the `data.why` and `data.fix` of a Convex application error: why the function refused, and what the user can do. See [Show why and how to fix it](../build/application-behavior/error-handling.md#show-why-and-how-to-fix-it).
70
+
71
+ `requestId` is the Convex request ID of a call that failed in a Convex function. The Convex logs record the same ID. It is read from the error text of Convex; when that text has no ID, `requestId` is `undefined`.
72
+
66
73
  `ConvexCallError` has no `cause`. The original error object is not kept, so it cannot leak through the error, its JSON, or the server-rendered payload. Only the development logger described below writes it, to the console.
67
74
 
68
- Construct one with `new ConvexCallError(input)`, where `input` is a `ConvexCallErrorInput`: `kind` and `message` are required, and `code`, `status`, `data`, `functionName`, `outcome`, and `phase` are optional. `toJSON()` returns a `SerializedConvexCallError`.
75
+ Construct one with `new ConvexCallError(input)`, where `input` is a `ConvexCallErrorInput`: `kind` and `message` are required, and `code`, `status`, `data`, `functionName`, `outcome`, `phase`, `why`, `fix`, and `requestId` are optional. `toJSON()` returns a `SerializedConvexCallError`.
69
76
 
70
77
  ### Message
71
78
 
@@ -208,7 +215,7 @@ try {
208
215
  isSerializedConvexCallError(value: unknown): value is SerializedConvexCallError
209
216
  ```
210
217
 
211
- `normalizeConvexError` uses this check before it turns a value back into a `ConvexCallError`. It accepts only a plain object with the keys below and no other keys, a known `kind`, and a string `message`. When present, `code` and `functionName` must be non-empty strings, `status` must be a finite number, and `outcome` and `phase` must be known values. `name: 'ConvexCallError'` alone is not enough. A value with an extra key, such as `stack`, fails the check.
218
+ `normalizeConvexError` uses this check before it turns a value back into a `ConvexCallError`. It accepts only a plain object with the keys below and no other keys, a known `kind`, and a string `message`. When present, `code`, `functionName`, `why`, and `fix` must be non-empty strings, `status` must be a finite number, `outcome` and `phase` must be known values, and `requestId` must be hexadecimal. `name: 'ConvexCallError'` alone is not enough. A value with an extra key, such as `stack`, fails the check.
212
219
 
213
220
  ```ts
214
221
  interface SerializedConvexCallError {
@@ -221,6 +228,9 @@ interface SerializedConvexCallError {
221
228
  functionName?: string
222
229
  outcome?: ConvexCallOutcome
223
230
  phase?: ConvexUploadPhase
231
+ why?: string
232
+ fix?: string
233
+ requestId?: string
224
234
  }
225
235
  ```
226
236
 
@@ -24,12 +24,25 @@ import { fail, type ErrorCode } from '@lupinum/better-convex-functions'
24
24
  Your own handlers use the same codes: `fail('INVALID_INPUT', 'name: use 1 to 100 characters.')`.
25
25
  A misspelled code is a type error.
26
26
 
27
+ A third argument tells the caller why the call failed and what to do. Write it for the person or
28
+ agent who reads it:
29
+
30
+ ```ts
31
+ fail('INVALID_INPUT', 'name: use 1 to 100 characters.', {
32
+ why: 'Project names are shown in lists.',
33
+ fix: 'Shorten the name to 100 characters or fewer.',
34
+ })
35
+ ```
36
+
37
+ `NOT_FOUND` and `FAILED` take no `why` or `fix`. `NOT_FOUND` must read like a missing row, so it
38
+ cannot tell that a row exists that the actor may not see. `FAILED` keeps its detail in the log.
39
+
27
40
  ## Where the code arrives
28
41
 
29
42
  | Caller | What it receives |
30
43
  | --- | --- |
31
44
  | The web client | A `ConvexCallError` of kind `server`. `error.code` is the code. Check it with `isConvexCallError(error, 'FORBIDDEN')` |
32
- | An MCP host or in-app agent | A tool result `{ error: { code, message } }`, marked as an error |
45
+ | An MCP host or in-app agent | A tool result `{ error: { code, message, why?, fix? } }`, marked as an error |
33
46
  | The approval page | `approve` returns `{ status: 'failed', error: { code, message } }` for a failure of the approved work |
34
47
 
35
48
  An error without a code never reaches a caller with its details. The web
@@ -85,6 +98,7 @@ your modules or while a call runs, so you see them in development.
85
98
  | `Tool name "…"` | A tool name has characters that some hosts reject | Use 1 to 64 letters, digits, `_` or `-` |
86
99
  | `Two operations use the tool name …` | Two operations share a tool name | Rename one |
87
100
  | `…: the argument name request_id is reserved` | A mutation tool has an argument called `request_id` | Rename the argument |
101
+ | `Job …: the argument name … is reserved` | A job has an argument called `actingAs`, `input`, `inner` or `trace` | Rename the argument |
88
102
  | `…: a paginated tool gets cursor and limit from the library` | A paginated query has its own `cursor` or `limit` argument | Rename the argument |
89
103
  | `Not exported from the agents module: …` | A tool function is not exported from the module that calls `defineTools` | Add the names to `export const { … } = tools.functions` |
90
104
  | `Set the SITE_URL environment variable on the Convex deployment` | An agent asked for approval, and `SITE_URL` is not set | Set `SITE_URL` to the public origin of your application |
@@ -75,12 +75,13 @@ Each package also exports `./agent-docs`, for example `@lupinum/better-convex-nu
75
75
  | Alias | Points to |
76
76
  | --- | --- |
77
77
  | `#convex/api` | Your `convex/_generated/api` |
78
+ | `#convex/dataModel` | Your `convex/_generated/dataModel`. Types only. |
78
79
  | `#convex/server` | `@lupinum/better-convex-nuxt/server` |
79
80
  | `#convex/auth-client` | The file in `convex.auth.client`. Only in builds with auth. |
80
81
 
81
- Use `#convex/api` in components, composables, middleware, and Nitro routes. Code in `convex/` imports `./_generated/api` directly.
82
+ Use `#convex/api` in components, composables, middleware, and Nitro routes, and `import type` from `#convex/dataModel` there for `Id` and `Doc`. Code in `convex/` imports the generated files by a path relative to the file: `./_generated/api` and `./_generated/dataModel` in `convex/`, `../_generated/dataModel` in `convex/lib/`.
82
83
 
83
- Before Convex creates `convex/_generated/api`, `#convex/api` points to a placeholder. Reading a function from it throws an error that tells you to run Convex codegen.
84
+ Before Convex creates `convex/_generated/api`, `#convex/api` points to a placeholder. Reading a function from it throws an error that tells you to run Convex codegen. `#convex/dataModel` has no placeholder: until Convex creates `convex/_generated/dataModel`, importing from it fails type-checking.
84
85
 
85
86
  ## Auto-imports
86
87
 
@@ -66,10 +66,13 @@ getToken(): Promise<string | null>
66
66
  query(query, ...args): Promise<Result>
67
67
  mutation(mutation, ...args): Promise<Result>
68
68
  action(action, ...args): Promise<Result>
69
+ fetch(path: string, init?: { method?: 'GET' | 'HEAD' }): Promise<Response>
69
70
  ```
70
71
 
71
72
  `getToken()` returns the Convex session token for this request, or `null` for an anonymous request. A function without arguments needs no `{}` argument. A function with declared arguments needs its argument object.
72
73
 
74
+ `fetch(path)` sends a `GET` (or `HEAD`) to `path` on the deployment's Convex HTTP actions host, with the Convex session token as `Authorization: Bearer`. It follows the `auth` option like `query`. It resolves with the upstream `Response` for every status and does not read the body, so `maxResponseBytes` does not apply. It does not follow redirects: a redirect comes back as the `3xx` response. `path` must start with one `/` and has no host, `\`, `#`, spaces or control characters; anything else, and any other method, throws `ServerConvexValidationError` before a request is sent. A network failure rejects with kind `transport` and code `NETWORK_ERROR`, or `CANCELLED` when the request was aborted. See [Private downloads](../build/files/private-downloads.md).
75
+
73
76
  Calls reject with a `ConvexCallError` that has `functionName`. A missing required user and a token exchange that rejects the credential use kind `authentication` and code `UNAUTHENTICATED`. When the auth server cannot be reached or answers with an unusable response, the error has kind `transport`. Invalid options throw `ServerConvexValidationError` before any network request.
74
77
 
75
78
  A query stops after `convex.server.queryTimeoutMs` (default 8 seconds), a mutation after 15 seconds, and an action after 60 seconds. A response larger than `convex.server.maxResponseBytes` (default 1 MiB) fails. See [module configuration](./module-configuration.md#server-limits).
@@ -172,7 +175,7 @@ Creates the Better Auth setup for one Convex deployment. It is the only way to c
172
175
  | `appName` | Application name that Better Auth shows, for example in two-factor apps |
173
176
  | `authFunctions` | References to the trigger functions, usually `internal.auth`. Without it, `triggers` do not run. |
174
177
  | `triggers` | `onCreate`, `onUpdate`, and `onDelete` handlers for each auth model, such as `user`. They run in the same mutation as the change. |
175
- | `beforeUserCreate` | Decide whether a new user may sign up. Return `{ allowed: false }` to refuse. |
178
+ | `beforeUserCreate` | Decide whether a new user may sign up. It gets `email`, `emailVerified`, `name`, `image`, and `isAnonymous`. Return `{ allowed: false }` to refuse. |
176
179
  | `email` | One function that sends every auth email: verification, password reset, one-time codes, two-factor codes, and invitations |
177
180
  | `emailAndPassword` | Off unless set. An object turns password sign-in on and requires a verified address; `requireEmailVerification: false` opts out. `passwordReset: true` adds link-based password reset. |
178
181
  | `emailVerification` | Email verification options |
@@ -197,6 +200,7 @@ The returned `auth` object has these members. The cost column lists the database
197
200
  | `getUser(ctx)` | The signed-in user, or `null`. Revoked, expired, and replaced sessions give `null`. | One component query |
198
201
  | `requireUser(ctx)` | Like `getUser`, but throws `ConvexError({ code: 'UNAUTHENTICATED' })` | One component query |
199
202
  | `getAuth(ctx)` | `{ auth, headers }` for `auth.api` calls as the signed-in user, from a mutation or action | One component query |
203
+ | `deleteUser(ctx, userId)` | Deletes another user with Better Auth: sessions, linked accounts and the auth user, with your `onDelete` triggers. Checks no permission: call it from an internal function after your own check. Mutation or action | Reads the user, its sessions and accounts; writes the user, deletes up to 64 sessions, the accounts and the user |
200
204
  | `sessionHttpAction(handler)` | Wrap an HTTP action that must act as the caller's session. The handler gets `{ request, auth, headers, user, sessionId }`. | One component query per request |
201
205
  | `triggerFunctions()` | `onCreate`, `onUpdate`, and `onDelete` internal mutations for `triggers`. Export them from `convex/auth.ts`. | Your trigger code |
202
206
  | `jwksOperatorFunctions()` | `ensureSigningKey`, `rotateSigningKey`, and `pruneSigningKeys` internal functions for signing keys | Runs only when you call them |
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- export { C as CatalogEntry, U as Uploads, a as UploadsOption, d as defineTools, u as uploadRoute } from './shared/better-convex-agents.Jrci7p3C.mjs';
1
+ export { C as CatalogEntry, U as Uploads, a as UploadsOption, d as defineTools, u as uploadRoute } from './shared/better-convex-agents.l5qUkNCR.mjs';
2
2
  import 'convex/server';
3
3
  import '@lupinum/better-convex-functions';
4
4
  import '@lupinum/better-convex-functions/internal';
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- export { C as CatalogEntry, U as Uploads, a as UploadsOption, d as defineTools, u as uploadRoute } from './shared/better-convex-agents.Jrci7p3C.js';
1
+ export { C as CatalogEntry, U as Uploads, a as UploadsOption, d as defineTools, u as uploadRoute } from './shared/better-convex-agents.l5qUkNCR.js';
2
2
  import 'convex/server';
3
3
  import '@lupinum/better-convex-functions';
4
4
  import '@lupinum/better-convex-functions/internal';
package/dist/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export { d as defineTools, u as uploadRoute } from './shared/better-convex-agents.DWStY2mj.mjs';
1
+ export { d as defineTools, u as uploadRoute } from './shared/better-convex-agents.BAvd6ID4.mjs';
2
2
  import '@lupinum/better-convex-functions';
3
3
  import '@lupinum/better-convex-functions/internal';
4
4
  import 'convex/server';
@@ -1,4 +1,4 @@
1
- export { t as toolFailure } from './shared/better-convex-agents.Jrci7p3C.mjs';
1
+ export { t as toolFailure } from './shared/better-convex-agents.l5qUkNCR.mjs';
2
2
  import { LibraryDataModel } from '@lupinum/better-convex-functions/internal';
3
3
  import { GenericMutationCtx } from 'convex/server';
4
4
  import { GenericId } from 'convex/values';
@@ -1,4 +1,4 @@
1
- export { t as toolFailure } from './shared/better-convex-agents.Jrci7p3C.js';
1
+ export { t as toolFailure } from './shared/better-convex-agents.l5qUkNCR.js';
2
2
  import { LibraryDataModel } from '@lupinum/better-convex-functions/internal';
3
3
  import { GenericMutationCtx } from 'convex/server';
4
4
  import { GenericId } from 'convex/values';
package/dist/internal.mjs CHANGED
@@ -1,4 +1,4 @@
1
- export { c as cancelRequests, f as finish, n as nextTurn, s as shownStatus, a as stallAfter, t as toolFailure, w as wait, b as wake } from './shared/better-convex-agents.DWStY2mj.mjs';
1
+ export { c as cancelRequests, f as finish, n as nextTurn, s as shownStatus, a as stallAfter, t as toolFailure, w as wait, b as wake } from './shared/better-convex-agents.BAvd6ID4.mjs';
2
2
  import '@lupinum/better-convex-functions';
3
3
  import '@lupinum/better-convex-functions/internal';
4
4
  import 'convex/server';
package/dist/mcp.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { McpServer, createMcpHandler, buildOAuthProtectedResourceMetadata, getOAuthProtectedResourceMetadataUrl, oauthMetadataResponse, originValidationResponse, verifyBearerToken, bearerAuthChallengeResponse, requireScopes, isLegacyRequest, WebStandardStreamableHTTPServerTransport, classifyInboundRequest, isJSONRPCErrorResponse, OAuthError, OAuthErrorCode, fromJsonSchema, SERVER_INFO_META_KEY } from '@modelcontextprotocol/server';
2
- import { r as runMcpRequestDeadline, h as boundMcpResponse, p as prepareBoundedMcpRequest, m as maximumMcpRequestBytes, M as McpTransportFailure, i as mcpTransportFailureResponse, g as grantedTools, e as toolCall, t as toolFailure, j as maximumMcpResponseBytes } from './shared/better-convex-agents.DWStY2mj.mjs';
2
+ import { r as runMcpRequestDeadline, h as boundMcpResponse, p as prepareBoundedMcpRequest, m as maximumMcpRequestBytes, M as McpTransportFailure, i as mcpTransportFailureResponse, g as grantedTools, e as toolCall, t as toolFailure, j as maximumMcpResponseBytes } from './shared/better-convex-agents.BAvd6ID4.mjs';
3
3
  import { guarded, storable } from '@lupinum/better-convex-functions/internal';
4
4
  import { httpActionGeneric } from 'convex/server';
5
5
  import '@lupinum/better-convex-functions';
@@ -567,7 +567,9 @@ function responseBytes(text, output, envelope) {
567
567
  function failure(reason) {
568
568
  return {
569
569
  isError: true,
570
- content: [{ type: "text", text: reason.message }],
570
+ content: [
571
+ { type: "text", text: [reason.message, reason.why, reason.fix].filter(Boolean).join(" ") }
572
+ ],
571
573
  structuredContent: { error: reason }
572
574
  };
573
575
  }