oneie 3.6.7 → 3.6.12

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 (168) hide show
  1. package/.claude/agents/agent-backend.md +83 -0
  2. package/.claude/agents/agent-designer.md +97 -0
  3. package/.claude/agents/agent-director.md +118 -7
  4. package/.claude/agents/agent-documenter.md +93 -0
  5. package/.claude/agents/agent-frontend.md +96 -0
  6. package/.claude/agents/agent-ops.md +264 -32
  7. package/.claude/agents/agent-problem-solver.md +166 -0
  8. package/.claude/agents/agent-quality.md +127 -0
  9. package/.claude/commands/build.md +293 -0
  10. package/.claude/commands/cascade.md +231 -127
  11. package/.claude/commands/deploy.md +56 -17
  12. package/.claude/commands/mcp-toggle.md +93 -0
  13. package/.claude/commands/one.md +78 -127
  14. package/.claude/commands/plan.md +394 -80
  15. package/.claude/commands/push.md +75 -14
  16. package/.claude/commands/release.md +89 -25
  17. package/.claude/commands/server.md +2 -0
  18. package/.claude/hooks/__pycache__/todo.cpython-313.pyc +0 -0
  19. package/.claude/hooks/root-cleanup.py +75 -0
  20. package/.claude/skills/INDEX.md +523 -0
  21. package/.claude/skills/REGISTRY.md +529 -0
  22. package/.claude/skills/agent-backend-create-mutation.md +319 -0
  23. package/.claude/skills/agent-designer-create-wireframe.md +341 -0
  24. package/.claude/skills/agent-frontend-create-page.md +413 -0
  25. package/.claude/skills/agents/README.md +238 -0
  26. package/dist/clone-web.js +1 -1
  27. package/dist/clone-web.js.map +1 -1
  28. package/folders.yaml +1 -1
  29. package/one/.obsidian/workspace.json +38 -38
  30. package/one/connections/api/queries-reference.md +842 -0
  31. package/one/connections/api-reference.md +1011 -0
  32. package/one/connections/integration-examples.md +875 -0
  33. package/one/connections/integration-guide.md +869 -0
  34. package/one/connections/integration-phase2.md +736 -0
  35. package/one/events/API_ROUTES_FIXES_SUMMARY.md +262 -0
  36. package/one/events/ASTRO-INTEGRATION-EXAMPLES.md +636 -0
  37. package/one/events/BEFORE_AFTER_COMPARISON.md +960 -0
  38. package/one/events/CONNECTIONS_DEMO.md +501 -0
  39. package/one/events/DELIVERABLES.md +432 -0
  40. package/one/events/DEMO-GROUPS-PAGE.md +392 -0
  41. package/one/events/DEMO-TESTING-SUMMARY.md +518 -0
  42. package/one/events/DEMO_COMPONENTS.md +487 -0
  43. package/one/events/DEMO_HOOKS_INDEX.md +334 -0
  44. package/one/events/DEMO_INFRASTRUCTURE.md +905 -0
  45. package/one/events/DEMO_INFRASTRUCTURE_SUMMARY.md +570 -0
  46. package/one/events/DEMO_INTEGRATION_CHECKLIST.md +431 -0
  47. package/one/events/DEMO_QUICK_REFERENCE.md +441 -0
  48. package/one/events/DEMO_SETUP.md +476 -0
  49. package/one/events/EFFECT_TS_API_PATTERN.md +478 -0
  50. package/one/events/GROUPS_DEMO_IMPLEMENTATION.md +414 -0
  51. package/one/events/HOOKS-DEMO.md +441 -0
  52. package/one/events/ONTOLOGY-HOOKS-README.md +700 -0
  53. package/one/events/ONTOLOGY-INTEGRATION-MANIFEST.md +365 -0
  54. package/one/events/QA-CHECKLIST.md +674 -0
  55. package/one/events/QUICK-START-ONTOLOGY.md +408 -0
  56. package/one/events/SEARCH_DEMO_CODE_REFERENCE.md +639 -0
  57. package/one/events/SEARCH_DEMO_DELIVERY.md +415 -0
  58. package/one/events/SEARCH_DEMO_SUMMARY.md +303 -0
  59. package/one/events/SEARCH_DEMO_VISUAL_GUIDE.md +381 -0
  60. package/one/events/TEST-PLAN-INDEX.md +346 -0
  61. package/one/events/TEST-PLAN.md +1417 -0
  62. package/one/events/TESTING-DELIVERY.txt +372 -0
  63. package/one/events/TRANSITIONS-QUICK-START.md +141 -0
  64. package/one/events/TYPESCRIPT_FIXES.md +152 -0
  65. package/one/events/TYPESCRIPT_FIXES_COMPLETE.txt +412 -0
  66. package/one/events/TYPESCRIPT_FIXES_INDEX.md +341 -0
  67. package/one/events/VIEW-TRANSITIONS.md +428 -0
  68. package/one/events/backend-integration-tests.md +606 -0
  69. package/one/events/backend-structure-diagram.txt +393 -0
  70. package/one/events/backend-structure-summary.txt +269 -0
  71. package/one/events/cloudflare-pages-infrastructure-setup.md +264 -0
  72. package/one/events/convex-analysis-index.md +304 -0
  73. package/one/events/convex-structure-analysis.md +700 -0
  74. package/one/events/design-spec-complete.md +208 -0
  75. package/one/events/ontology-test-examples.md +562 -0
  76. package/one/events/phase1-backend-implementation-complete.md +518 -0
  77. package/one/events/test-dashboard.md +345 -0
  78. package/one/events/test-index.md +361 -0
  79. package/one/events/test-report-ontology.md +582 -0
  80. package/one/events/testing-summary.md +344 -0
  81. package/one/groups/features.md +2878 -0
  82. package/one/groups/strategy copy.md +869 -0
  83. package/one/knowledge/backend-api-reference.md +710 -0
  84. package/one/knowledge/documentation-summary.md +285 -0
  85. package/one/knowledge/lessons-learned.md +294 -4
  86. package/one/knowledge/ontology-visual-guide.md +360 -0
  87. package/one/knowledge/ontology.md +9 -17
  88. package/one/things/demo-accessibility-animations.md +999 -0
  89. package/one/things/demo-components.md +1304 -0
  90. package/one/things/demo-design-summary.md +629 -0
  91. package/one/things/demo-design-system.md +919 -0
  92. package/one/things/demo-page-layouts.md +989 -0
  93. package/one/things/designs/accessibility-audit.md +790 -0
  94. package/one/things/designs/component-specifications.md +757 -0
  95. package/one/things/designs/design-overview.md +318 -0
  96. package/one/things/designs/design-tokens.md +414 -0
  97. package/one/things/designs/wireframes-dashboard.md +653 -0
  98. package/one/things/docs/api-requests.md +923 -0
  99. package/one/things/features/0 All Features.md +2 -0
  100. package/one/things/implementation/backend-guide.md +412 -0
  101. package/one/things/plans/2-backend-agnostic-frontend.md +11 -8
  102. package/one/things/plans/2-sites.md +895 -0
  103. package/one/things/plans/ai-elements.md +1259 -0
  104. package/one/things/plans/ai-integration.md +947 -0
  105. package/one/things/plans/ai-sdk.md +761 -0
  106. package/one/things/plans/app.md +1 -1
  107. package/one/things/plans/architecture-summary.md +283 -0
  108. package/one/things/plans/async-ai-agents.md +215 -0
  109. package/one/things/plans/backend-agnostic-frontend.md +11 -6
  110. package/one/things/plans/backend-cleanup-quickstart.md +346 -0
  111. package/one/things/plans/backend-ontology-conformance.md +416 -0
  112. package/one/things/plans/backend-status.md +541 -0
  113. package/one/things/plans/backend-structure.md +799 -0
  114. package/one/things/plans/backend-target-structure.md +438 -0
  115. package/one/things/plans/backend.md +1133 -0
  116. package/one/things/plans/better-auth-any-backend.md +11 -11
  117. package/one/things/plans/cli-updates-required.md +280 -0
  118. package/one/things/plans/complete-step-by-step.md +1302 -0
  119. package/one/things/plans/convex-agents.md +1005 -0
  120. package/one/things/plans/deployment-architecture.md +426 -0
  121. package/one/things/plans/development-plan.md +1220 -0
  122. package/one/things/plans/effect.md +808 -48
  123. package/one/things/plans/integrate-frontend-and-backend.md +579 -0
  124. package/one/things/plans/mcp-clear-context-prompt.md +60 -0
  125. package/one/things/plans/mcp-simple.md +228 -0
  126. package/one/things/plans/one.md +8 -7
  127. package/one/things/plans/ontology-6-dimensions.md +20 -14
  128. package/one/things/plans/quick-wins.md +1273 -0
  129. package/one/things/plans/readme-backend-cleanup.md +361 -0
  130. package/one/things/plans/separate-demo.md +830 -0
  131. package/one/things/plans/separate.md +3 -3
  132. package/one/things/plans/sequence.md +1897 -0
  133. package/one/things/plans/sync-checklist.md +321 -0
  134. package/one/things/plans/unified-implementation-plan.md +3 -3
  135. package/one/things/plans/update-demos.md +513 -0
  136. package/package.json +1 -1
  137. package/.claude/agents/backend-specialist.md +0 -169
  138. package/.claude/agents/designer.md +0 -216
  139. package/.claude/agents/frontend-specialist.md +0 -236
  140. package/.claude/commands/done.md +0 -35
  141. package/.claude/commands/infer.md +0 -138
  142. package/.claude/commands/next.md +0 -53
  143. package/.claude/commands/one copy.md +0 -565
  144. package/.claude/commands/one-template.md +0 -106
  145. package/.claude/commands/one-v1.md +0 -609
  146. package/.claude/hooks/__pycache__/knowledge-post.cpython-313.pyc +0 -0
  147. package/.claude/hooks/__pycache__/knowledge-pre.cpython-313.pyc +0 -0
  148. package/one/groups/nine-padel-customers.md +0 -138
  149. package/one/groups/nine-padel-data-structure.md +0 -167
  150. package/one/groups/nine-padel-ontology-specification.md +0 -359
  151. package/one/groups/nine-padel-ontology.md +0 -143
  152. package/one/groups/nine-padel-strategy.md +0 -234
  153. package/one/groups/nine-padel.md +0 -211
  154. package/one/groups/nine-padle-contents.baked.md +0 -1252
  155. package/one/groups/nine-padle-contents.md +0 -6
  156. package/one/things/features/1-1-agent-prompts/design.md +0 -470
  157. package/one/things/features/1-1-agent-prompts/tests.md +0 -264
  158. package/one/things/features/1-2-yaml-orchestrator/design.md +0 -497
  159. package/one/things/features/1-2-yaml-orchestrator/tests.md +0 -227
  160. package/one/things/features/1-3-event-coordination/design.md +0 -544
  161. package/one/things/features/1-3-event-coordination/tests.md +0 -223
  162. package/one/things/features/1-4-knowledge-management/design.md +0 -609
  163. package/one/things/features/1-4-knowledge-management/tests.md +0 -195
  164. package/one/things/features/1-5-quality-loops/design.md +0 -797
  165. package/one/things/features/1-5-quality-loops/tests.md +0 -212
  166. package/one/things/features/1-6-numbering-structure/design.md +0 -610
  167. package/one/things/features/1-6-numbering-structure/tests.md +0 -213
  168. package/one/things/features/dataprovider-interface/1-tests.md +0 -1522
