@elytracms/studio 0.0.55 → 0.0.57

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 (55) hide show
  1. package/convex/auth.ts +152 -2
  2. package/convex/users.ts +41 -14
  3. package/dist/components/ai/ai-chat-panel-lazy.js +3 -3
  4. package/dist/components/ai/ai-chat-panel-lazy.js.map +1 -1
  5. package/dist/components/ai/ai-chat-panel.d.ts +0 -9
  6. package/dist/components/ai/ai-chat-panel.js +161 -60
  7. package/dist/components/ai/ai-chat-panel.js.map +1 -1
  8. package/dist/components/ai/chat-ui.d.ts +62 -10
  9. package/dist/components/ai/chat-ui.js +130 -23
  10. package/dist/components/ai/chat-ui.js.map +1 -1
  11. package/dist/lib/ai/anthropic-provider.d.ts +0 -12
  12. package/dist/lib/ai/anthropic-provider.js +3 -11
  13. package/dist/lib/ai/anthropic-provider.js.map +1 -1
  14. package/dist/lib/ai/chat-context.d.ts +58 -0
  15. package/dist/lib/ai/chat-context.js +71 -0
  16. package/dist/lib/ai/chat-context.js.map +1 -0
  17. package/dist/lib/ai/chat-loop.d.ts +70 -0
  18. package/dist/lib/ai/chat-loop.js +46 -0
  19. package/dist/lib/ai/chat-loop.js.map +1 -0
  20. package/dist/lib/ai/chat-state.d.ts +70 -57
  21. package/dist/lib/ai/chat-state.js +49 -90
  22. package/dist/lib/ai/chat-state.js.map +1 -1
  23. package/dist/lib/ai/fake-provider.d.ts +84 -6
  24. package/dist/lib/ai/fake-provider.js +193 -8
  25. package/dist/lib/ai/fake-provider.js.map +1 -1
  26. package/dist/lib/ai/gateway-provider.d.ts +30 -0
  27. package/dist/lib/ai/gateway-provider.js +73 -0
  28. package/dist/lib/ai/gateway-provider.js.map +1 -0
  29. package/dist/lib/ai/index.d.ts +3 -1
  30. package/dist/lib/ai/index.js +3 -1
  31. package/dist/lib/ai/index.js.map +1 -1
  32. package/dist/lib/ai/node-handler.d.ts +13 -4
  33. package/dist/lib/ai/node-handler.js +33 -3
  34. package/dist/lib/ai/node-handler.js.map +1 -1
  35. package/dist/lib/ai/route-provider.d.ts +35 -10
  36. package/dist/lib/ai/route-provider.js +13 -6
  37. package/dist/lib/ai/route-provider.js.map +1 -1
  38. package/dist/lib/ai/route.d.ts +50 -21
  39. package/dist/lib/ai/route.js +69 -40
  40. package/dist/lib/ai/route.js.map +1 -1
  41. package/dist/lib/ai/tools.d.ts +169 -39
  42. package/dist/lib/ai/tools.js +308 -62
  43. package/dist/lib/ai/tools.js.map +1 -1
  44. package/dist/lib/ai/types.d.ts +11 -16
  45. package/dist/lib/ai/types.js.map +1 -1
  46. package/dist/lib/auth/convex-auth-adapter.d.ts +37 -14
  47. package/dist/lib/auth/convex-auth-adapter.js +72 -16
  48. package/dist/lib/auth/convex-auth-adapter.js.map +1 -1
  49. package/dist/lib/i18n/messages.en.js +9 -0
  50. package/dist/lib/i18n/messages.en.js.map +1 -1
  51. package/dist/ui/badge.d.ts +1 -1
  52. package/package.json +4 -3
  53. package/dist/lib/ai/create-flow.d.ts +0 -132
  54. package/dist/lib/ai/create-flow.js +0 -280
  55. package/dist/lib/ai/create-flow.js.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/lib/ai/tools.ts"],"names":[],"mappings":"AAqDA,2FAA2F;AAC3F,MAAM,CAAC,MAAM,mBAAmB,GAAG,oBAAoB,CAAA;AAEvD;;;;GAIG;AACH,MAAM,UAAU,aAAa,CAAC,aAAgC;IAC5D,OAAO;QACL,IAAI,EAAE,QAAQ;QACd,UAAU,EAAE;YACV,MAAM,EAAE;gBACN,IAAI,EAAE,QAAQ;gBACd,IAAI,EAAE,CAAC,iBAAiB,EAAE,YAAY,EAAE,gBAAgB,EAAE,mBAAmB,EAAE,SAAS,CAAC;gBACzF,WAAW,EACT,wEAAwE;oBACxE,4EAA4E;oBAC5E,gFAAgF;oBAChF,yDAAyD;oBACzD,2CAA2C;aAC9C;YACD,UAAU,EAAE;gBACV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AC,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,CAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAA;QAClF,CAAC;QACD,KAAK,YAAY;YACf,OAAO,EAAE,MAAM,EAAE,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,CAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAA;QACtE,KAAK,gBAAgB,CAAC,CAAC,CAAC;YACtB,MAAM,UAAU,GAAG,GAAG,CAAC,YAAY,CAAC,CAAA;YACpC,IAAI,CAAC,UAAU;gBAAE,OAAO,IAAI,CAAA;YAC5B,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,CAAC,GAAG,CAAC,aAAa,CAAC,CAAC,CAAC,CAAC,EAAE,WAAW,EAAE,GAAG,CAAC,aAAa,CAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAA;QACpG,CAAC;QACD,KAAK,mBAAmB,CAAC,CAAC,CAAC;YACzB,MAAM,UAAU,GAAG,GAAG,CAAC,YAAY,CAAC,CAAA;YACpC,IAAI,CAAC,UAAU;gBAAE,OAAO,IAAI,CAAA;YAC5B,OAAO,EAAE,MAAM,EAAE,UAAU,EAAE,GAAG,CAAC,GAAG,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,KAAK,EAAE,GAAG,CAAC,OAAO,CAAE,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAA;QAClF,CAAC;QACD,KAAK,SAAS;YACZ,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,GAAG,CAAC,SAAS,CAAC,IAAI,EAAE,EAAE,CAAA;QAClD;YACE,OAAO,IAAI,CAAA;IACf,CAAC;AACH,CAAC","sourcesContent":["/**\n * The narrow tool set the creation flow's model works against (EC-199).\n *\n * Per the ratified AD, tools execute CLIENT-side against the operations layer with\n * the user's own session — this module only declares their SHAPES (the model-facing\n * planner schema) and the reader interface the studio binds to operations. The engine\n * never gains a write path: `searchDocuments` / `listAssets` are reads that gather the\n * real ids a proposal may reference (a relation id is otherwise structurally\n * impossible — see `buildTargetShape`), and `createDocument` is the terminal action\n * that runs `applyContentWithShape` and yields a reviewable proposal. `updateFields`\n * and `translate` are deliberately NOT here — they are later slices (EC-332 / post-v1).\n */\nimport type { CmsDocument, JsonSchema } from '@elytracms/core/cms-core'\n\n/** A document the model may reference as a relation target (from a `searchDocuments` read). */\nexport interface DocumentSearchResult {\n id: string\n title?: string\n}\n\n/** An asset the model may reference (from a `listAssets` read). */\nexport interface AssetSearchResult {\n id: string\n title?: string\n}\n\n/**\n * The client-side, operations-backed readers the orchestrator calls. The studio binds\n * these to the user's authenticated operations client; tests bind an in-memory fake.\n * Reads only — there is no write tool (apply is a separate, human-gated draft write).\n */\nexport interface CreateFlowTools {\n searchDocuments(input: {\n collection: string\n query?: string\n limit?: number\n }): Promise<DocumentSearchResult[]>\n listAssets(input: { query?: string; limit?: number }): Promise<AssetSearchResult[]>\n /**\n * Fetch a full document (values + localized) for the translate flow (EC-332). Optional:\n * the creation flow never needs it, so a studio that only wires create can omit it.\n */\n getDocument?(input: { collection: string; id: string }): Promise<CmsDocument | null>\n}\n\n/** One planned step the model returns — the discriminated tool/action union. */\nexport type PlannerAction =\n | { action: 'searchDocuments'; collection: string; query?: string }\n | { action: 'listAssets'; query?: string }\n | { action: 'createDocument'; collection: string; instruction?: string }\n | { action: 'translateDocument'; collection: string; query?: string }\n | { action: 'respond'; message: string }\n\n/** The schema name the planner call carries — how a FakeProvider tells plan vs. author. */\nexport const PLANNER_SCHEMA_NAME = 'create_flow_action'\n\n/**\n * The structured-output schema for ONE planning step. `action` is a closed enum and\n * `collection` is leashed to the known collection ids, so the model can neither invent\n * an action nor target a collection that does not exist.\n */\nexport function plannerSchema(collectionIds: readonly string[]): JsonSchema {\n return {\n type: 'object',\n properties: {\n action: {\n type: 'string',\n enum: ['searchDocuments', 'listAssets', 'createDocument', 'translateDocument', 'respond'],\n description:\n 'searchDocuments: find real ids for a relation target before creating. ' +\n 'listAssets: find real asset ids. createDocument: author the document once ' +\n 'you have what you need. translateDocument: fill the empty locale values of an ' +\n 'existing document (search for it first to get its id). ' +\n 'respond: reply without creating anything.',\n },\n collection: {\n type: 'string',\n ...(collectionIds.length > 0 ? { enum: [...collectionIds] } : {}),\n description: 'Target collection id (for searchDocuments / createDocument / translateDocument).',\n },\n query: {\n type: 'string',\n description: 'Optional search text (searchDocuments / listAssets / translateDocument).',\n },\n instruction: {\n type: 'string',\n description: 'What to write, refining the user request (createDocument).',\n },\n message: { type: 'string', description: 'Assistant reply text (respond).' },\n },\n required: ['action'],\n additionalProperties: false,\n }\n}\n\n/** Coerce a raw structured-output object into a {@link PlannerAction}; `null` if unusable. */\nexport function parsePlannerAction(raw: unknown): PlannerAction | null {\n if (typeof raw !== 'object' || raw === null) return null\n const value = raw as Record<string, unknown>\n const action = value.action\n const str = (k: string): string | undefined =>\n typeof value[k] === 'string' && (value[k] as string).length > 0 ? (value[k] as string) : undefined\n switch (action) {\n case 'searchDocuments': {\n const collection = str('collection')\n if (!collection) return null\n return { action, collection, ...(str('query') ? { query: str('query')! } : {}) }\n }\n case 'listAssets':\n return { action, ...(str('query') ? { query: str('query')! } : {}) }\n case 'createDocument': {\n const collection = str('collection')\n if (!collection) return null\n return { action, collection, ...(str('instruction') ? { instruction: str('instruction')! } : {}) }\n }\n case 'translateDocument': {\n const collection = str('collection')\n if (!collection) return null\n return { action, collection, ...(str('query') ? { query: str('query')! } : {}) }\n }\n case 'respond':\n return { action, message: str('message') ?? '' }\n default:\n return null\n }\n}\n"]}