@@ -0,0 +1,1005 @@
1
+ # Convex Agents Implementation Plan
2
+
3
+ **Version:** 1.0.0
4
+ **Status:** Planning
5
+ **Integration:** AI SDK + AI Elements
6
+ **Target Platform:** Convex Cloud + Astro + React 19
7
+
8
+ ---
9
+
10
+ ## Architecture: Effect.ts Wrapping Agent Component
11
+
12
+ Convex Agents component provides infrastructure (thread management, streaming, retries). We wrap it with **Effect.ts services** for type-safe business logic composition:
13
+
14
+ ```typescript
15
+ // Tagged error types for agent operations
16
+ class AgentExecutionError extends Data.TaggedError("AgentExecutionError")<{
17
+ agentName: string
18
+ threadId: string
19
+ cause: unknown
20
+ }> {}
21
+
22
+ class ThreadNotFoundError extends Data.TaggedError("ThreadNotFoundError")<{
23
+ threadId: string
24
+ }> {}
25
+
26
+ // Define AgentService with Context.Tag
27
+ class AgentService extends Context.Tag("AgentService")<
28
+ AgentService,
29
+ {
30
+ readonly createThread: (
31
+ ctx: ActionCtx,
32
+ agentId: string,
33
+ initialMessage: string
34
+ ) => Effect.Effect<{ threadId: string }, AgentExecutionError>
35
+
36
+ readonly continueThread: (
37
+ ctx: ActionCtx,
38
+ threadId: string,
39
+ message: string
40
+ ) => Effect.Effect<{ response: string; threadId: string }, AgentExecutionError | ThreadNotFoundError>
41
+
42
+ readonly getThreadMessages: (
43
+ threadId: string
44
+ ) => Effect.Effect<Message[], ThreadNotFoundError>
45
+ }
46
+ >() {}
47
+
48
+ // Implement using Agent component
49
+ const AgentServiceLive = Layer.effect(
50
+ AgentService,
51
+ Effect.gen(function* () {
52
+ const agent = new Agent(components.agent, {
53
+ name: "Main Agent",
54
+ chat: openai("gpt-4-turbo"),
55
+ instructions: "You are a helpful AI assistant.",
56
+ tools: {
57
+ /* tools defined separately */
58
+ }
59
+ });
60
+
61
+ return {
62
+ createThread: (ctx, agentId, initialMessage) =>
63
+ Effect.gen(function* () {
64
+ const result = yield* Effect.tryPromise({
65
+ try: () => agent.createThread(ctx, {
66
+ messages: [{ role: "user", content: initialMessage }]
67
+ }),
68
+ catch: (error) => new AgentExecutionError({
69
+ agentName: "Main Agent",
70
+ threadId: "unknown",
71
+ cause: error
72
+ })
73
+ });
74
+ return { threadId: result.threadId };
75
+ }),
76
+
77
+ continueThread: (ctx, threadId, message) =>
78
+ Effect.gen(function* () {
79
+ const { thread } = yield* Effect.tryPromise({
80
+ try: () => agent.continueThread(ctx, { threadId }),
81
+ catch: (error) => new ThreadNotFoundError({ threadId })
82
+ });
83
+
84
+ const response = yield* Effect.tryPromise({
85
+ try: () => thread.generateText({ prompt: message }),
86
+ catch: (error) => new AgentExecutionError({
87
+ agentName: "Main Agent",
88
+ threadId,
89
+ cause: error
90
+ })
91
+ });
92
+
93
+ return { response: response.text, threadId };
94
+ }),
95
+
96
+ getThreadMessages: (threadId) =>
97
+ Effect.tryPromise({
98
+ try: () => agent.getMessages(threadId),
99
+ catch: (error) => new ThreadNotFoundError({ threadId })
100
+ })
101
+ };
102
+ })
103
+ );
104
+ ```
105
+
106
+ ---
107
+
108
+ ## Overview
109
+
110
+ **Convex Agents** is a Convex component that manages AI agent workflows. It provides:
111
+
112
+ - Thread-based conversation management
113
+ - Automatic message persistence
114
+ - Tool call orchestration
115
+ - Real-time streaming via WebSockets
116
+ - Built-in RAG support for knowledge retrieval
117
+ - Multi-tenant isolation (per `groupId`)
118
+ - Usage tracking for billing
119
+
120
+ ### Why Convex Agents?
121
+
122
+ - **Persistence**: All conversations automatically saved in Convex database
123
+ - **Scalability**: Handles thousands of concurrent agent threads
124
+ - **Real-time**: WebSocket streaming for instant client updates
125
+ - **Type-safe**: Full TypeScript support with auto-generated types
126
+ - **Integrated**: Works seamlessly with Convex functions, auth, and storage
127
+
128
+ ---
129
+
130
+ ## Architecture: Convex Agents in the Stack
131
+
132
+ ```
133
+ AI Elements UI (Chat Interface)
134
+ ↓
135
+ React Components + useChat Hook
136
+ ↓
137
+ Convex Mutations (Agent Functions)
138
+ ↓
139
+ Convex Agents Runtime
140
+ ├─ Thread Management
141
+ ├─ Message Persistence
142
+ ├─ Tool Execution
143
+ ├─ Streaming Pipeline
144
+ └─ RAG Integration
145
+ ↓
146
+ AI SDK (generateText, streamText)
147
+ ↓
148
+ LLM Providers (OpenAI, Anthropic, etc.)
149
+ ```
150
+
151
+ ---
152
+
153
+ ## Installation & Setup (Infer 1-10)
154
+
155
+ ### Install Package
156
+
157
+ ```bash
158
+ npm install @convex-dev/agent
159
+ ```
160
+
161
+ ### Add to Schema
162
+
163
+ ```typescript
164
+ // backend/convex/schema.ts
165
+ import { defineSchema, defineTable } from "convex/server";
166
+ import { v } from "convex/values";
167
+ import { agentTables } from "@convex-dev/agent";
168
+
169
+ export default defineSchema({
170
+ // Existing tables...
171
+ groups: defineTable({...}),
172
+ things: defineTable({...}),
173
+ connections: defineTable({...}),
174
+ events: defineTable({...}),
175
+ knowledge: defineTable({...}),
176
+
177
+ // AI-specific tables
178
+ aiCalls: defineTable({
179
+ groupId: v.id("groups"),
180
+ model: v.string(),
181
+ provider: v.string(),
182
+ prompt: v.string(),
183
+ result: v.string(),
184
+ tokensUsed: v.optional(v.object({ input: v.number(), output: v.number() })),
185
+ duration: v.number(),
186
+ timestamp: v.number(),
187
+ }).index("by_groupId", ["groupId"]),
188
+
189
+ // Agent tables (provided by Convex Agents component)
190
+ ...agentTables(),
191
+ });
192
+ ```
193
+
194
+ ### Initialize Agent Runtime
195
+
196
+ ```typescript
197
+ // backend/convex/agent.ts
198
+ import { defineAgent } from "@convex-dev/agent";
199
+ import { internal } from "./_generated/server";
200
+ import { openai } from "@ai-sdk/openai";
201
+
202
+ export const agentRuntime = defineAgent(async (ctx, params) => {
203
+ const { groupId, agentId, message, threadId } = params;
204
+
205
+ // Get agent configuration from things table
206
+ const agent = await ctx.db.get(agentId);
207
+ if (!agent || agent.type !== "agent") {
208
+ throw new Error("Agent not found");
209
+ }
210
+
211
+ // Set up model based on agent configuration
212
+ const model = openai(agent.properties.model || "gpt-4-turbo");
213
+
214
+ return {
215
+ model,
216
+ systemPrompt: agent.properties.systemPrompt,
217
+ tools: await loadAgentTools(ctx, groupId, agentId),
218
+ };
219
+ });
220
+
221
+ async function loadAgentTools(ctx: any, groupId: string, agentId: string) {
222
+ // Load tool definitions from agent configuration
223
+ // Tools are defined in agent.properties.tools array
224
+ return {};
225
+ }
226
+ ```
227
+
228
+ ---
229
+
230
+ ## Thread Management (Infer 11-20)
231
+
232
+ ### Create Agent Thread
233
+
234
+ ```typescript
235
+ // backend/convex/mutations/agentThreads.ts
236
+ import { mutation } from "./_generated/server";
237
+ import { v } from "convex/values";
238
+
239
+ export const createThread = mutation({
240
+ args: {
241
+ groupId: v.id("groups"),
242
+ agentId: v.id("things"),
243
+ title: v.optional(v.string()),
244
+ },
245
+ handler: async (ctx, args) => {
246
+ // Create a new thread in aiThreads table
247
+ const threadId = await ctx.db.insert("aiThreads", {
248
+ groupId: args.groupId,
249
+ agentId: args.agentId,
250
+ title: args.title || "New Conversation",
251
+ status: "active",
252
+ metadata: {
253
+ createdBy: ctx.auth?.getUserIdentity()?.tokenIdentifier,
254
+ },
255
+ createdAt: Date.now(),
256
+ updatedAt: Date.now(),
257
+ });
258
+
259
+ // Log event
260
+ await ctx.db.insert("events", {
261
+ groupId: args.groupId,
262
+ type: "agent_thread_created",
263
+ actorId: ctx.auth?.getUserIdentity()?.tokenIdentifier,
264
+ targetId: threadId,
265
+ timestamp: Date.now(),
266
+ metadata: { agentId: args.agentId },
267
+ });
268
+
269
+ return threadId;
270
+ },
271
+ });
272
+
273
+ export const listThreads = query({
274
+ args: { groupId: v.id("groups"), agentId: v.id("things") },
275
+ handler: async (ctx, args) => {
276
+ return await ctx.db
277
+ .query("aiThreads")
278
+ .withIndex("by_groupId", (q) => q.eq("groupId", args.groupId))
279
+ .filter((q) => q.eq(q.field("agentId"), args.agentId))
280
+ .order("desc")
281
+ .collect();
282
+ },
283
+ });
284
+
285
+ export const getThread = query({
286
+ args: { threadId: v.id("aiThreads") },
287
+ handler: async (ctx, args) => {
288
+ return await ctx.db.get(args.threadId);
289
+ },
290
+ });
291
+
292
+ export const archiveThread = mutation({
293
+ args: { threadId: v.id("aiThreads") },
294
+ handler: async (ctx, args) => {
295
+ const thread = await ctx.db.get(args.threadId);
296
+ if (!thread) throw new Error("Thread not found");
297
+
298
+ await ctx.db.patch(args.threadId, {
299
+ status: "archived",
300
+ updatedAt: Date.now(),
301
+ });
302
+
303
+ return args.threadId;
304
+ },
305
+ });
306
+ ```
307
+
308
+ ### Message Management (via Convex Agents)
309
+
310
+ Convex Agents automatically manages messages within threads. Messages are:
311
+
312
+ - Stored in a Convex Agents internal table
313
+ - Keyed by `threadId`
314
+ - Accessible via `getMessages()` helper
315
+ - Automatically included in agent context
316
+
317
+ ```typescript
318
+ // backend/convex/queries/agentMessages.ts
319
+ import { query } from "./_generated/server";
320
+ import { v } from "convex/values";
321
+ import { getMessages } from "@convex-dev/agent";
322
+
323
+ export const getThreadMessages = query({
324
+ args: { threadId: v.string() },
325
+ handler: async (ctx, args) => {
326
+ // Retrieve all messages for a thread
327
+ const messages = await getMessages(ctx, {
328
+ threadId: args.threadId,
329
+ });
330
+
331
+ return messages;
332
+ },
333
+ });
334
+
335
+ export const getThreadContext = query({
336
+ args: { threadId: v.string(), limit: v.optional(v.number()) },
337
+ handler: async (ctx, args) => {
338
+ const messages = await getMessages(ctx, {
339
+ threadId: args.threadId,
340
+ limit: args.limit || 10,
341
+ });
342
+
343
+ // Return formatted for LLM context
344
+ return messages.map((msg) => ({
345
+ role: msg.role,
346
+ content: msg.content,
347
+ timestamp: msg.createdAt,
348
+ }));
349
+ },
350
+ });
351
+ ```
352
+
353
+ ---
354
+
355
+ ## Tool Integration (Infer 21-30)
356
+
357
+ ### Define Agent Tools
358
+
359
+ ```typescript
360
+ // backend/convex/agent/tools.ts
361
+ import { tool } from "ai";
362
+ import { z } from "zod";
363
+
364
+ export const agentTools = {
365
+ searchKnowledge: tool({
366
+ description: "Search the group's knowledge base for relevant information",
367
+ parameters: z.object({
368
+ query: v.string().describe("Search query"),
369
+ limit: z.number().default(5),
370
+ }),
371
+ execute: async (input) => {
372
+ // Implement RAG search against knowledge table
373
+ return "Search results...";
374
+ },
375
+ }),
376
+
377
+ createTask: tool({
378
+ description: "Create a new task thing",
379
+ parameters: z.object({
380
+ title: z.string(),
381
+ description: z.string().optional(),
382
+ priority: z.enum(["low", "medium", "high"]),
383
+ }),
384
+ execute: async (input) => {
385
+ // Create thing with type: "task"
386
+ return { taskId: "task_123", created: true };
387
+ },
388
+ }),
389
+
390
+ getContext: tool({
391
+ description: "Get information about the current context",
392
+ parameters: z.object({
393
+ contextType: z.enum(["group", "user", "agent"]),
394
+ }),
395
+ execute: async (input) => {
396
+ // Return context information
397
+ return { context: "context_data" };
398
+ },
399
+ }),
400
+
401
+ callHuman: tool({
402
+ description: "Escalate to human support",
403
+ parameters: z.object({
404
+ reason: z.string().describe("Reason for escalation"),
405
+ }),
406
+ execute: async (input) => {
407
+ // Create connection to human agent
408
+ // Send notification
409
+ return { escalationId: "esc_123", status: "waiting_for_human" };
410
+ },
411
+ }),
412
+ };
413
+ ```
414
+
415
+ ### Register Tools with Agent
416
+
417
+ ```typescript
418
+ // backend/convex/agent.ts (updated)
419
+ import { agentTools } from "./agent/tools";
420
+
421
+ export const agentRuntime = defineAgent(async (ctx, params) => {
422
+ const { groupId, agentId, message, threadId } = params;
423
+
424
+ const agent = await ctx.db.get(agentId);
425
+ if (!agent || agent.type !== "agent") {
426
+ throw new Error("Agent not found");
427
+ }
428
+
429
+ const model = openai(agent.properties.model || "gpt-4-turbo");
430
+
431
+ // Filter tools based on agent.properties.tools array
432
+ const allowedTools = agent.properties.tools || [];
433
+ const tools = Object.fromEntries(
434
+ Object.entries(agentTools).filter(([name]) => allowedTools.includes(name))
435
+ );
436
+
437
+ return {
438
+ model,
439
+ systemPrompt: agent.properties.systemPrompt,
440
+ tools,
441
+ groupId,
442
+ threadId,
443
+ };
444
+ });
445
+ ```
446
+
447
+ ### Execute Tool Calls
448
+
449
+ Convex Agents automatically executes tool calls and manages the agentic loop. When the agent calls a tool:
450
+
451
+ 1. Tool execution is triggered
452
+ 2. Result is stored in thread context
453
+ 3. Agent continues with result included
454
+ 4. Client sees streamed updates
455
+
456
+ ---
457
+
458
+ ## Streaming Setup (Infer 31-40)
459
+
460
+ ### Streaming Mutation
461
+
462
+ ```typescript
463
+ // backend/convex/mutations/agentChat.ts
464
+ import { mutation } from "./_generated/server";
465
+ import { v } from "convex/values";
466
+ import { streamText } from "ai";
467
+ import { agentRuntime } from "../agent";
468
+
469
+ export const sendMessage = mutation({
470
+ args: {
471
+ groupId: v.id("groups"),
472
+ agentId: v.id("things"),
473
+ threadId: v.string(),
474
+ message: v.string(),
475
+ },
476
+ handler: async (ctx, args) => {
477
+ // Add message to thread
478
+ const agent = await ctx.db.get(args.agentId);
479
+ if (!agent) throw new Error("Agent not found");
480
+
481
+ // Get agent configuration
482
+ const config = await agentRuntime(ctx, {
483
+ groupId: args.groupId,
484
+ agentId: args.agentId,
485
+ threadId: args.threadId,
486
+ message: args.message,
487
+ });
488
+
489
+ // Get conversation context
490
+ const messages = await getMessages(ctx, {
491
+ threadId: args.threadId,
492
+ limit: 20,
493
+ });
494
+
495
+ // Stream text response
496
+ const { textStream, usage } = await streamText({
497
+ model: config.model,
498
+ system: config.systemPrompt,
499
+ tools: config.tools,
500
+ messages: [
501
+ ...messages,
502
+ { role: "user", content: args.message },
503
+ ],
504
+ });
505
+
506
+ // Log AI call
507
+ await ctx.db.insert("aiCalls", {
508
+ groupId: args.groupId,
509
+ model: agent.properties.model,
510
+ provider: "openai",
511
+ prompt: args.message,
512
+ result: "", // Will be populated later
513
+ tokensUsed: { input: 0, output: 0 },
514
+ duration: 0,
515
+ timestamp: Date.now(),
516
+ });
517
+
518
+ // Update thread
519
+ await ctx.db.patch(args.threadId, {
520
+ updatedAt: Date.now(),
521
+ });
522
+
523
+ return {
524
+ threadId: args.threadId,
525
+ stream: textStream,
526
+ usage,
527
+ };
528
+ },
529
+ });
530
+ ```
531
+
532
+ ### WebSocket Streaming (Client)
533
+
534
+ ```typescript
535
+ // web/src/lib/hooks/useAgentStream.ts
536
+ import { useMutation } from "convex/react";
537
+ import { api } from "@/convex/_generated/api";
538
+ import { useState } from "react";
539
+
540
+ export function useAgentStream(groupId: string, agentId: string, threadId: string) {
541
+ const sendMessage = useMutation(api.mutations.agentChat.sendMessage);
542
+ const [messages, setMessages] = useState<Array<{ role: string; content: string }>>([]);
543
+ const [isStreaming, setIsStreaming] = useState(false);
544
+
545
+ const stream = async (userMessage: string) => {
546
+ setIsStreaming(true);
547
+ setMessages((prev) => [...prev, { role: "user", content: userMessage }]);
548
+
549
+ try {
550
+ const response = await sendMessage({
551
+ groupId,
552
+ agentId,
553
+ threadId,
554
+ message: userMessage,
555
+ });
556
+
557
+ // Handle streaming response
558
+ const reader = response.stream.getReader();
559
+ const decoder = new TextDecoder();
560
+ let fullResponse = "";
561
+
562
+ while (true) {
563
+ const { done, value } = await reader.read();
564
+ if (done) break;
565
+
566
+ const chunk = decoder.decode(value);
567
+ fullResponse += chunk;
568
+
569
+ // Update UI with streaming text
570
+ setMessages((prev) => {
571
+ const updated = [...prev];
572
+ const lastMsg = updated[updated.length - 1];
573
+ if (lastMsg?.role === "assistant") {
574
+ lastMsg.content = fullResponse;
575
+ } else {
576
+ updated.push({ role: "assistant", content: fullResponse });
577
+ }
578
+ return updated;
579
+ });
580
+ }
581
+ } catch (error) {
582
+ console.error("Stream error:", error);
583
+ } finally {
584
+ setIsStreaming(false);
585
+ }
586
+ };
587
+
588
+ return {
589
+ messages,
590
+ isStreaming,
591
+ stream,
592
+ };
593
+ }
594
+ ```
595
+
596
+ ---
597
+
598
+ ## RAG Integration (Infer 51-60)
599
+
600
+ ### Connect Agent to Knowledge
601
+
602
+ ```typescript
603
+ // backend/convex/agent/tools.ts (updated)
604
+ import { searchKnowledge } from "../services/rag";
605
+
606
+ export const agentTools = {
607
+ searchKnowledge: tool({
608
+ description: "Search the group's knowledge base",
609
+ parameters: z.object({
610
+ query: z.string(),
611
+ limit: z.number().default(5),
612
+ }),
613
+ execute: async (input, { ctx, groupId }) => {
614
+ const results = await searchKnowledge(ctx, {
615
+ groupId,
616
+ query: input.query,
617
+ limit: input.limit,
618
+ });
619
+
620
+ return {
621
+ results: results.map((r) => ({
622
+ title: r.title,
623
+ content: r.content,
624
+ relevance: r.relevance,
625
+ })),
626
+ };
627
+ },
628
+ }),
629
+ };
630
+ ```
631
+
632
+ ### RAG Service
633
+
634
+ ```typescript
635
+ // backend/convex/services/rag.ts
636
+ import { QueryCtx } from "./_generated/server";
637
+ import { v } from "convex/values";
638
+
639
+ export async function searchKnowledge(
640
+ ctx: QueryCtx,
641
+ args: {
642
+ groupId: string;
643
+ query: string;
644
+ limit: number;
645
+ }
646
+ ) {
647
+ // 1. Embed query using AI SDK
648
+ const queryEmbedding = await embedText(args.query);
649
+
650
+ // 2. Search knowledge table for similar embeddings
651
+ const results = await ctx.db
652
+ .query("knowledge")
653
+ .withIndex("by_groupId", (q) => q.eq("groupId", args.groupId))
654
+ .collect();
655
+
656
+ // 3. Calculate cosine similarity
657
+ const scored = results
658
+ .map((result) => ({
659
+ ...result,
660
+ relevance: cosineSimilarity(queryEmbedding, result.embedding),
661
+ }))
662
+ .sort((a, b) => b.relevance - a.relevance)
663
+ .slice(0, args.limit);
664
+
665
+ return scored;
666
+ }
667
+
668
+ function cosineSimilarity(a: number[], b: number[]): number {
669
+ const dotProduct = a.reduce((sum, val, i) => sum + val * b[i], 0);
670
+ const magnitude = Math.sqrt(a.reduce((sum, val) => sum + val * val, 0)) *
671
+ Math.sqrt(b.reduce((sum, val) => sum + val * val, 0));
672
+ return dotProduct / magnitude;
673
+ }
674
+
675
+ async function embedText(text: string): Promise<number[]> {
676
+ // Use OpenAI embeddings or similar
677
+ // Return 1536-dimensional vector
678
+ return [];
679
+ }
680
+ ```
681
+
682
+ ---
683
+
684
+ ## Multi-Tenant Isolation (Infer 71-80)
685
+
686
+ ### Group Scoping
687
+
688
+ All agent operations are scoped to `groupId`:
689
+
690
+ ```typescript
691
+ // ✅ Good: Scoped to group
692
+ export const listAgents = query({
693
+ args: { groupId: v.id("groups") },
694
+ handler: async (ctx, args) => {
695
+ return await ctx.db
696
+ .query("things")
697
+ .withIndex("by_type", (q) => q.eq("type", "agent"))
698
+ .filter((q) => q.eq(q.field("groupId"), args.groupId))
699
+ .collect();
700
+ },
701
+ });
702
+
703
+ // ❌ Bad: Not scoped
704
+ export const listAllAgents = query({
705
+ handler: async (ctx) => {
706
+ return await ctx.db.query("things").collect();
707
+ },
708
+ });
709
+ ```
710
+
711
+ ### Authorization
712
+
713
+ ```typescript
714
+ // Verify user has access to group
715
+ async function verifyGroupAccess(ctx: any, groupId: string) {
716
+ const userId = ctx.auth?.getUserIdentity()?.tokenIdentifier;
717
+ if (!userId) throw new Error("Not authenticated");
718
+
719
+ // Check if user is member of group
720
+ const membership = await ctx.db
721
+ .query("connections")
722
+ .filter((q) =>
723
+ q.and(
724
+ q.eq(q.field("type"), "member_of"),
725
+ q.eq(q.field("groupId"), groupId),
726
+ q.eq(q.field("from"), userId)
727
+ )
728
+ )
729
+ .first();
730
+
731
+ if (!membership) throw new Error("Access denied");
732
+ return true;
733
+ }
734
+ ```
735
+
736
+ ---
737
+
738
+ ## Usage Tracking & Billing (Infer 81-90)
739
+
740
+ ### Token Tracking
741
+
742
+ ```typescript
743
+ // backend/convex/services/usage.ts
744
+ import { MutationCtx } from "./_generated/server";
745
+
746
+ export async function trackUsage(
747
+ ctx: MutationCtx,
748
+ args: {
749
+ groupId: string;
750
+ model: string;
751
+ provider: string;
752
+ inputTokens: number;
753
+ outputTokens: number;
754
+ }
755
+ ) {
756
+ // Get group plan
757
+ const group = await ctx.db.get(args.groupId);
758
+ const plan = group?.properties?.plan || "starter";
759
+
760
+ // Calculate cost
761
+ const rates = {
762
+ openai: { input: 0.005, output: 0.015 },
763
+ anthropic: { input: 0.008, output: 0.024 },
764
+ };
765
+
766
+ const rate = rates[args.provider] || rates.openai;
767
+ const cost = (args.inputTokens * rate.input + args.outputTokens * rate.output) / 1000;
768
+
769
+ // Log usage event
770
+ await ctx.db.insert("events", {
771
+ groupId: args.groupId,
772
+ type: "usage_tracked",
773
+ actorId: null,
774
+ targetId: null,
775
+ timestamp: Date.now(),
776
+ metadata: {
777
+ model: args.model,
778
+ provider: args.provider,
779
+ tokens: args.inputTokens + args.outputTokens,
780
+ cost,
781
+ plan,
782
+ },
783
+ });
784
+
785
+ return { cost, totalTokens: args.inputTokens + args.outputTokens };
786
+ }
787
+ ```
788
+
789
+ ### Usage Dashboard
790
+
791
+ ```typescript
792
+ // backend/convex/queries/usage.ts
793
+ export const getGroupUsage = query({
794
+ args: { groupId: v.id("groups"), period: v.string() },
795
+ handler: async (ctx, args) => {
796
+ const now = Date.now();
797
+ const startTime = getPeriodStart(args.period, now);
798
+
799
+ const events = await ctx.db
800
+ .query("events")
801
+ .withIndex("by_groupId", (q) => q.eq("groupId", args.groupId))
802
+ .filter((q) => q.eq(q.field("type"), "usage_tracked"))
803
+ .filter((q) => q.gte(q.field("timestamp"), startTime))
804
+ .collect();
805
+
806
+ return {
807
+ totalTokens: events.reduce((sum, e) => sum + (e.metadata.tokens || 0), 0),
808
+ totalCost: events.reduce((sum, e) => sum + (e.metadata.cost || 0), 0),
809
+ byModel: groupBy(events, (e) => e.metadata.model),
810
+ byProvider: groupBy(events, (e) => e.metadata.provider),
811
+ };
812
+ },
813
+ });
814
+ ```
815
+
816
+ ---
817
+
818
+ ## Error Handling & Recovery (Infer 91-100)
819
+
820
+ ### Graceful Error Handling
821
+
822
+ ```typescript
823
+ // backend/convex/mutations/agentChat.ts (updated)
824
+ export const sendMessage = mutation({
825
+ args: {
826
+ groupId: v.id("groups"),
827
+ agentId: v.id("things"),
828
+ threadId: v.string(),
829
+ message: v.string(),
830
+ },
831
+ handler: async (ctx, args) => {
832
+ try {
833
+ // ... main flow ...
834
+ } catch (error) {
835
+ // Log error to events table
836
+ await ctx.db.insert("events", {
837
+ groupId: args.groupId,
838
+ type: "agent_error",
839
+ actorId: ctx.auth?.getUserIdentity()?.tokenIdentifier,
840
+ targetId: args.agentId,
841
+ timestamp: Date.now(),
842
+ metadata: {
843
+ error: error instanceof Error ? error.message : "Unknown error",
844
+ threadId: args.threadId,
845
+ },
846
+ });
847
+
848
+ // Return user-friendly error
849
+ return {
850
+ success: false,
851
+ error: "Failed to generate response. Please try again.",
852
+ };
853
+ }
854
+ },
855
+ });
856
+ ```
857
+
858
+ ### Retry Logic
859
+
860
+ ```typescript
861
+ // web/src/lib/hooks/useAgentRetry.ts
862
+ export function useAgentRetry(maxRetries = 3) {
863
+ return async (fn: () => Promise<any>) => {
864
+ for (let i = 0; i < maxRetries; i++) {
865
+ try {
866
+ return await fn();
867
+ } catch (error) {
868
+ if (i === maxRetries - 1) throw error;
869
+
870
+ // Exponential backoff
871
+ await new Promise((resolve) =>
872
+ setTimeout(resolve, Math.pow(2, i) * 1000)
873
+ );
874
+ }
875
+ }
876
+ };
877
+ }
878
+ ```
879
+
880
+ ---
881
+
882
+ ## Performance Optimization
883
+
884
+ | Optimization | Impact | Implementation |
885
+ |--------------|--------|-----------------|
886
+ | Message pagination | Reduce context size | Load 10 messages initially, paginate |
887
+ | Embedding caching | Faster RAG | Cache query embeddings for 5 minutes |
888
+ | Tool call batching | Reduce API calls | Group multiple tool executions |
889
+ | Streaming chunking | Better UX | Stream 50-100 tokens at a time |
890
+ | Index optimization | Faster queries | Use proper indexes on groupId |
891
+
892
+ ---
893
+
894
+ ## Testing Strategy
895
+
896
+ ### Unit Tests
897
+
898
+ ```typescript
899
+ // test/agent/tools.test.ts
900
+ test("searchKnowledge returns relevant results", async () => {
901
+ const results = await searchKnowledge(ctx, {
902
+ groupId: "group_123",
903
+ query: "how to create a task?",
904
+ limit: 5,
905
+ });
906
+
907
+ expect(results).toHaveLength(5);
908
+ expect(results[0].relevance).toBeGreaterThan(0.5);
909
+ });
910
+ ```
911
+
912
+ ### Integration Tests
913
+
914
+ ```typescript
915
+ // test/agent/integration.test.ts
916
+ test("full agent conversation flow", async () => {
917
+ // 1. Create group and agent
918
+ // 2. Create thread
919
+ // 3. Send message
920
+ // 4. Verify response streamed
921
+ // 5. Verify messages persisted
922
+ // 6. Verify usage tracked
923
+ });
924
+ ```
925
+
926
+ ---
927
+
928
+ ## Common Patterns
929
+
930
+ ### Pattern: Agent Context Injection
931
+
932
+ ```typescript
933
+ // Inject group context into all agent operations
934
+ type AgentContext = {
935
+ groupId: string;
936
+ agentId: string;
937
+ userId: string;
938
+ thread: any;
939
+ };
940
+
941
+ async function withAgentContext<T>(
942
+ ctx: MutationCtx,
943
+ args: any,
944
+ handler: (context: AgentContext) => Promise<T>
945
+ ): Promise<T> {
946
+ const agent = await ctx.db.get(args.agentId);
947
+ return handler({
948
+ groupId: args.groupId,
949
+ agentId: args.agentId,
950
+ userId: ctx.auth?.getUserIdentity()?.tokenIdentifier || "",
951
+ thread: args.threadId,
952
+ });
953
+ }
954
+ ```
955
+
956
+ ### Pattern: Message Formatting
957
+
958
+ ```typescript
959
+ // Format Convex messages for LLM
960
+ function formatMessagesForLLM(messages: any[]) {
961
+ return messages.map((msg) => ({
962
+ role: msg.role === "assistant" ? "assistant" : "user",
963
+ content: msg.content,
964
+ }));
965
+ }
966
+ ```
967
+
968
+ ---
969
+
970
+ ## Deployment Checklist
971
+
972
+ - [ ] Install `@convex-dev/agent` package
973
+ - [ ] Add agent tables to schema
974
+ - [ ] Create agent thing with properties
975
+ - [ ] Implement streaming mutations
976
+ - [ ] Set up RAG integration
977
+ - [ ] Configure rate limiting
978
+ - [ ] Add usage tracking
979
+ - [ ] Test multi-tenant isolation
980
+ - [ ] Deploy to production
981
+ - [ ] Monitor thread creation rate
982
+ - [ ] Track token usage per group
983
+
984
+ ---
985
+
986
+ ## Next Steps
987
+
988
+ 1. Install Convex Agents: `npm install @convex-dev/agent`
989
+ 2. Update schema with agent tables
990
+ 3. Create agent threads management mutations
991
+ 4. Implement streaming response mutations
992
+ 5. Connect to AI SDK generateText/streamText
993
+ 6. Add RAG search tool
994
+ 7. Test end-to-end flow
995
+ 8. Deploy to production
996
+
997
+ ---
998
+
999
+ ## References
1000
+
1001
+ - [Convex Agents Documentation](https://www.convex.dev/components/agent)
1002
+ - [Convex Database](https://docs.convex.dev/database)
1003
+ - [Convex Mutations](https://docs.convex.dev/functions/mutations)
1004
+ - [AI SDK Integration](./ai-sdk.md)
1005
+ - [6-Dimension Ontology](../knowledge/ontology.md)