1
+ {"version":3,"file":"tools.js","sourceRoot":"","sources":["../../../src/lib/ai/tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;GA0BG;AACH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE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AAM,WAAW,CAAC,MAAM,CAAC,IAA0C,CAAC,CAAA;oBAC7E,KAAK,gBAAgB;wBACnB,OAAO,MAAM,cAAc,CACzB,IAAI,CAAC,UAAU,EACf,MAAM,CAAC,IAAmD,CAC3D,CAAA;oBACH,KAAK,mBAAmB;wBACtB,OAAO,MAAM,SAAS,CACpB,IAAI,CAAC,UAAU,EACf,MAAM,CAAC,IAA2D,CACnE,CAAA;oBACH,2EAA2E;oBAC3E;wBACE,OAAO,EAAE,EAAE,EAAE,KAAK,EAAE,SAAS,EAAE,iBAAiB,IAAI,CAAC,QAAQ,IAAI,EAAE,CAAA;gBACvE,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,OAAO;oBACL,EAAE,EAAE,KAAK;oBACT,SAAS,EAAE,OAAO,IAAI,CAAC,QAAQ,iBAAiB,KAAK,YAAY,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe,EAAE;iBAC3G,CAAA;YACH,CAAC;QACH,CAAC;KACF,CAAA;AACH,CAAC","sourcesContent":["/**\n * The narrow tool set the assistant works against (EC-199, reshaped by EC-334).\n *\n * Per the ratified AD, tools execute CLIENT-side against the operations layer with\n * the user's own session. This module carries the three pieces of that contract:\n *\n * 1. {@link chatToolDefinitions} — the SDK-native tool DEFINITIONS the route's\n * chat branch declares in `streamText`, deliberately WITHOUT `execute`, so the\n * SDK forwards every call to the client (the route stays a zero-data-access\n * proxy). Plain `{ description, inputSchema }` objects with zod schemas —\n * structurally the SDK's `FunctionTool`, with no SDK import (bundle discipline).\n * 2. {@link ChatToolReaders} — the operations-backed read interface the studio\n * binds client-side (search / list / get). Reads only — the engine never gains\n * a write path; apply is a separate, human-gated draft write.\n * 3. {@link createChatToolExecutor} — the client executor map `useChat`'s\n * `onToolCall` dispatches into. Readers pass through; the terminal tools run\n * the deterministic engines (`applyContentWithShape` / `translateDocument`)\n * through the route's kept `generate` branch and return a COMPACT proposal\n * summary as the tool output — the full proposal goes to the review UI via\n * `onProposal(toolCallId, …)`, never to the model.\n *\n * EC-378 adds `updateFields` as one more definition + one more executor case —\n * the map's shape leaves that slot open.\n *\n * The EC-199 planner enum/schema (`plannerSchema` / `parsePlannerAction`) retired\n * with the hand-rolled orchestrator (EC-334 slice 2).\n */\nimport { z } from 'zod'\nimport { resolveDocumentTitle } from '@elytracms/core/cms-core'\nimport type {\n CmsDocument,\n CollectionDef,\n CollectionRegistry,\n CmsValidationIssue,\n LocaleConfig,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\nimport { applyContentWithShape } from './apply-content'\nimport { translateDocument } from './translate-document'\nimport type { ChatProposal } from './chat-state'\nimport type {\n AiProvider,\n RelationCandidate,\n RelationCandidates,\n ResolvedKnowledge,\n} from './types'\n\n/** A document the model may reference as a relation target (from a `searchDocuments` read). */\nexport interface DocumentSearchResult {\n id: string\n title?: string\n}\n\n/** An asset the model may reference (from a `listAssets` read). */\nexport interface AssetSearchResult {\n id: string\n title?: string\n}\n\n/**\n * The client-side, operations-backed readers the executor calls. The studio binds\n * these to the user's authenticated operations client; tests bind an in-memory fake.\n * Reads only — there is no write tool (apply is a separate, human-gated draft write).\n */\nexport interface ChatToolReaders {\n searchDocuments(input: {\n collection: string\n query?: string\n limit?: number\n }): Promise<DocumentSearchResult[]>\n listAssets(input: { query?: string; limit?: number }): Promise<AssetSearchResult[]>\n /**\n * Fetch a full document (values + localized) — the translate flow and the model's\n * `getDocument` tool. Optional: a studio that only wires create can omit it.\n */\n getDocument?(input: { collection: string; id: string }): Promise<CmsDocument | null>\n}\n\n/** Per-search result cap (protects the wire — results become model context). */\nexport const DEFAULT_SEARCH_LIMIT = 20\n\n// --- SDK-native chat tool definitions (EC-334) --------------------------------------\n\n/**\n * One model-facing tool definition for the route's `streamText` call. Structurally\n * the SDK's `FunctionTool` WITHOUT `execute` (execution is client-side, always) —\n * typed locally so this module needs no SDK import.\n */\nexport interface ChatToolDefinition {\n description: string\n /** Zod input schema (the AI SDK accepts zod schemas as `inputSchema` directly). */\n inputSchema: z.ZodType\n}\n\n/**\n * The tool set the native chat branch declares (EC-334). No `execute` on any entry:\n * the SDK forwards each call to the client, which executes reads against the\n * operations layer with the user's session and posts the result back; the terminal\n * tools (`createDocument` / `translateDocument`) run the deterministic engines\n * client-side and return a compact proposal summary as the tool output. The route\n * itself never executes anything.\n *\n * Collections are NOT enum-leashed here — the route has zero data access, so it has\n * no catalog; the catalog reaches the model through the request `context` (system\n * prompt), and every id a proposal references must come from a tool RESULT\n * (client-validated; `applyContentWithShape` still enum-leashes relation ids).\n */\nexport const chatToolDefinitions = {\n searchDocuments: {\n description:\n 'Search documents in a collection. Use it to find the REAL ids a relation may ' +\n 'reference, or to locate an existing document — never invent an id. Returns ' +\n '{ id, title } summaries.',\n inputSchema: z.object({\n collection: z\n .string()\n .describe('Target collection id (from the catalog in the system context).'),\n query: z.string().optional().describe('Optional search text (title match).'),\n limit: z.number().int().positive().optional().describe('Max results.'),\n }),\n },\n listAssets: {\n description:\n 'List or search assets (images, files). Use it to find REAL asset ids — never ' +\n 'invent one. Returns { id, title } summaries.',\n inputSchema: z.object({\n query: z.string().optional().describe('Optional search text.'),\n limit: z.number().int().positive().optional().describe('Max results.'),\n }),\n },\n getDocument: {\n description: 'Fetch one full document (values + localized values) by collection and id.',\n inputSchema: z.object({\n collection: z.string().describe('Collection id.'),\n id: z.string().describe('Document id (from a searchDocuments result).'),\n }),\n },\n createDocument: {\n description:\n 'Author a NEW document in a collection as a reviewable draft proposal. Terminal ' +\n 'step of a creation request — call it once you have gathered the real ids you ' +\n 'need. Returns a compact proposal summary.',\n inputSchema: z.object({\n collection: z.string().describe('Target collection id.'),\n instruction: z.string().describe('What to write, refining the user request.'),\n }),\n },\n translateDocument: {\n description:\n 'Fill the empty locale values of an EXISTING document (search for it first to ' +\n 'get its id). Returns a compact proposal summary.',\n inputSchema: z.object({\n collection: z.string().describe('Collection id.'),\n id: z.string().describe('Document id (from a searchDocuments result).'),\n locale: z.string().optional().describe('Target locale (defaults to the active one).'),\n }),\n },\n} satisfies Record<string, ChatToolDefinition>\n\n// --- Client executor map (EC-334) ----------------------------------------------------\n\n/** One forwarded tool call, as `useChat`'s `onToolCall` receives it. */\nexport interface ChatToolCall {\n toolCallId: string\n toolName: string\n input: unknown\n}\n\n/**\n * A tool execution outcome: an `output` posted back as the tool result, or an\n * `errorText` posted as an `output-error` part (the model sees the failure and\n * can react — never a thrown exception into the stream).\n */\nexport type ChatToolOutcome = { ok: true; output: unknown } | { ok: false; errorText: string }\n\n/**\n * The per-conversation relation-candidate store: every `searchDocuments` result\n * is recorded per collection, and `createDocument` may only reference the ids\n * gathered here (the `applyContentWithShape` enum leash makes a hallucinated id\n * structurally unrepresentable). Held by the panel per conversation — a new\n * conversation (EC-380 clear) starts an empty store.\n */\nexport interface ChatCandidateStore {\n record(collection: string, results: readonly DocumentSearchResult[]): void\n /** Candidates for a target collection's relation fields, keyed by field name. */\n candidatesFor(collection: CollectionDef): RelationCandidates\n}\n\nexport function createChatCandidateStore(): ChatCandidateStore {\n const searched = new Map<string, Map<string, DocumentSearchResult>>()\n return {\n record(collection, results) {\n const byId = searched.get(collection) ?? new Map<string, DocumentSearchResult>()\n for (const result of results) byId.set(result.id, result)\n searched.set(collection, byId)\n },\n candidatesFor(collection) {\n const candidates: RelationCandidates = {}\n for (const field of collection.fields) {\n if (field.type !== 'relation') continue\n const found = searched.get(field.target)\n if (!found || found.size === 0) continue\n candidates[field.name] = [...found.values()].map(\n (r): RelationCandidate => ({ id: r.id, ...(r.title ? { label: r.title } : {}) }),\n )\n }\n return candidates\n },\n }\n}\n\nexport interface ChatToolExecutorOptions {\n /** The (route) provider the terminal engines proxy their model calls through. */\n provider: AiProvider\n registry: CollectionRegistry\n /** The collections the assistant may target (unknown ids fail loud). */\n collections: readonly CollectionDef[]\n /** Operations-backed readers (client-side, user's session). */\n readers: ChatToolReaders\n /** Mint a fresh document id for a new draft (studio: the CMS store's minter). */\n mintDocumentId: (collectionId: string) => string\n /** Per-conversation relation-candidate store (see {@link createChatCandidateStore}). */\n candidates: ChatCandidateStore\n /**\n * Full proposal sink, keyed by `toolCallId` — the review UI's entry point.\n * The tool OUTPUT stays a compact summary; the patch never reaches the model.\n */\n onProposal: (toolCallId: string, proposal: ChatProposal) => void\n /** Current knowledge snapshot (thunk — the body thunk refreshes it per request). */\n knowledge?: () => ResolvedKnowledge | undefined\n /** Component manifests — context for `allow`-leashed richText/blocks fields. */\n components?: readonly ComponentManifest[]\n /** Target locale for localized fields. */\n locale?: string\n /** Locale config — required for `translateDocument`. */\n localeConfig?: LocaleConfig\n /** Injected leashes / store for `applyContentWithShape`'s validation. */\n validateRichTextEmbeds?: ValidateDocumentOptions['validateRichTextEmbeds']\n validateComposition?: ValidateDocumentOptions['validateComposition']\n store?: ValidateDocumentOptions['store']\n /** Max repair attempts inside `applyContentWithShape`. */\n maxRepairAttempts?: number\n /** Per-search result cap (default {@link DEFAULT_SEARCH_LIMIT}). */\n searchLimit?: number\n}\n\n/** The executor `useChat`'s `onToolCall` dispatches into. */\nexport interface ChatToolExecutor {\n execute(call: ChatToolCall): Promise<ChatToolOutcome>\n}\n\nfunction issueSummary(issues: readonly CmsValidationIssue[]): string {\n return issues\n .slice(0, 5)\n .map((issue) => issue.message)\n .join('; ')\n}\n\n/**\n * Build the client executor map. Every entry validates its input against\n * {@link chatToolDefinitions}' zod schema (the route validates UIMessages only\n * structurally — deep input validation is the client's), executes with the\n * user's session, and returns a JSON-safe outcome. EC-378's `updateFields`\n * lands as one more case in this dispatch.\n */\nexport function createChatToolExecutor(options: ChatToolExecutorOptions): ChatToolExecutor {\n const searchLimit = options.searchLimit ?? DEFAULT_SEARCH_LIMIT\n\n function collectionById(id: string): CollectionDef | undefined {\n return options.collections.find((c) => c.id === id)\n }\n\n async function searchDocuments(input: {\n collection: string\n query?: string\n limit?: number\n }): Promise<ChatToolOutcome> {\n if (!collectionById(input.collection)) {\n return { ok: false, errorText: `Unknown collection \"${input.collection}\" — use a collection id from the catalog.` }\n }\n const limit = Math.min(input.limit ?? searchLimit, searchLimit)\n const results = (\n await options.readers.searchDocuments({\n collection: input.collection,\n ...(input.query ? { query: input.query } : {}),\n limit,\n })\n ).slice(0, limit)\n options.candidates.record(input.collection, results)\n return { ok: true, output: results }\n }\n\n async function listAssets(input: { query?: string; limit?: number }): Promise<ChatToolOutcome> {\n const limit = Math.min(input.limit ?? searchLimit, searchLimit)\n const results = (\n await options.readers.listAssets({\n ...(input.query ? { query: input.query } : {}),\n limit,\n })\n ).slice(0, limit)\n return { ok: true, output: results }\n }\n\n async function getDocument(input: { collection: string; id: string }): Promise<ChatToolOutcome> {\n if (!options.readers.getDocument) {\n return { ok: false, errorText: 'Reading documents is not available here.' }\n }\n const document = await options.readers.getDocument(input)\n if (!document) {\n return { ok: false, errorText: `Document \"${input.collection}/${input.id}\" was not found.` }\n }\n return { ok: true, output: document }\n }\n\n async function createDocument(\n toolCallId: string,\n input: { collection: string; instruction: string },\n ): Promise<ChatToolOutcome> {\n const collection = collectionById(input.collection)\n if (!collection) {\n return { ok: false, errorText: `Unknown collection \"${input.collection}\" — use a collection id from the catalog.` }\n }\n const documentId = options.mintDocumentId(collection.id)\n const knowledge = options.knowledge?.()\n const result = await applyContentWithShape({\n provider: options.provider,\n registry: options.registry,\n collection,\n documentId,\n instruction: input.instruction,\n ...(knowledge ? { knowledge } : {}),\n ...(options.components ? { components: options.components } : {}),\n candidates: options.candidates.candidatesFor(collection),\n ...(options.locale ? { locale: options.locale } : {}),\n ...(options.validateRichTextEmbeds\n ? { validateRichTextEmbeds: options.validateRichTextEmbeds }\n : {}),\n ...(options.validateComposition ? { validateComposition: options.validateComposition } : {}),\n ...(options.store ? { store: options.store } : {}),\n ...(options.maxRepairAttempts !== undefined\n ? { maxRepairAttempts: options.maxRepairAttempts }\n : {}),\n })\n if (!result.ok) {\n return {\n ok: false,\n errorText: `The drafted ${collection.id} did not pass validation: ${issueSummary(result.issues)}`,\n }\n }\n options.onProposal(toolCallId, {\n origin: 'create',\n collection: collection.id,\n documentId,\n patch: result.patch,\n provenance: result.provenance,\n attempts: result.attempts,\n issues: result.issues,\n })\n // Compact summary only — the full patch goes to the review UI, not the model.\n return {\n ok: true,\n output: {\n status: 'proposed',\n collection: collection.id,\n documentId,\n title: resolveDocumentTitle(collection, result.patch.values, documentId),\n note: 'Draft proposal created; the editor reviews and applies it in the studio. Summarize briefly — do not repeat the content.',\n },\n }\n }\n\n async function translate(\n toolCallId: string,\n input: { collection: string; id: string; locale?: string },\n ): Promise<ChatToolOutcome> {\n const collection = collectionById(input.collection)\n if (!collection) {\n return { ok: false, errorText: `Unknown collection \"${input.collection}\" — use a collection id from the catalog.` }\n }\n if (!options.readers.getDocument || !options.localeConfig) {\n return { ok: false, errorText: 'Translation is not available here.' }\n }\n const document = await options.readers.getDocument({\n collection: input.collection,\n id: input.id,\n })\n if (!document) {\n return { ok: false, errorText: `Document \"${input.collection}/${input.id}\" was not found.` }\n }\n const knowledge = options.knowledge?.()\n const result = await translateDocument({\n provider: options.provider,\n collection,\n document,\n localeConfig: options.localeConfig,\n ...(input.locale ? { targetLocales: [input.locale] } : {}),\n ...(knowledge ? { knowledge } : {}),\n })\n if (result.total === 0) {\n return {\n ok: true,\n output: {\n status: 'nothing-to-translate',\n note: 'Every locale value is already filled — there is nothing to translate.',\n },\n }\n }\n if (result.translated === 0) {\n return { ok: false, errorText: 'The translation did not produce any content.' }\n }\n options.onProposal(toolCallId, {\n origin: 'translate',\n collection: collection.id,\n documentId: document.id,\n patch: {\n collection: collection.id,\n id: document.id,\n values: result.document.values,\n ...(result.document.localized ? { localized: result.document.localized } : {}),\n },\n provenance: result.provenance,\n attempts: 1,\n issues: [],\n before: {\n values: document.values,\n ...(document.localized ? { localized: document.localized } : {}),\n },\n })\n return {\n ok: true,\n output: {\n status: 'proposed',\n collection: collection.id,\n documentId: document.id,\n translatedUnits: result.translated,\n note: 'Translation proposal created; the editor reviews and applies it in the studio.',\n },\n }\n }\n\n return {\n async execute(call: ChatToolCall): Promise<ChatToolOutcome> {\n const definition = (chatToolDefinitions as Record<string, ChatToolDefinition>)[call.toolName]\n if (!definition) {\n return { ok: false, errorText: `Unknown tool \"${call.toolName}\".` }\n }\n const parsed = definition.inputSchema.safeParse(call.input)\n if (!parsed.success) {\n return { ok: false, errorText: `Invalid ${call.toolName} input: ${parsed.error.message}` }\n }\n try {\n switch (call.toolName) {\n case 'searchDocuments':\n return await searchDocuments(parsed.data as { collection: string; query?: string; limit?: number })\n case 'listAssets':\n return await listAssets(parsed.data as { query?: string; limit?: number })\n case 'getDocument':\n return await getDocument(parsed.data as { collection: string; id: string })\n case 'createDocument':\n return await createDocument(\n call.toolCallId,\n parsed.data as { collection: string; instruction: string },\n )\n case 'translateDocument':\n return await translate(\n call.toolCallId,\n parsed.data as { collection: string; id: string; locale?: string },\n )\n // EC-378: case 'updateFields' lands here (leashed field-update proposals).\n default:\n return { ok: false, errorText: `Unknown tool \"${call.toolName}\".` }\n }\n } catch (error) {\n return {\n ok: false,\n errorText: `The ${call.toolName} step failed: ${error instanceof Error ? error.message : 'unknown error'}`,\n }\n }\n },\n }\n}\n"]}
@@ -12,6 +12,7 @@
12
12
  */
13
13
  import type { CollectionDef, CollectionRegistry, CmsValidationIssue, FieldValues, JsonSchema, ValidateDocumentOptions } from '@elytracms/core/cms-core';
14
14
  import type { ComponentManifest } from '@elytracms/core/component-registry';
15
+ import type { LanguageModel } from 'ai';
15
16
  /**
16
17
  * The capabilities the engine requires of a provider. Both must be `true` — the
17
18
  * capability gate (`resolveAiConfig`) fails loud otherwise (tool-calling +
@@ -46,20 +47,11 @@ export interface GenerateStructuredResult {
46
47
  object: unknown;
47
48
  usage?: AiUsage;
48
49
  }
49
- /** One chat message the streaming route relays to the provider. */
50
- export interface AiChatMessage {
51
- role: 'system' | 'user' | 'assistant';
52
- content: string;
53
- }
54
- /** A streaming chat/completion request the server-route factory forwards to the provider. */
55
- export interface StreamChatRequest {
56
- system?: string;
57
- messages: AiChatMessage[];
58
- }
59
50
  /**
60
- * A provider adapter over a tool-calling, structured-output model. Anthropic in
61
- * production, {@link FakeProvider} (deterministic, keyless) in tests/playground —
62
- * both implement this identical surface so the whole loop runs without a key.
51
+ * A provider adapter over a tool-calling, structured-output model. Anthropic (or
52
+ * the Vercel AI Gateway) in production, {@link FakeProvider} (deterministic,
53
+ * keyless) in tests/playground — all implement this identical surface so the whole
54
+ * loop runs without a key.
63
55
  */
64
56
  export interface AiProvider {
65
57
  /** Stable provider id (e.g. `anthropic`, `fake`); recorded in provenance. */
@@ -71,10 +63,13 @@ export interface AiProvider {
71
63
  /** Produce a single schema-constrained structured object. */
72
64
  generateStructured(request: GenerateStructuredRequest): Promise<GenerateStructuredResult>;
73
65
  /**
74
- * Stream a chat/completion response as a Web `Response` — the server-route body.
75
- * Optional: headless callers may only use {@link generateStructured}.
66
+ * The AI-SDK `LanguageModel` behind this provider — the seam the route's native
67
+ * chat branch consumes (EC-334: `streamText` over UIMessages, tools declared
68
+ * without `execute` so they forward to the client). Optional: a pure structured
69
+ * proxy (the client-side route provider) exposes none — the route answers 501
70
+ * for chat requests then.
76
71
  */
77
- streamChat?(request: StreamChatRequest): Promise<Response>;
72
+ languageModel?(): Promise<LanguageModel>;
78
73
  }
79
74
  /** Soft, advisory limits for the route counter and the engine repair loop. */
80
75
  export interface AiLimits {
@@ -1 +1 @@
1
- {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/ai/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * `@elytracms/studio/lib/ai` — headless AI platform seam types (EC-331, phase 1).\n *\n * Pure types only: this module imports nothing at runtime (every import is\n * `import type`), so referencing `StudioAiConfig` from the studio-config type does\n * NOT pull the `ai` / `@ai-sdk/*` runtime onto the critical path. The runtime lives\n * in the sibling modules (`config`, `anthropic-provider`, `fake-provider`,\n * `knowledge`, `shape`, `apply-content`, `route`, `provenance`), reached only when\n * the `ai` block is configured and the AI subsystem actually boots. The Anthropic\n * provider additionally loads `ai`/`@ai-sdk/anthropic` via dynamic `import()`, so\n * even importing this barrel never eagerly loads the SDK.\n */\nimport type {\n CollectionDef,\n CollectionRegistry,\n CmsValidationIssue,\n FieldValues,\n JsonSchema,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\n\n// --- Provider seam ----------------------------------------------------------------\n\n/**\n * The capabilities the engine requires of a provider. Both must be `true` — the\n * capability gate (`resolveAiConfig`) fails loud otherwise (tool-calling +\n * structured output are the non-negotiable floor for schema-guaranteed authoring).\n */\nexport interface AiProviderCapabilities {\n /** The provider can call tools (function/tool calling). */\n toolCalling: boolean\n /** The provider can return schema-constrained structured output. */\n structuredOutput: boolean\n}\n\n/** A request for one schema-constrained structured object — the engine's core primitive. */\nexport interface GenerateStructuredRequest {\n /** System prompt: rules, injection stance, closed-world constraints. */\n system?: string\n /** The task prompt plus assembled context (knowledge, existing values, prior issues). */\n prompt: string\n /** The target shape as a JSON Schema (draft 2020-12 subset) the output must satisfy. */\n schema: JsonSchema\n /** A short name for the schema (some providers surface it as the tool/output name). */\n schemaName?: string\n /** A one-line description of what the schema represents. */\n schemaDescription?: string\n}\n\n/** Token usage a provider may report (best-effort; recorded for soft spend counters). */\nexport interface AiUsage {\n inputTokens?: number\n outputTokens?: number\n}\n\nexport interface GenerateStructuredResult {\n /** The structured object the provider produced (best-effort match to the request schema). */\n object: unknown\n usage?: AiUsage\n}\n\n/** One chat message the streaming route relays to the provider. */\nexport interface AiChatMessage {\n role: 'system' | 'user' | 'assistant'\n content: string\n}\n\n/** A streaming chat/completion request the server-route factory forwards to the provider. */\nexport interface StreamChatRequest {\n system?: string\n messages: AiChatMessage[]\n}\n\n/**\n * A provider adapter over a tool-calling, structured-output model. Anthropic in\n * production, {@link FakeProvider} (deterministic, keyless) in tests/playground —\n * both implement this identical surface so the whole loop runs without a key.\n */\nexport interface AiProvider {\n /** Stable provider id (e.g. `anthropic`, `fake`); recorded in provenance. */\n readonly id: string\n /** The model id the provider targets, when fixed; recorded in provenance. */\n readonly model?: string\n /** The provider's capabilities — validated by the capability gate at config load. */\n capabilities(): AiProviderCapabilities\n /** Produce a single schema-constrained structured object. */\n generateStructured(request: GenerateStructuredRequest): Promise<GenerateStructuredResult>\n /**\n * Stream a chat/completion response as a Web `Response` — the server-route body.\n * Optional: headless callers may only use {@link generateStructured}.\n */\n streamChat?(request: StreamChatRequest): Promise<Response>\n}\n\n// --- Config seam ------------------------------------------------------------------\n\n/** Soft, advisory limits for the route counter and the engine repair loop. */\nexport interface AiLimits {\n /** Soft per-project ceiling on route requests per minute (advisory; route-enforced). */\n maxRequestsPerMinute?: number\n /** Cap on repair attempts after the first generation (engine default when omitted). */\n maxRepairAttempts?: number\n}\n\n/**\n * The `ai` block of `defineStudio({ ai })` (EC-331). Studio-only live code — like\n * `fieldRenderers` / `i18n`, it never reaches the delivery bundle. The block's\n * ABSENCE means the feature is fully absent (no AI UI, no AI deps on the critical\n * path); `enabled: false` is a temporary kill-switch that keeps the config.\n */\nexport interface StudioAiConfig {\n /**\n * Temporary kill-switch. Presence of the whole `ai` block enables the feature;\n * `enabled: false` disables it without removing the config. Omitted ⇒ enabled.\n */\n enabled?: boolean\n /** The provider adapter (live code): Anthropic in production, FakeProvider in tests/playground. */\n provider: AiProvider\n /** Project knowledge sources assembled into the model's context. */\n knowledge?: KnowledgeSource[]\n /** Soft rate / repair limits. */\n limits?: AiLimits\n}\n\n// --- Knowledge seam ---------------------------------------------------------------\n\n/** An inline knowledge literal (markdown prose versioned with the repo). */\nexport interface KnowledgeItem {\n title?: string\n content: string\n}\n\n/**\n * A `fromCollection('<id>')` source: studio-editable knowledge whose *content* is\n * prose held in the DB (data), while the mechanism stays code. Resolved by a\n * caller-supplied collection reader (starter-kit / studio wires it to operations).\n */\nexport interface KnowledgeCollectionSource {\n readonly kind: 'collection'\n /** Collection id whose documents supply editable knowledge prose. */\n readonly collectionId: string\n /** Field carrying the prose; when omitted the reader picks the collection's title/first text field. */\n readonly field?: string\n}\n\n/** An async (or sync) function producing knowledge items at resolve time. */\nexport type KnowledgeFn = () =>\n | KnowledgeItem\n | KnowledgeItem[]\n | Promise<KnowledgeItem | KnowledgeItem[]>\n\n/** A knowledge source: inline literal, async function, or `fromCollection(...)` sugar. */\nexport type KnowledgeSource = KnowledgeItem | KnowledgeFn | KnowledgeCollectionSource\n\n/** The assembled knowledge context — a flat, deterministic list of resolved items. */\nexport interface ResolvedKnowledge {\n items: KnowledgeItem[]\n}\n\n/** Reads knowledge prose out of a `fromCollection` source (wired to the operations layer). */\nexport type KnowledgeCollectionReader = (\n source: KnowledgeCollectionSource,\n) => KnowledgeItem[] | Promise<KnowledgeItem[]>\n\n// --- Engine seam ------------------------------------------------------------------\n\n/**\n * A relation candidate id (from a `searchDocuments`/tool result). Relation fields may\n * ONLY use ids present here — the target shape emits them as an enum, so a\n * hallucinated id is not even representable as valid structured output.\n */\nexport interface RelationCandidate {\n id: string\n /** Human label (title) for the model to choose against. */\n label?: string\n}\n\n/** Relation candidate ids keyed by field name. A field absent here is omitted from the shape. */\nexport type RelationCandidates = Record<string, RelationCandidate[]>\n\n/** The typed draft-values patch the engine emits — applied by the draft-write path. */\nexport interface ContentPatch {\n collection: string\n id: string\n /** Non-localized field values. */\n values: FieldValues\n /** Per-locale field values (localized fields, under the target locale). */\n localized?: Record<string, FieldValues>\n}\n\n/** Origin marker the draft-write path records so an AI-authored draft is attributable. */\nexport interface AiProvenance {\n origin: 'assistant'\n /** Provider id (e.g. `anthropic`, `fake`). */\n provider: string\n /** Model id, when the provider fixes one. */\n model?: string\n /** ISO timestamp when the content was generated. */\n at: string\n}\n\nexport interface ApplyContentInput {\n provider: AiProvider\n registry: CollectionRegistry\n collection: CollectionDef\n /** Document id the patch targets (an existing doc for updates, or a fresh id for creation). */\n documentId: string\n /** The author's instruction / prompt. */\n instruction: string\n /** Assembled knowledge context (from `resolveKnowledge`). */\n knowledge?: ResolvedKnowledge\n /** Component manifests — context for `allow`-leashed richText/blocks fields. */\n components?: readonly ComponentManifest[]\n /** Relation candidate ids by field — the ONLY ids a relation field may use. */\n candidates?: RelationCandidates\n /** Existing draft values (updates): the model output merges over these before validation. */\n existing?: FieldValues\n /** Target locale for localized fields (their values land under `localized[locale]`). */\n locale?: string\n /** Injected rich-text embed leash (studio-wired); enforced when present. */\n validateRichTextEmbeds?: ValidateDocumentOptions['validateRichTextEmbeds']\n /** Injected blocks composition leash (studio-wired); enforced when present. */\n validateComposition?: ValidateDocumentOptions['validateComposition']\n /** Document store for relation/asset existence checks (optional). */\n store?: ValidateDocumentOptions['store']\n /** Max repair attempts after the first generation (default {@link DEFAULT_MAX_REPAIR_ATTEMPTS}). */\n maxRepairAttempts?: number\n}\n\n/** The engine's outcome: a valid, leash-compliant patch, or the blocking issues. */\nexport type ApplyContentResult =\n | {\n ok: true\n patch: ContentPatch\n provenance: AiProvenance\n /** Total generation attempts made (1 = happy path, >1 = repaired). */\n attempts: number\n /** Non-error issues surfaced by the accepted document (e.g. warnings). */\n issues: CmsValidationIssue[]\n }\n | {\n ok: false\n /** The error-severity issues from the final failed attempt. */\n issues: CmsValidationIssue[]\n attempts: number\n provenance: AiProvenance\n }\n\n// --- Route seam -------------------------------------------------------------------\n\n/** A validated studio session, from the host-wired `getSession`. Opaque beyond `userId`. */\nexport interface AiSession {\n /** Authenticated principal id. */\n userId: string\n [key: string]: unknown\n}\n\nexport interface AiRouteHandlerOptions {\n /** The provider (holds the host-env key). The route is a thin proxy over it. */\n provider: AiProvider\n /**\n * Server-side session check (reject anonymous callers). Returns a session for an\n * authenticated caller, `null` otherwise. Wired by the host to its own auth — the\n * route consumes it, never re-implements it.\n */\n getSession: (request: Request) => AiSession | null | Promise<AiSession | null>\n /** Soft per-project rate limit (advisory spend guard). */\n limits?: AiLimits\n /** Derive the per-project rate-bucket key from a request (default: one global bucket). */\n projectKey?: (request: Request) => string\n}\n\n/** The mounted route handler: a framework-agnostic Web `Request → Response`. */\nexport type AiRouteHandler = (request: Request) => Promise<Response>\n"]}
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/lib/ai/types.ts"],"names":[],"mappings":"","sourcesContent":["/**\n * `@elytracms/studio/lib/ai` — headless AI platform seam types (EC-331, phase 1).\n *\n * Pure types only: this module imports nothing at runtime (every import is\n * `import type`), so referencing `StudioAiConfig` from the studio-config type does\n * NOT pull the `ai` / `@ai-sdk/*` runtime onto the critical path. The runtime lives\n * in the sibling modules (`config`, `anthropic-provider`, `fake-provider`,\n * `knowledge`, `shape`, `apply-content`, `route`, `provenance`), reached only when\n * the `ai` block is configured and the AI subsystem actually boots. The Anthropic\n * provider additionally loads `ai`/`@ai-sdk/anthropic` via dynamic `import()`, so\n * even importing this barrel never eagerly loads the SDK.\n */\nimport type {\n CollectionDef,\n CollectionRegistry,\n CmsValidationIssue,\n FieldValues,\n JsonSchema,\n ValidateDocumentOptions,\n} from '@elytracms/core/cms-core'\nimport type { ComponentManifest } from '@elytracms/core/component-registry'\n// Type-only on purpose (erased at compile; `verbatimModuleSyntax`): referencing the\n// SDK's `LanguageModel` here creates NO runtime edge — pinned in `bundle.test.ts`.\nimport type { LanguageModel } from 'ai'\n\n// --- Provider seam ----------------------------------------------------------------\n\n/**\n * The capabilities the engine requires of a provider. Both must be `true` — the\n * capability gate (`resolveAiConfig`) fails loud otherwise (tool-calling +\n * structured output are the non-negotiable floor for schema-guaranteed authoring).\n */\nexport interface AiProviderCapabilities {\n /** The provider can call tools (function/tool calling). */\n toolCalling: boolean\n /** The provider can return schema-constrained structured output. */\n structuredOutput: boolean\n}\n\n/** A request for one schema-constrained structured object — the engine's core primitive. */\nexport interface GenerateStructuredRequest {\n /** System prompt: rules, injection stance, closed-world constraints. */\n system?: string\n /** The task prompt plus assembled context (knowledge, existing values, prior issues). */\n prompt: string\n /** The target shape as a JSON Schema (draft 2020-12 subset) the output must satisfy. */\n schema: JsonSchema\n /** A short name for the schema (some providers surface it as the tool/output name). */\n schemaName?: string\n /** A one-line description of what the schema represents. */\n schemaDescription?: string\n}\n\n/** Token usage a provider may report (best-effort; recorded for soft spend counters). */\nexport interface AiUsage {\n inputTokens?: number\n outputTokens?: number\n}\n\nexport interface GenerateStructuredResult {\n /** The structured object the provider produced (best-effort match to the request schema). */\n object: unknown\n usage?: AiUsage\n}\n\n/**\n * A provider adapter over a tool-calling, structured-output model. Anthropic (or\n * the Vercel AI Gateway) in production, {@link FakeProvider} (deterministic,\n * keyless) in tests/playground — all implement this identical surface so the whole\n * loop runs without a key.\n */\nexport interface AiProvider {\n /** Stable provider id (e.g. `anthropic`, `fake`); recorded in provenance. */\n readonly id: string\n /** The model id the provider targets, when fixed; recorded in provenance. */\n readonly model?: string\n /** The provider's capabilities — validated by the capability gate at config load. */\n capabilities(): AiProviderCapabilities\n /** Produce a single schema-constrained structured object. */\n generateStructured(request: GenerateStructuredRequest): Promise<GenerateStructuredResult>\n /**\n * The AI-SDK `LanguageModel` behind this provider — the seam the route's native\n * chat branch consumes (EC-334: `streamText` over UIMessages, tools declared\n * without `execute` so they forward to the client). Optional: a pure structured\n * proxy (the client-side route provider) exposes none — the route answers 501\n * for chat requests then.\n */\n languageModel?(): Promise<LanguageModel>\n}\n\n// --- Config seam ------------------------------------------------------------------\n\n/** Soft, advisory limits for the route counter and the engine repair loop. */\nexport interface AiLimits {\n /** Soft per-project ceiling on route requests per minute (advisory; route-enforced). */\n maxRequestsPerMinute?: number\n /** Cap on repair attempts after the first generation (engine default when omitted). */\n maxRepairAttempts?: number\n}\n\n/**\n * The `ai` block of `defineStudio({ ai })` (EC-331). Studio-only live code — like\n * `fieldRenderers` / `i18n`, it never reaches the delivery bundle. The block's\n * ABSENCE means the feature is fully absent (no AI UI, no AI deps on the critical\n * path); `enabled: false` is a temporary kill-switch that keeps the config.\n */\nexport interface StudioAiConfig {\n /**\n * Temporary kill-switch. Presence of the whole `ai` block enables the feature;\n * `enabled: false` disables it without removing the config. Omitted ⇒ enabled.\n */\n enabled?: boolean\n /** The provider adapter (live code): Anthropic in production, FakeProvider in tests/playground. */\n provider: AiProvider\n /** Project knowledge sources assembled into the model's context. */\n knowledge?: KnowledgeSource[]\n /** Soft rate / repair limits. */\n limits?: AiLimits\n}\n\n// --- Knowledge seam ---------------------------------------------------------------\n\n/** An inline knowledge literal (markdown prose versioned with the repo). */\nexport interface KnowledgeItem {\n title?: string\n content: string\n}\n\n/**\n * A `fromCollection('<id>')` source: studio-editable knowledge whose *content* is\n * prose held in the DB (data), while the mechanism stays code. Resolved by a\n * caller-supplied collection reader (starter-kit / studio wires it to operations).\n */\nexport interface KnowledgeCollectionSource {\n readonly kind: 'collection'\n /** Collection id whose documents supply editable knowledge prose. */\n readonly collectionId: string\n /** Field carrying the prose; when omitted the reader picks the collection's title/first text field. */\n readonly field?: string\n}\n\n/** An async (or sync) function producing knowledge items at resolve time. */\nexport type KnowledgeFn = () =>\n | KnowledgeItem\n | KnowledgeItem[]\n | Promise<KnowledgeItem | KnowledgeItem[]>\n\n/** A knowledge source: inline literal, async function, or `fromCollection(...)` sugar. */\nexport type KnowledgeSource = KnowledgeItem | KnowledgeFn | KnowledgeCollectionSource\n\n/** The assembled knowledge context — a flat, deterministic list of resolved items. */\nexport interface ResolvedKnowledge {\n items: KnowledgeItem[]\n}\n\n/** Reads knowledge prose out of a `fromCollection` source (wired to the operations layer). */\nexport type KnowledgeCollectionReader = (\n source: KnowledgeCollectionSource,\n) => KnowledgeItem[] | Promise<KnowledgeItem[]>\n\n// --- Engine seam ------------------------------------------------------------------\n\n/**\n * A relation candidate id (from a `searchDocuments`/tool result). Relation fields may\n * ONLY use ids present here — the target shape emits them as an enum, so a\n * hallucinated id is not even representable as valid structured output.\n */\nexport interface RelationCandidate {\n id: string\n /** Human label (title) for the model to choose against. */\n label?: string\n}\n\n/** Relation candidate ids keyed by field name. A field absent here is omitted from the shape. */\nexport type RelationCandidates = Record<string, RelationCandidate[]>\n\n/** The typed draft-values patch the engine emits — applied by the draft-write path. */\nexport interface ContentPatch {\n collection: string\n id: string\n /** Non-localized field values. */\n values: FieldValues\n /** Per-locale field values (localized fields, under the target locale). */\n localized?: Record<string, FieldValues>\n}\n\n/** Origin marker the draft-write path records so an AI-authored draft is attributable. */\nexport interface AiProvenance {\n origin: 'assistant'\n /** Provider id (e.g. `anthropic`, `fake`). */\n provider: string\n /** Model id, when the provider fixes one. */\n model?: string\n /** ISO timestamp when the content was generated. */\n at: string\n}\n\nexport interface ApplyContentInput {\n provider: AiProvider\n registry: CollectionRegistry\n collection: CollectionDef\n /** Document id the patch targets (an existing doc for updates, or a fresh id for creation). */\n documentId: string\n /** The author's instruction / prompt. */\n instruction: string\n /** Assembled knowledge context (from `resolveKnowledge`). */\n knowledge?: ResolvedKnowledge\n /** Component manifests — context for `allow`-leashed richText/blocks fields. */\n components?: readonly ComponentManifest[]\n /** Relation candidate ids by field — the ONLY ids a relation field may use. */\n candidates?: RelationCandidates\n /** Existing draft values (updates): the model output merges over these before validation. */\n existing?: FieldValues\n /** Target locale for localized fields (their values land under `localized[locale]`). */\n locale?: string\n /** Injected rich-text embed leash (studio-wired); enforced when present. */\n validateRichTextEmbeds?: ValidateDocumentOptions['validateRichTextEmbeds']\n /** Injected blocks composition leash (studio-wired); enforced when present. */\n validateComposition?: ValidateDocumentOptions['validateComposition']\n /** Document store for relation/asset existence checks (optional). */\n store?: ValidateDocumentOptions['store']\n /** Max repair attempts after the first generation (default {@link DEFAULT_MAX_REPAIR_ATTEMPTS}). */\n maxRepairAttempts?: number\n}\n\n/** The engine's outcome: a valid, leash-compliant patch, or the blocking issues. */\nexport type ApplyContentResult =\n | {\n ok: true\n patch: ContentPatch\n provenance: AiProvenance\n /** Total generation attempts made (1 = happy path, >1 = repaired). */\n attempts: number\n /** Non-error issues surfaced by the accepted document (e.g. warnings). */\n issues: CmsValidationIssue[]\n }\n | {\n ok: false\n /** The error-severity issues from the final failed attempt. */\n issues: CmsValidationIssue[]\n attempts: number\n provenance: AiProvenance\n }\n\n// --- Route seam -------------------------------------------------------------------\n\n/** A validated studio session, from the host-wired `getSession`. Opaque beyond `userId`. */\nexport interface AiSession {\n /** Authenticated principal id. */\n userId: string\n [key: string]: unknown\n}\n\nexport interface AiRouteHandlerOptions {\n /** The provider (holds the host-env key). The route is a thin proxy over it. */\n provider: AiProvider\n /**\n * Server-side session check (reject anonymous callers). Returns a session for an\n * authenticated caller, `null` otherwise. Wired by the host to its own auth — the\n * route consumes it, never re-implements it.\n */\n getSession: (request: Request) => AiSession | null | Promise<AiSession | null>\n /** Soft per-project rate limit (advisory spend guard). */\n limits?: AiLimits\n /** Derive the per-project rate-bucket key from a request (default: one global bucket). */\n projectKey?: (request: Request) => string\n}\n\n/** The mounted route handler: a framework-agnostic Web `Request → Response`. */\nexport type AiRouteHandler = (request: Request) => Promise<Response>\n"]}
@@ -5,11 +5,15 @@ import type { SessionStore } from './local-auth-adapter.js';
5
5
  * Classify a thrown sign-in error as a DEPLOYMENT-setup failure rather than a
6
6
  * credential problem (EC-257). Matches the Convex Auth signing-path throws:
7
7
  * `requireEnv('JWT_PRIVATE_KEY'|'JWKS'|'CONVEX_SITE_URL')` (→ "Missing environment
8
- * variable …") and `importPKCS8` on a malformed key. Deliberately narrow — a genuine
9
- * wrong-password error carries none of these tokens — and checked BEFORE the credential
10
- * regex so it always wins. Note: a PRODUCTION deployment redacts non-`ConvexError`
11
- * messages to a generic "Server Error", which this can't match; there the honest
12
- * fallback is the neutral "unavailable" branch (never "password too short").
8
+ * variable …") and `importPKCS8` on a malformed key — plus the EC-363 server code
9
+ * `deployment-misconfigured` (`defineStudioAuth` wraps those library throws in a
10
+ * `ConvexError` whose `.data` survives prod redaction, so this classifies on
11
+ * PRODUCTION deployments too once their functions are redeployed). Deliberately
12
+ * narrow — a genuine wrong-password error carries none of these tokens — and checked
13
+ * BEFORE the credential regex so it always wins. On a prod deployment whose
14
+ * functions PREDATE EC-363 the plain-`Error` message is redacted to "Server Error",
15
+ * which this can't match; there the honest fallback is the neutral "unavailable"
16
+ * branch (never "password too short").
13
17
  */
14
18
  export declare function isDeploymentMisconfigured(message: string): boolean;
15
19
  /**
@@ -25,9 +29,11 @@ export declare function isDeploymentMisconfigured(message: string): boolean;
25
29
  * (`dist/esm/browser/http_client.js`, ~L388-396 + L459-461). The server keeps
26
30
  * `errorData` for a `ConvexError` in prod while redacting `errorMessage`. So the
27
31
  * only classifiable text that survives prod is the `.data` of a `ConvexError` —
28
- * e.g. our invite gate's `ConvexError(NOT_INVITED_REASON)`. On DEV deployments
29
- * nothing is redacted, so `.message` also carries the token (the regex ladder
30
- * still matches); non-Convex errors only have a `.message`.
32
+ * our invite gate's `ConvexError(NOT_INVITED_REASON)` and, since EC-363, the
33
+ * coded `ConvexError({ code })` that `defineStudioAuth` wraps around the
34
+ * library's credential/env throws. On DEV deployments nothing is redacted, so
35
+ * `.message` also carries the token (the regex ladder still matches);
36
+ * non-Convex errors only have a `.message`.
31
37
  *
32
38
  * Duck-types the `data` property rather than `instanceof ConvexError`: two
33
39
  * copies of the `convex` module can coexist under Vite (transformed vs
@@ -39,27 +45,44 @@ type SignInFailure = Extract<SignInResult, {
39
45
  ok: false;
40
46
  }>;
41
47
  /**
42
- * Pure sign-in/sign-up error classifier (EC-257 / EC-324 / EC-362). Runs the
43
- * regex ladder over {@link convexErrorClassifierText} output (data-first).
48
+ * Pure sign-in/sign-up error classifier (EC-257 / EC-324 / EC-362 / EC-363).
49
+ * Runs the regex ladder over {@link convexErrorClassifierText} output
50
+ * (data-first).
51
+ *
52
+ * EC-363: `defineStudioAuth` now wraps `@convex-dev/auth`'s plain-`Error`
53
+ * credential/env throws server-side in a `ConvexError` carrying a stable code
54
+ * in `.data` (`{"code":"invalid-credentials" | "too-many-attempts" |
55
+ * "account-exists" | "deployment-misconfigured"}`). The data-first text folds
56
+ * that JSON in, so the SAME ladder classifies the codes (they survive prod
57
+ * redaction) AND the raw dev-shape messages — a deployment whose functions
58
+ * predate EC-363 still classifies exactly as before (dev: full message; prod:
59
+ * the honest generic below).
44
60
  *
45
61
  * Order matters: a DEPLOYMENT-misconfiguration (EC-257) and an uninvited
46
62
  * sign-up (EC-324) are each checked BEFORE the credential regex so neither
47
63
  * degrades to the lying "password too short". The final fallback is HONEST
48
64
  * ("unexpected server error — check the deployment logs"), never "unavailable":
49
- * on a prod deployment the credential/`InvalidAccountId`/env errors thrown by
50
- * `@convex-dev/auth` are PLAIN `Error`s (not `ConvexError`s), so prod redacts
51
- * them to `"Server Error"` with no `.data` and they legitimately land here.
65
+ * unknown errors — and any plain `Error` a pre-EC-363 prod deployment redacts
66
+ * to `"Server Error"` with no `.data` — legitimately land here.
52
67
  */
53
68
  export declare function classifySignInError(flow: 'signIn' | 'signUp', text: string): SignInFailure;
54
69
  type ChangePasswordFailure = Extract<ChangePasswordResult, {
55
70
  ok: false;
56
71
  }>;
57
72
  /**
58
- * Pure password-change error classifier (EC-240 H-tail / EC-362). Same
73
+ * Pure password-change error classifier (EC-240 H-tail / EC-362 / EC-377). Same
59
74
  * data-first text + honest fallback discipline as {@link classifySignInError};
60
75
  * `deployment-misconfigured` collapses onto the `unavailable` reason
61
76
  * (`ChangePasswordResult` has no dedicated reason for it) with a specific
62
77
  * remediation message.
78
+ *
79
+ * EC-377: `users:changePassword` now codes its provider throws server-side with
80
+ * the EC-363 `toCodedSignInError` wrap (`{"code":"invalid-credentials" |
81
+ * "too-many-attempts" | "deployment-misconfigured"}`) plus a coded
82
+ * `weak-password` min-length guard — the data-first text folds those in, so the
83
+ * SAME ladder classifies the codes (they survive prod redaction) AND the raw
84
+ * dev-shape messages. A deployment whose functions predate EC-377 classifies
85
+ * exactly as before (dev: full message; prod: the honest generic below).
63
86
  */
64
87
  export declare function classifyChangePasswordError(text: string): ChangePasswordFailure;
65
88
  /**
@@ -26,14 +26,18 @@ const TOKEN_STORAGE_PREFIX = 'elytra.convex-auth.jwt';
26
26
  * Classify a thrown sign-in error as a DEPLOYMENT-setup failure rather than a
27
27
  * credential problem (EC-257). Matches the Convex Auth signing-path throws:
28
28
  * `requireEnv('JWT_PRIVATE_KEY'|'JWKS'|'CONVEX_SITE_URL')` (→ "Missing environment
29
- * variable …") and `importPKCS8` on a malformed key. Deliberately narrow — a genuine
30
- * wrong-password error carries none of these tokens — and checked BEFORE the credential
31
- * regex so it always wins. Note: a PRODUCTION deployment redacts non-`ConvexError`
32
- * messages to a generic "Server Error", which this can't match; there the honest
33
- * fallback is the neutral "unavailable" branch (never "password too short").
29
+ * variable …") and `importPKCS8` on a malformed key — plus the EC-363 server code
30
+ * `deployment-misconfigured` (`defineStudioAuth` wraps those library throws in a
31
+ * `ConvexError` whose `.data` survives prod redaction, so this classifies on
32
+ * PRODUCTION deployments too once their functions are redeployed). Deliberately
33
+ * narrow — a genuine wrong-password error carries none of these tokens — and checked
34
+ * BEFORE the credential regex so it always wins. On a prod deployment whose
35
+ * functions PREDATE EC-363 the plain-`Error` message is redacted to "Server Error",
36
+ * which this can't match; there the honest fallback is the neutral "unavailable"
37
+ * branch (never "password too short").
34
38
  */
35
39
  export function isDeploymentMisconfigured(message) {
36
- return /JWT_PRIVATE_KEY|JWKS|CONVEX_SITE_URL|Missing environment variable|PKCS8|private key/i.test(message);
40
+ return /JWT_PRIVATE_KEY|JWKS|CONVEX_SITE_URL|Missing environment variable|PKCS8|private key|deployment-misconfigured/i.test(message);
37
41
  }
38
42
  /**
39
43
  * Reduce a thrown Convex error to the text used for classification (EC-362).
@@ -48,9 +52,11 @@ export function isDeploymentMisconfigured(message) {
48
52
  * (`dist/esm/browser/http_client.js`, ~L388-396 + L459-461). The server keeps
49
53
  * `errorData` for a `ConvexError` in prod while redacting `errorMessage`. So the
50
54
  * only classifiable text that survives prod is the `.data` of a `ConvexError` —
51
- * e.g. our invite gate's `ConvexError(NOT_INVITED_REASON)`. On DEV deployments
52
- * nothing is redacted, so `.message` also carries the token (the regex ladder
53
- * still matches); non-Convex errors only have a `.message`.
55
+ * our invite gate's `ConvexError(NOT_INVITED_REASON)` and, since EC-363, the
56
+ * coded `ConvexError({ code })` that `defineStudioAuth` wraps around the
57
+ * library's credential/env throws. On DEV deployments nothing is redacted, so
58
+ * `.message` also carries the token (the regex ladder still matches);
59
+ * non-Convex errors only have a `.message`.
54
60
  *
55
61
  * Duck-types the `data` property rather than `instanceof ConvexError`: two
56
62
  * copies of the `convex` module can coexist under Vite (transformed vs
@@ -82,16 +88,25 @@ export function convexErrorClassifierText(error) {
82
88
  return parts.join('\n');
83
89
  }
84
90
  /**
85
- * Pure sign-in/sign-up error classifier (EC-257 / EC-324 / EC-362). Runs the
86
- * regex ladder over {@link convexErrorClassifierText} output (data-first).
91
+ * Pure sign-in/sign-up error classifier (EC-257 / EC-324 / EC-362 / EC-363).
92
+ * Runs the regex ladder over {@link convexErrorClassifierText} output
93
+ * (data-first).
94
+ *
95
+ * EC-363: `defineStudioAuth` now wraps `@convex-dev/auth`'s plain-`Error`
96
+ * credential/env throws server-side in a `ConvexError` carrying a stable code
97
+ * in `.data` (`{"code":"invalid-credentials" | "too-many-attempts" |
98
+ * "account-exists" | "deployment-misconfigured"}`). The data-first text folds
99
+ * that JSON in, so the SAME ladder classifies the codes (they survive prod
100
+ * redaction) AND the raw dev-shape messages — a deployment whose functions
101
+ * predate EC-363 still classifies exactly as before (dev: full message; prod:
102
+ * the honest generic below).
87
103
  *
88
104
  * Order matters: a DEPLOYMENT-misconfiguration (EC-257) and an uninvited
89
105
  * sign-up (EC-324) are each checked BEFORE the credential regex so neither
90
106
  * degrades to the lying "password too short". The final fallback is HONEST
91
107
  * ("unexpected server error — check the deployment logs"), never "unavailable":
92
- * on a prod deployment the credential/`InvalidAccountId`/env errors thrown by
93
- * `@convex-dev/auth` are PLAIN `Error`s (not `ConvexError`s), so prod redacts
94
- * them to `"Server Error"` with no `.data` and they legitimately land here.
108
+ * unknown errors — and any plain `Error` a pre-EC-363 prod deployment redacts
109
+ * to `"Server Error"` with no `.data` — legitimately land here.
95
110
  */
96
111
  export function classifySignInError(flow, text) {
97
112
  // EC-257: a DEPLOYMENT-misconfiguration — its auth signing key is unset — must be
@@ -117,6 +132,20 @@ export function classifySignInError(flow, text) {
117
132
  message: 'This deployment is invite-only. Ask an admin to invite your email, then create your account.',
118
133
  };
119
134
  }
135
+ // EC-363: the sign-in rate limit. New deployments code it server-side
136
+ // (`{"code":"too-many-attempts"}` survives prod redaction); dev/old
137
+ // deployments surface the library's plain `TooManyFailedAttempts`. Checked
138
+ // BEFORE the credential regex; truthful wait-and-retry copy on the existing
139
+ // `unavailable` reason (a throttled deployment "can't sign you in right
140
+ // now" — the adapter contract gains no new reason for a transient state).
141
+ if (/too-many-attempts|TooManyFailedAttempts/i.test(text)) {
142
+ return {
143
+ ok: false,
144
+ reason: 'unavailable',
145
+ message: 'Too many failed sign-in attempts — wait a moment, then try again.',
146
+ };
147
+ }
148
+ // The EC-363 code `account-exists` matches via `exists`.
120
149
  if (flow === 'signUp' && /already|exists|InvalidAccountId/i.test(text)) {
121
150
  return {
122
151
  ok: false,
@@ -124,6 +153,7 @@ export function classifySignInError(flow, text) {
124
153
  message: 'An account with this email already exists — sign in instead.',
125
154
  };
126
155
  }
156
+ // The EC-363 code `invalid-credentials` matches via `credential`.
127
157
  if (/InvalidSecret|InvalidAccountId|credential|password/i.test(text)) {
128
158
  return {
129
159
  ok: false,
@@ -141,13 +171,23 @@ export function classifySignInError(flow, text) {
141
171
  };
142
172
  }
143
173
  /**
144
- * Pure password-change error classifier (EC-240 H-tail / EC-362). Same
174
+ * Pure password-change error classifier (EC-240 H-tail / EC-362 / EC-377). Same
145
175
  * data-first text + honest fallback discipline as {@link classifySignInError};
146
176
  * `deployment-misconfigured` collapses onto the `unavailable` reason
147
177
  * (`ChangePasswordResult` has no dedicated reason for it) with a specific
148
178
  * remediation message.
179
+ *
180
+ * EC-377: `users:changePassword` now codes its provider throws server-side with
181
+ * the EC-363 `toCodedSignInError` wrap (`{"code":"invalid-credentials" |
182
+ * "too-many-attempts" | "deployment-misconfigured"}`) plus a coded
183
+ * `weak-password` min-length guard — the data-first text folds those in, so the
184
+ * SAME ladder classifies the codes (they survive prod redaction) AND the raw
185
+ * dev-shape messages. A deployment whose functions predate EC-377 classifies
186
+ * exactly as before (dev: full message; prod: the honest generic below).
149
187
  */
150
188
  export function classifyChangePasswordError(text) {
189
+ // The EC-363/EC-377 code `deployment-misconfigured` matches via
190
+ // `isDeploymentMisconfigured` (it carries the code token).
151
191
  if (isDeploymentMisconfigured(text)) {
152
192
  return {
153
193
  ok: false,
@@ -155,13 +195,29 @@ export function classifyChangePasswordError(text) {
155
195
  message: 'This deployment can’t change your password: its auth signing key is not set. Run `npx @convex-dev/auth`.',
156
196
  };
157
197
  }
158
- if (/InvalidSecret|InvalidAccountId|current password|incorrect/i.test(text)) {
198
+ // EC-377: `retrieveAccount` rate-limits failed CURRENT-password attempts like
199
+ // sign-ins. New deployments code it (`{"code":"too-many-attempts"}` survives
200
+ // prod redaction); dev/old deployments surface the library's plain
201
+ // `TooManyFailedAttempts`. Checked BEFORE the credential regex; truthful
202
+ // wait-and-retry copy on the existing `unavailable` reason (mirrors
203
+ // `classifySignInError`, EC-363).
204
+ if (/too-many-attempts|TooManyFailedAttempts/i.test(text)) {
205
+ return {
206
+ ok: false,
207
+ reason: 'unavailable',
208
+ message: 'Too many failed attempts — wait a moment, then try again.',
209
+ };
210
+ }
211
+ // `invalid-credentials` is the EC-377 code token; the rest is the pre-EC-377
212
+ // dev-message ladder, verbatim.
213
+ if (/invalid-credentials|InvalidSecret|InvalidAccountId|current password|incorrect/i.test(text)) {
159
214
  return {
160
215
  ok: false,
161
216
  reason: 'invalid-credentials',
162
217
  message: 'Your current password is incorrect.',
163
218
  };
164
219
  }
220
+ // The EC-377 code `weak-password` matches via `weak`.
165
221
  if (/at least|too short|8 characters|password requirement|weak/i.test(text)) {
166
222
  return {
167
223
  ok: false,
@@ -1 +1 @@
1
- {"version":3,"file":"convex-auth-adapter.js","sourceRoot":"","sources":["../../../src/lib/auth/convex-auth-adapter.ts"],"names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AAE,EAAE,EAAE,IAAI,EAAE,CAAA;QACrB,CAAC;QAAC,OAAO,KAAK,EAAE,CAAC;YACf,6EAA6E;YAC7E,6EAA6E;YAC7E,mDAAmD;YACnD,OAAO,2BAA2B,CAAC,yBAAyB,CAAC,KAAK,CAAC,CAAC,CAAA;QACtE,CAAC;IACH,CAAC;IAEO,MAAM,CAAC,EAAY;QACzB,OAAO;YACL,EAAE,EAAE,EAAE,CAAC,EAAE;YACT,KAAK,EAAE,EAAE,CAAC,KAAK;YACf,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACrC,0EAA0E;YAC1E,uEAAuE;YACvE,yBAAyB;YACzB,WAAW,EAAE,EAAE;SAChB,CAAA;IACH,CAAC;IAEO,UAAU;QAChB,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QACpC,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAA;IACzB,CAAC;CACF","sourcesContent":["import type { ConvexHttpClient } from 'convex/browser'\nimport { actionRef, mutationRef, queryRef } from '../persistence/convex-client'\nimport type {\n AuthAdapter,\n AuthSession,\n ChangePasswordInput,\n ChangePasswordResult,\n SignInCredentials,\n SignInResult,\n UpdateProfileInput,\n UpdateProfileResult,\n} from './auth-adapter'\nimport type { SessionStore } from './local-auth-adapter'\n\n/**\n * Convex Auth implementation of the project-owned {@link AuthAdapter}\n * (EC-150). Decision record (also in `convex/auth.ts`): **Convex Auth** over\n * Clerk — self-contained on the Convex stack, sessions in our own tables, no\n * extra vendor; reachable only through this adapter so a swap stays local.\n *\n * Flow (server side lives in `convex/auth.ts` + `convex/users.ts`):\n * 1. `signIn` calls the `auth:signIn` action with the Password provider\n * (`flow: 'signIn'`); on success Convex returns a JWT + refresh token.\n * 2. The JWT is set on the *shared* Convex client (`client.setAuth`), so every\n * subsequent persistence query/mutation runs authenticated and the\n * server-side `requireRole` guards see the caller.\n * 3. `currentSession` restores the JWT from storage and asks `users:me`.\n * 4. `signOut` calls `auth:signOut` and clears the JWT.\n *\n * v1 scope note: the stored JWT is short-lived and this adapter does not yet\n * run the refresh-token loop (the official `@convex-dev/auth/react` client\n * does); an expired session simply resolves to \"signed out\" and the user signs\n * in again. Live-deployment hardening is EC-156. No live deployment exists in\n * this repo — this file is typecheck-verified and exercised against the local\n * adapter's shared interface.\n */\n\nconst TOKEN_STORAGE_PREFIX = 'elytra.convex-auth.jwt'\n\n/**\n * Classify a thrown sign-in error as a DEPLOYMENT-setup failure rather than a\n * credential problem (EC-257). Matches the Convex Auth signing-path throws:\n * `requireEnv('JWT_PRIVATE_KEY'|'JWKS'|'CONVEX_SITE_URL')` (→ \"Missing environment\n * variable …\") and `importPKCS8` on a malformed key. Deliberately narrow — a genuine\n * wrong-password error carries none of these tokens — and checked BEFORE the credential\n * regex so it always wins. Note: a PRODUCTION deployment redacts non-`ConvexError`\n * messages to a generic \"Server Error\", which this can't match; there the honest\n * fallback is the neutral \"unavailable\" branch (never \"password too short\").\n */\nexport function isDeploymentMisconfigured(message: string): boolean {\n return /JWT_PRIVATE_KEY|JWKS|CONVEX_SITE_URL|Missing environment variable|PKCS8|private key/i.test(\n message,\n )\n}\n\n/**\n * Reduce a thrown Convex error to the text used for classification (EC-362).\n *\n * **Read `.data` FIRST, then `.message`** — because a PRODUCTION Convex\n * deployment REDACTS a UDF's thrown-error `.message` to a generic\n * `\"[Request ID: …] Server Error\"`, but a `ConvexError`'s `.data` payload\n * survives to the client. Proven in the installed `convex@1.42.1` browser\n * client: on an `\"error\"` response `ConvexHttpClient.action` throws\n * `forwardErrorData(respJSON.errorData, new ConvexError(respJSON.errorMessage))`,\n * and `forwardErrorData` sets `error.data = jsonToConvex(errorData)`\n * (`dist/esm/browser/http_client.js`, ~L388-396 + L459-461). The server keeps\n * `errorData` for a `ConvexError` in prod while redacting `errorMessage`. So the\n * only classifiable text that survives prod is the `.data` of a `ConvexError` —\n * e.g. our invite gate's `ConvexError(NOT_INVITED_REASON)`. On DEV deployments\n * nothing is redacted, so `.message` also carries the token (the regex ladder\n * still matches); non-Convex errors only have a `.message`.\n *\n * Duck-types the `data` property rather than `instanceof ConvexError`: two\n * copies of the `convex` module can coexist under Vite (transformed vs\n * pre-bundled), so `instanceof` can spuriously fail (EC-357). `.data` may be a\n * string (our gates) or a structured object (future gates) — both are folded in.\n */\nexport function convexErrorClassifierText(error: unknown): string {\n const parts: string[] = []\n if (typeof error === 'object' && error !== null && 'data' in error) {\n const data = (error as { data: unknown }).data\n if (typeof data === 'string') {\n parts.push(data)\n } else if (data !== null && data !== undefined) {\n try {\n parts.push(JSON.stringify(data))\n } catch {\n // Non-serializable data (cycles) — ignore; fall back to the message.\n }\n }\n }\n if (error instanceof Error) parts.push(error.message)\n else if (typeof error === 'string') parts.push(error)\n if (parts.length === 0) parts.push(String(error))\n return parts.join('\\n')\n}\n\ntype SignInFailure = Extract<SignInResult, { ok: false }>\n\n/**\n * Pure sign-in/sign-up error classifier (EC-257 / EC-324 / EC-362). Runs the\n * regex ladder over {@link convexErrorClassifierText} output (data-first).\n *\n * Order matters: a DEPLOYMENT-misconfiguration (EC-257) and an uninvited\n * sign-up (EC-324) are each checked BEFORE the credential regex so neither\n * degrades to the lying \"password too short\". The final fallback is HONEST\n * (\"unexpected server error — check the deployment logs\"), never \"unavailable\":\n * on a prod deployment the credential/`InvalidAccountId`/env errors thrown by\n * `@convex-dev/auth` are PLAIN `Error`s (not `ConvexError`s), so prod redacts\n * them to `\"Server Error\"` with no `.data` and they legitimately land here.\n */\nexport function classifySignInError(flow: 'signIn' | 'signUp', text: string): SignInFailure {\n // EC-257: a DEPLOYMENT-misconfiguration — its auth signing key is unset — must be\n // classified FIRST so it never falls through to the lying \"password too short\".\n // Convex Auth signs the session JWT with the deployment's `JWT_PRIVATE_KEY`\n // (+ `JWKS`/`CONVEX_SITE_URL`); when any is unset (`npx @convex-dev/auth` never\n // run) the `requireEnv`/`importPKCS8` call throws AFTER the password is validated,\n // so EVERY sign-in fails regardless of the password.\n if (isDeploymentMisconfigured(text)) {\n return {\n ok: false,\n reason: 'deployment-misconfigured',\n message:\n 'This deployment can’t sign you in: its auth signing key is not set. Run `npx @convex-dev/auth` against this deployment, then retry. (The deployment-setup check reports the same.)',\n }\n }\n // EC-324: an uninvited sign-up is rejected server-side (`gateAccountCreation`/\n // `gateSessionCreation` throw `ConvexError(NOT_INVITED_REASON)`, whose `.data`\n // survives to the client even in production). Checked BEFORE the credential regex.\n if (/not-invited|invite-only|invite only/i.test(text)) {\n return {\n ok: false,\n reason: 'not-invited',\n message:\n 'This deployment is invite-only. Ask an admin to invite your email, then create your account.',\n }\n }\n if (flow === 'signUp' && /already|exists|InvalidAccountId/i.test(text)) {\n return {\n ok: false,\n reason: 'account-exists',\n message: 'An account with this email already exists — sign in instead.',\n }\n }\n if (/InvalidSecret|InvalidAccountId|credential|password/i.test(text)) {\n return {\n ok: false,\n reason: 'invalid-credentials',\n message:\n flow === 'signUp'\n ? 'That email or password can’t be used (password too short?).'\n : 'Email or password is incorrect.',\n }\n }\n const verb = flow === 'signUp' ? 'Sign-up' : 'Sign-in'\n return {\n ok: false,\n reason: 'unavailable',\n message: `${verb} failed (unexpected server error) — check the deployment logs.`,\n }\n}\n\ntype ChangePasswordFailure = Extract<ChangePasswordResult, { ok: false }>\n\n/**\n * Pure password-change error classifier (EC-240 H-tail / EC-362). Same\n * data-first text + honest fallback discipline as {@link classifySignInError};\n * `deployment-misconfigured` collapses onto the `unavailable` reason\n * (`ChangePasswordResult` has no dedicated reason for it) with a specific\n * remediation message.\n */\nexport function classifyChangePasswordError(text: string): ChangePasswordFailure {\n if (isDeploymentMisconfigured(text)) {\n return {\n ok: false,\n reason: 'unavailable',\n message:\n 'This deployment can’t change your password: its auth signing key is not set. Run `npx @convex-dev/auth`.',\n }\n }\n if (/InvalidSecret|InvalidAccountId|current password|incorrect/i.test(text)) {\n return {\n ok: false,\n reason: 'invalid-credentials',\n message: 'Your current password is incorrect.',\n }\n }\n if (/at least|too short|8 characters|password requirement|weak/i.test(text)) {\n return {\n ok: false,\n reason: 'weak-password',\n message: 'Choose a stronger password (at least 8 characters).',\n }\n }\n return {\n ok: false,\n reason: 'unavailable',\n message: 'Password change failed (unexpected server error) — check the deployment logs.',\n }\n}\n\n/**\n * Per-deployment token key (EC-179, vision AD-8). One project per backend, so a\n * session is scoped to its deployment: signing into Aurora's backend must not\n * carry a JWT to Northwind's. Keying the stored token by the deployment URL\n * makes each backend's session independent — switching to a project on a\n * not-yet-authenticated backend reads no token and the guard asks for sign-in.\n * (A future shared external IdP — WorkOS/Clerk — would issue one identity valid\n * on every deployment, collapsing this back to a single session.)\n */\nexport function tokenStorageKey(deploymentUrl?: string): string {\n return deploymentUrl ? `${TOKEN_STORAGE_PREFIX}::${deploymentUrl}` : TOKEN_STORAGE_PREFIX\n}\n\n/**\n * Best-effort \"is there a session for this deployment?\" — a synchronous token\n * presence check used to label per-backend projects in the switcher/launcher\n * (EC-179). It does not validate the token (an expired one still redirects to\n * sign-in on entry); it just answers \"has the user signed into this backend?\".\n */\nexport function hasStoredConvexSession(\n deploymentUrl: string,\n store: SessionStore = defaultStore(),\n): boolean {\n return store.getItem(tokenStorageKey(deploymentUrl)) !== null\n}\n\ninterface SignInActionResult {\n tokens?: { token: string; refreshToken: string } | null\n}\n\ninterface MeResult {\n id: string\n email: string\n name?: string\n}\n\nfunction defaultStore(): SessionStore {\n if (typeof window !== 'undefined' && window.sessionStorage) return window.sessionStorage\n const memory = new Map<string, string>()\n return {\n getItem: (key) => memory.get(key) ?? null,\n setItem: (key, value) => void memory.set(key, value),\n removeItem: (key) => void memory.delete(key),\n }\n}\n\nexport class ConvexAuthAdapter implements AuthAdapter {\n private readonly tokenKey: string\n\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly store: SessionStore = defaultStore(),\n /** Deployment URL the token is scoped to (per-backend sessions, EC-179). */\n deploymentUrl?: string,\n ) {\n this.tokenKey = tokenStorageKey(deploymentUrl)\n }\n\n async currentSession(): Promise<AuthSession | null> {\n const token = this.store.getItem(this.tokenKey)\n if (!token) return null\n this.client.setAuth(token)\n try {\n const me = (await this.client.query(queryRef('users:me'), {})) as MeResult | null\n if (!me) {\n this.clearToken()\n return null\n }\n return { user: this.toUser(me) }\n } catch {\n // Expired/invalid JWT or unreachable backend → treat as signed out.\n this.clearToken()\n return null\n }\n }\n\n async signIn(credentials: SignInCredentials): Promise<SignInResult> {\n return this.authenticate('signIn', credentials)\n }\n\n async signUp(credentials: SignInCredentials): Promise<SignInResult> {\n return this.authenticate('signUp', credentials)\n }\n\n /**\n * Shared password flow (EC-150/EC-179). `signIn` and `signUp` differ only by\n * the Convex Auth `flow` param; both return a token + load `users:me`.\n */\n private async authenticate(\n flow: 'signIn' | 'signUp',\n credentials: SignInCredentials,\n ): Promise<SignInResult> {\n let result: SignInActionResult\n try {\n result = (await this.client.action(actionRef('auth:signIn'), {\n provider: 'password',\n params: {\n email: credentials.email.trim().toLowerCase(),\n password: credentials.password,\n flow,\n },\n })) as SignInActionResult\n } catch (error) {\n // Convex Auth surfaces credential/registration problems as thrown errors.\n // Classify from the DATA-FIRST text (a `ConvexError`'s `.data` survives prod\n // redaction, the redacted `.message` does not — EC-362), then apply the pure\n // regex ladder. See `convexErrorClassifierText` / `classifySignInError`.\n return classifySignInError(flow, convexErrorClassifierText(error))\n }\n if (!result.tokens) {\n return {\n ok: false,\n reason: 'invalid-credentials',\n message: 'Email or password is incorrect.',\n }\n }\n this.store.setItem(this.tokenKey, result.tokens.token)\n this.client.setAuth(result.tokens.token)\n const me = (await this.client.query(queryRef('users:me'), {})) as MeResult | null\n if (!me) {\n this.clearToken()\n return { ok: false, reason: 'unavailable', message: 'Sign-in is currently unavailable.' }\n }\n return { ok: true, session: { user: this.toUser(me) } }\n }\n\n async signOut(): Promise<void> {\n try {\n await this.client.action(actionRef('auth:signOut'), {})\n } catch {\n // Already signed out / unreachable — clearing local state is what matters.\n }\n this.clearToken()\n }\n\n /**\n * Self-service identity edit (EC-240 H-tail item 2). Patches the caller's OWN\n * auth `users` row (name / avatar) via the self-scoped `users:updateProfile`\n * mutation, then re-reads `users:me` so the returned session carries the new\n * name. Auth-owned fields never flow through the members-rail `users.save`.\n */\n async updateProfile(input: UpdateProfileInput): Promise<UpdateProfileResult> {\n const token = this.store.getItem(this.tokenKey)\n if (!token) {\n return { ok: false, reason: 'not-authenticated', message: 'You are not signed in.' }\n }\n this.client.setAuth(token)\n try {\n await this.client.mutation(mutationRef('users:updateProfile'), {\n ...(input.name !== undefined ? { name: input.name } : {}),\n ...(input.avatar !== undefined ? { avatar: input.avatar } : {}),\n })\n const me = (await this.client.query(queryRef('users:me'), {})) as MeResult | null\n if (!me) {\n return { ok: false, reason: 'unavailable', message: 'Profile update is currently unavailable.' }\n }\n return { ok: true, session: { user: this.toUser(me) } }\n } catch {\n return { ok: false, reason: 'unavailable', message: 'Profile update is currently unavailable.' }\n }\n }\n\n /**\n * Self-service password change (EC-240 H-tail item 3). Delegates entirely to\n * the provider via the self-scoped `users:changePassword` ACTION (which calls\n * Convex Auth's `retrieveAccount` to verify the current password, then\n * `modifyAccountCredentials` to set the new one). **Seam only:** the raw\n * password values are forwarded to the provider and NEVER logged or inspected\n * here.\n */\n async changePassword(input: ChangePasswordInput): Promise<ChangePasswordResult> {\n const token = this.store.getItem(this.tokenKey)\n if (!token) {\n return { ok: false, reason: 'not-authenticated', message: 'You are not signed in.' }\n }\n this.client.setAuth(token)\n try {\n await this.client.action(actionRef('users:changePassword'), {\n currentPassword: input.currentPassword,\n newPassword: input.newPassword,\n })\n return { ok: true }\n } catch (error) {\n // Data-first classification (EC-362): the change-password ACTION runs on the\n // same deployment, so a prod redaction erases the thrown `.message` the same\n // way — read a surviving `ConvexError.data` first.\n return classifyChangePasswordError(convexErrorClassifierText(error))\n }\n }\n\n private toUser(me: MeResult): AuthSession['user'] {\n return {\n id: me.id,\n email: me.email,\n ...(me.name ? { name: me.name } : {}),\n // No global flags: project creation is config/CLI-owned (AD-11), so there\n // is no in-studio `create-projects` capability. Per-project roles come\n // from `projectMembers`.\n globalFlags: [],\n }\n }\n\n private clearToken(): void {\n this.store.removeItem(this.tokenKey)\n this.client.clearAuth()\n }\n}\n"]}
1
+ {"version":3,"file":"convex-auth-adapter.js","sourceRoot":"","sources":["../../../src/lib/auth/convex-auth-adapter.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,SAAS,EAAE,WAAW,EAAE,QAAQ,EAAE,MAAM,8BAA8B,CAAA;AAa/E;;;;;;;;;;;;;;;;;;;;;GAqBG;AAEH,MAAM,oBAAoB,GAAG,wBAAwB,CAAA;AAErD;;;;;;;;;;;;;GAaG;AACH,MAAM,UAAU,yBAAyB,CAAC,OAAe;IACvD,OAAO,+GAA+G,CAAC,IAAI,CACzH,OAAO,CACR,CAAA;AACH,CAAC;AAED;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,MAAM,UAAU,yBAAyB,CAAC,KAAc;IACtD,MAAM,KAAK,GAAa,EAAE,CAAA;IAC1B,IAAI,OAAO,KAAK,KAAK,QAAQ,IAAI,KAAK,KAAK,IAAI,IAAI,MAAM,IAAI,KAAK,EAAE,CAAC;QACnE,MAAM,IAAI,GAAI,KAA2B,CAAC,IAAI,CAAA;QAC9C,IAAI,OAAO,IAAI,KAAK,QAAQ,EAAE,CAAC;YAC7B,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,CAAA;QAClB,CAAC;aAAM,IAAI,IAAI,KAAK,IAAI,IAAI,IAAI,KAAK,SAAS,EAAE,CAAC;YAC/C,IAAI,CAAC;gBACH,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAA;YAClC,CAAC;YAAC,MAAM,CAAC;gBACP,qEAAqE;YACvE,CAAC;QACH,CAAC;IACH,CAAC;IACD,IAAI,KAAK,YAAY,KAAK;QAAE,KAAK,CAAC,IA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AC,KAAK;YACf,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,CAAC,EAAE,IAAI,EAAE,EAAE,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;YACrC,0EAA0E;YAC1E,uEAAuE;YACvE,yBAAyB;YACzB,WAAW,EAAE,EAAE;SAChB,CAAA;IACH,CAAC;IAEO,UAAU;QAChB,IAAI,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAA;QACpC,IAAI,CAAC,MAAM,CAAC,SAAS,EAAE,CAAA;IACzB,CAAC;CACF","sourcesContent":["import type { ConvexHttpClient } from 'convex/browser'\nimport { actionRef, mutationRef, queryRef } from '../persistence/convex-client'\nimport type {\n AuthAdapter,\n AuthSession,\n ChangePasswordInput,\n ChangePasswordResult,\n SignInCredentials,\n SignInResult,\n UpdateProfileInput,\n UpdateProfileResult,\n} from './auth-adapter'\nimport type { SessionStore } from './local-auth-adapter'\n\n/**\n * Convex Auth implementation of the project-owned {@link AuthAdapter}\n * (EC-150). Decision record (also in `convex/auth.ts`): **Convex Auth** over\n * Clerk — self-contained on the Convex stack, sessions in our own tables, no\n * extra vendor; reachable only through this adapter so a swap stays local.\n *\n * Flow (server side lives in `convex/auth.ts` + `convex/users.ts`):\n * 1. `signIn` calls the `auth:signIn` action with the Password provider\n * (`flow: 'signIn'`); on success Convex returns a JWT + refresh token.\n * 2. The JWT is set on the *shared* Convex client (`client.setAuth`), so every\n * subsequent persistence query/mutation runs authenticated and the\n * server-side `requireRole` guards see the caller.\n * 3. `currentSession` restores the JWT from storage and asks `users:me`.\n * 4. `signOut` calls `auth:signOut` and clears the JWT.\n *\n * v1 scope note: the stored JWT is short-lived and this adapter does not yet\n * run the refresh-token loop (the official `@convex-dev/auth/react` client\n * does); an expired session simply resolves to \"signed out\" and the user signs\n * in again. Live-deployment hardening is EC-156. No live deployment exists in\n * this repo — this file is typecheck-verified and exercised against the local\n * adapter's shared interface.\n */\n\nconst TOKEN_STORAGE_PREFIX = 'elytra.convex-auth.jwt'\n\n/**\n * Classify a thrown sign-in error as a DEPLOYMENT-setup failure rather than a\n * credential problem (EC-257). Matches the Convex Auth signing-path throws:\n * `requireEnv('JWT_PRIVATE_KEY'|'JWKS'|'CONVEX_SITE_URL')` (→ \"Missing environment\n * variable …\") and `importPKCS8` on a malformed key — plus the EC-363 server code\n * `deployment-misconfigured` (`defineStudioAuth` wraps those library throws in a\n * `ConvexError` whose `.data` survives prod redaction, so this classifies on\n * PRODUCTION deployments too once their functions are redeployed). Deliberately\n * narrow — a genuine wrong-password error carries none of these tokens — and checked\n * BEFORE the credential regex so it always wins. On a prod deployment whose\n * functions PREDATE EC-363 the plain-`Error` message is redacted to \"Server Error\",\n * which this can't match; there the honest fallback is the neutral \"unavailable\"\n * branch (never \"password too short\").\n */\nexport function isDeploymentMisconfigured(message: string): boolean {\n return /JWT_PRIVATE_KEY|JWKS|CONVEX_SITE_URL|Missing environment variable|PKCS8|private key|deployment-misconfigured/i.test(\n message,\n )\n}\n\n/**\n * Reduce a thrown Convex error to the text used for classification (EC-362).\n *\n * **Read `.data` FIRST, then `.message`** — because a PRODUCTION Convex\n * deployment REDACTS a UDF's thrown-error `.message` to a generic\n * `\"[Request ID: …] Server Error\"`, but a `ConvexError`'s `.data` payload\n * survives to the client. Proven in the installed `convex@1.42.1` browser\n * client: on an `\"error\"` response `ConvexHttpClient.action` throws\n * `forwardErrorData(respJSON.errorData, new ConvexError(respJSON.errorMessage))`,\n * and `forwardErrorData` sets `error.data = jsonToConvex(errorData)`\n * (`dist/esm/browser/http_client.js`, ~L388-396 + L459-461). The server keeps\n * `errorData` for a `ConvexError` in prod while redacting `errorMessage`. So the\n * only classifiable text that survives prod is the `.data` of a `ConvexError` —\n * our invite gate's `ConvexError(NOT_INVITED_REASON)` and, since EC-363, the\n * coded `ConvexError({ code })` that `defineStudioAuth` wraps around the\n * library's credential/env throws. On DEV deployments nothing is redacted, so\n * `.message` also carries the token (the regex ladder still matches);\n * non-Convex errors only have a `.message`.\n *\n * Duck-types the `data` property rather than `instanceof ConvexError`: two\n * copies of the `convex` module can coexist under Vite (transformed vs\n * pre-bundled), so `instanceof` can spuriously fail (EC-357). `.data` may be a\n * string (our gates) or a structured object (future gates) — both are folded in.\n */\nexport function convexErrorClassifierText(error: unknown): string {\n const parts: string[] = []\n if (typeof error === 'object' && error !== null && 'data' in error) {\n const data = (error as { data: unknown }).data\n if (typeof data === 'string') {\n parts.push(data)\n } else if (data !== null && data !== undefined) {\n try {\n parts.push(JSON.stringify(data))\n } catch {\n // Non-serializable data (cycles) — ignore; fall back to the message.\n }\n }\n }\n if (error instanceof Error) parts.push(error.message)\n else if (typeof error === 'string') parts.push(error)\n if (parts.length === 0) parts.push(String(error))\n return parts.join('\\n')\n}\n\ntype SignInFailure = Extract<SignInResult, { ok: false }>\n\n/**\n * Pure sign-in/sign-up error classifier (EC-257 / EC-324 / EC-362 / EC-363).\n * Runs the regex ladder over {@link convexErrorClassifierText} output\n * (data-first).\n *\n * EC-363: `defineStudioAuth` now wraps `@convex-dev/auth`'s plain-`Error`\n * credential/env throws server-side in a `ConvexError` carrying a stable code\n * in `.data` (`{\"code\":\"invalid-credentials\" | \"too-many-attempts\" |\n * \"account-exists\" | \"deployment-misconfigured\"}`). The data-first text folds\n * that JSON in, so the SAME ladder classifies the codes (they survive prod\n * redaction) AND the raw dev-shape messages — a deployment whose functions\n * predate EC-363 still classifies exactly as before (dev: full message; prod:\n * the honest generic below).\n *\n * Order matters: a DEPLOYMENT-misconfiguration (EC-257) and an uninvited\n * sign-up (EC-324) are each checked BEFORE the credential regex so neither\n * degrades to the lying \"password too short\". The final fallback is HONEST\n * (\"unexpected server error — check the deployment logs\"), never \"unavailable\":\n * unknown errors — and any plain `Error` a pre-EC-363 prod deployment redacts\n * to `\"Server Error\"` with no `.data` — legitimately land here.\n */\nexport function classifySignInError(flow: 'signIn' | 'signUp', text: string): SignInFailure {\n // EC-257: a DEPLOYMENT-misconfiguration — its auth signing key is unset — must be\n // classified FIRST so it never falls through to the lying \"password too short\".\n // Convex Auth signs the session JWT with the deployment's `JWT_PRIVATE_KEY`\n // (+ `JWKS`/`CONVEX_SITE_URL`); when any is unset (`npx @convex-dev/auth` never\n // run) the `requireEnv`/`importPKCS8` call throws AFTER the password is validated,\n // so EVERY sign-in fails regardless of the password.\n if (isDeploymentMisconfigured(text)) {\n return {\n ok: false,\n reason: 'deployment-misconfigured',\n message:\n 'This deployment can’t sign you in: its auth signing key is not set. Run `npx @convex-dev/auth` against this deployment, then retry. (The deployment-setup check reports the same.)',\n }\n }\n // EC-324: an uninvited sign-up is rejected server-side (`gateAccountCreation`/\n // `gateSessionCreation` throw `ConvexError(NOT_INVITED_REASON)`, whose `.data`\n // survives to the client even in production). Checked BEFORE the credential regex.\n if (/not-invited|invite-only|invite only/i.test(text)) {\n return {\n ok: false,\n reason: 'not-invited',\n message:\n 'This deployment is invite-only. Ask an admin to invite your email, then create your account.',\n }\n }\n // EC-363: the sign-in rate limit. New deployments code it server-side\n // (`{\"code\":\"too-many-attempts\"}` survives prod redaction); dev/old\n // deployments surface the library's plain `TooManyFailedAttempts`. Checked\n // BEFORE the credential regex; truthful wait-and-retry copy on the existing\n // `unavailable` reason (a throttled deployment \"can't sign you in right\n // now\" — the adapter contract gains no new reason for a transient state).\n if (/too-many-attempts|TooManyFailedAttempts/i.test(text)) {\n return {\n ok: false,\n reason: 'unavailable',\n message: 'Too many failed sign-in attempts — wait a moment, then try again.',\n }\n }\n // The EC-363 code `account-exists` matches via `exists`.\n if (flow === 'signUp' && /already|exists|InvalidAccountId/i.test(text)) {\n return {\n ok: false,\n reason: 'account-exists',\n message: 'An account with this email already exists — sign in instead.',\n }\n }\n // The EC-363 code `invalid-credentials` matches via `credential`.\n if (/InvalidSecret|InvalidAccountId|credential|password/i.test(text)) {\n return {\n ok: false,\n reason: 'invalid-credentials',\n message:\n flow === 'signUp'\n ? 'That email or password can’t be used (password too short?).'\n : 'Email or password is incorrect.',\n }\n }\n const verb = flow === 'signUp' ? 'Sign-up' : 'Sign-in'\n return {\n ok: false,\n reason: 'unavailable',\n message: `${verb} failed (unexpected server error) — check the deployment logs.`,\n }\n}\n\ntype ChangePasswordFailure = Extract<ChangePasswordResult, { ok: false }>\n\n/**\n * Pure password-change error classifier (EC-240 H-tail / EC-362 / EC-377). Same\n * data-first text + honest fallback discipline as {@link classifySignInError};\n * `deployment-misconfigured` collapses onto the `unavailable` reason\n * (`ChangePasswordResult` has no dedicated reason for it) with a specific\n * remediation message.\n *\n * EC-377: `users:changePassword` now codes its provider throws server-side with\n * the EC-363 `toCodedSignInError` wrap (`{\"code\":\"invalid-credentials\" |\n * \"too-many-attempts\" | \"deployment-misconfigured\"}`) plus a coded\n * `weak-password` min-length guard — the data-first text folds those in, so the\n * SAME ladder classifies the codes (they survive prod redaction) AND the raw\n * dev-shape messages. A deployment whose functions predate EC-377 classifies\n * exactly as before (dev: full message; prod: the honest generic below).\n */\nexport function classifyChangePasswordError(text: string): ChangePasswordFailure {\n // The EC-363/EC-377 code `deployment-misconfigured` matches via\n // `isDeploymentMisconfigured` (it carries the code token).\n if (isDeploymentMisconfigured(text)) {\n return {\n ok: false,\n reason: 'unavailable',\n message:\n 'This deployment can’t change your password: its auth signing key is not set. Run `npx @convex-dev/auth`.',\n }\n }\n // EC-377: `retrieveAccount` rate-limits failed CURRENT-password attempts like\n // sign-ins. New deployments code it (`{\"code\":\"too-many-attempts\"}` survives\n // prod redaction); dev/old deployments surface the library's plain\n // `TooManyFailedAttempts`. Checked BEFORE the credential regex; truthful\n // wait-and-retry copy on the existing `unavailable` reason (mirrors\n // `classifySignInError`, EC-363).\n if (/too-many-attempts|TooManyFailedAttempts/i.test(text)) {\n return {\n ok: false,\n reason: 'unavailable',\n message: 'Too many failed attempts — wait a moment, then try again.',\n }\n }\n // `invalid-credentials` is the EC-377 code token; the rest is the pre-EC-377\n // dev-message ladder, verbatim.\n if (/invalid-credentials|InvalidSecret|InvalidAccountId|current password|incorrect/i.test(text)) {\n return {\n ok: false,\n reason: 'invalid-credentials',\n message: 'Your current password is incorrect.',\n }\n }\n // The EC-377 code `weak-password` matches via `weak`.\n if (/at least|too short|8 characters|password requirement|weak/i.test(text)) {\n return {\n ok: false,\n reason: 'weak-password',\n message: 'Choose a stronger password (at least 8 characters).',\n }\n }\n return {\n ok: false,\n reason: 'unavailable',\n message: 'Password change failed (unexpected server error) — check the deployment logs.',\n }\n}\n\n/**\n * Per-deployment token key (EC-179, vision AD-8). One project per backend, so a\n * session is scoped to its deployment: signing into Aurora's backend must not\n * carry a JWT to Northwind's. Keying the stored token by the deployment URL\n * makes each backend's session independent — switching to a project on a\n * not-yet-authenticated backend reads no token and the guard asks for sign-in.\n * (A future shared external IdP — WorkOS/Clerk — would issue one identity valid\n * on every deployment, collapsing this back to a single session.)\n */\nexport function tokenStorageKey(deploymentUrl?: string): string {\n return deploymentUrl ? `${TOKEN_STORAGE_PREFIX}::${deploymentUrl}` : TOKEN_STORAGE_PREFIX\n}\n\n/**\n * Best-effort \"is there a session for this deployment?\" — a synchronous token\n * presence check used to label per-backend projects in the switcher/launcher\n * (EC-179). It does not validate the token (an expired one still redirects to\n * sign-in on entry); it just answers \"has the user signed into this backend?\".\n */\nexport function hasStoredConvexSession(\n deploymentUrl: string,\n store: SessionStore = defaultStore(),\n): boolean {\n return store.getItem(tokenStorageKey(deploymentUrl)) !== null\n}\n\ninterface SignInActionResult {\n tokens?: { token: string; refreshToken: string } | null\n}\n\ninterface MeResult {\n id: string\n email: string\n name?: string\n}\n\nfunction defaultStore(): SessionStore {\n if (typeof window !== 'undefined' && window.sessionStorage) return window.sessionStorage\n const memory = new Map<string, string>()\n return {\n getItem: (key) => memory.get(key) ?? null,\n setItem: (key, value) => void memory.set(key, value),\n removeItem: (key) => void memory.delete(key),\n }\n}\n\nexport class ConvexAuthAdapter implements AuthAdapter {\n private readonly tokenKey: string\n\n constructor(\n private readonly client: ConvexHttpClient,\n private readonly store: SessionStore = defaultStore(),\n /** Deployment URL the token is scoped to (per-backend sessions, EC-179). */\n deploymentUrl?: string,\n ) {\n this.tokenKey = tokenStorageKey(deploymentUrl)\n }\n\n async currentSession(): Promise<AuthSession | null> {\n const token = this.store.getItem(this.tokenKey)\n if (!token) return null\n this.client.setAuth(token)\n try {\n const me = (await this.client.query(queryRef('users:me'), {})) as MeResult | null\n if (!me) {\n this.clearToken()\n return null\n }\n return { user: this.toUser(me) }\n } catch {\n // Expired/invalid JWT or unreachable backend → treat as signed out.\n this.clearToken()\n return null\n }\n }\n\n async signIn(credentials: SignInCredentials): Promise<SignInResult> {\n return this.authenticate('signIn', credentials)\n }\n\n async signUp(credentials: SignInCredentials): Promise<SignInResult> {\n return this.authenticate('signUp', credentials)\n }\n\n /**\n * Shared password flow (EC-150/EC-179). `signIn` and `signUp` differ only by\n * the Convex Auth `flow` param; both return a token + load `users:me`.\n */\n private async authenticate(\n flow: 'signIn' | 'signUp',\n credentials: SignInCredentials,\n ): Promise<SignInResult> {\n let result: SignInActionResult\n try {\n result = (await this.client.action(actionRef('auth:signIn'), {\n provider: 'password',\n params: {\n email: credentials.email.trim().toLowerCase(),\n password: credentials.password,\n flow,\n },\n })) as SignInActionResult\n } catch (error) {\n // Convex Auth surfaces credential/registration problems as thrown errors.\n // Classify from the DATA-FIRST text (a `ConvexError`'s `.data` survives prod\n // redaction, the redacted `.message` does not — EC-362), then apply the pure\n // regex ladder. See `convexErrorClassifierText` / `classifySignInError`.\n return classifySignInError(flow, convexErrorClassifierText(error))\n }\n if (!result.tokens) {\n return {\n ok: false,\n reason: 'invalid-credentials',\n message: 'Email or password is incorrect.',\n }\n }\n this.store.setItem(this.tokenKey, result.tokens.token)\n this.client.setAuth(result.tokens.token)\n const me = (await this.client.query(queryRef('users:me'), {})) as MeResult | null\n if (!me) {\n this.clearToken()\n return { ok: false, reason: 'unavailable', message: 'Sign-in is currently unavailable.' }\n }\n return { ok: true, session: { user: this.toUser(me) } }\n }\n\n async signOut(): Promise<void> {\n try {\n await this.client.action(actionRef('auth:signOut'), {})\n } catch {\n // Already signed out / unreachable — clearing local state is what matters.\n }\n this.clearToken()\n }\n\n /**\n * Self-service identity edit (EC-240 H-tail item 2). Patches the caller's OWN\n * auth `users` row (name / avatar) via the self-scoped `users:updateProfile`\n * mutation, then re-reads `users:me` so the returned session carries the new\n * name. Auth-owned fields never flow through the members-rail `users.save`.\n */\n async updateProfile(input: UpdateProfileInput): Promise<UpdateProfileResult> {\n const token = this.store.getItem(this.tokenKey)\n if (!token) {\n return { ok: false, reason: 'not-authenticated', message: 'You are not signed in.' }\n }\n this.client.setAuth(token)\n try {\n await this.client.mutation(mutationRef('users:updateProfile'), {\n ...(input.name !== undefined ? { name: input.name } : {}),\n ...(input.avatar !== undefined ? { avatar: input.avatar } : {}),\n })\n const me = (await this.client.query(queryRef('users:me'), {})) as MeResult | null\n if (!me) {\n return { ok: false, reason: 'unavailable', message: 'Profile update is currently unavailable.' }\n }\n return { ok: true, session: { user: this.toUser(me) } }\n } catch {\n return { ok: false, reason: 'unavailable', message: 'Profile update is currently unavailable.' }\n }\n }\n\n /**\n * Self-service password change (EC-240 H-tail item 3). Delegates entirely to\n * the provider via the self-scoped `users:changePassword` ACTION (which calls\n * Convex Auth's `retrieveAccount` to verify the current password, then\n * `modifyAccountCredentials` to set the new one). **Seam only:** the raw\n * password values are forwarded to the provider and NEVER logged or inspected\n * here.\n */\n async changePassword(input: ChangePasswordInput): Promise<ChangePasswordResult> {\n const token = this.store.getItem(this.tokenKey)\n if (!token) {\n return { ok: false, reason: 'not-authenticated', message: 'You are not signed in.' }\n }\n this.client.setAuth(token)\n try {\n await this.client.action(actionRef('users:changePassword'), {\n currentPassword: input.currentPassword,\n newPassword: input.newPassword,\n })\n return { ok: true }\n } catch (error) {\n // Data-first classification (EC-362): the change-password ACTION runs on the\n // same deployment, so a prod redaction erases the thrown `.message` the same\n // way — read a surviving `ConvexError.data` first.\n return classifyChangePasswordError(convexErrorClassifierText(error))\n }\n }\n\n private toUser(me: MeResult): AuthSession['user'] {\n return {\n id: me.id,\n email: me.email,\n ...(me.name ? { name: me.name } : {}),\n // No global flags: project creation is config/CLI-owned (AD-11), so there\n // is no in-studio `create-projects` capability. Per-project roles come\n // from `projectMembers`.\n globalFlags: [],\n }\n }\n\n private clearToken(): void {\n this.store.removeItem(this.tokenKey)\n this.client.clearAuth()\n }\n}\n"]}