oneie 3.6.7 → 3.6.11

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 (165) 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 +182 -25
  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/mcp-toggle.md +93 -0
  12. package/.claude/commands/one.md +198 -116
  13. package/.claude/commands/plan.md +394 -80
  14. package/.claude/commands/release.md +41 -19
  15. package/.claude/commands/server.md +2 -0
  16. package/.claude/hooks/root-cleanup.py +75 -0
  17. package/.claude/skills/INDEX.md +523 -0
  18. package/.claude/skills/REGISTRY.md +529 -0
  19. package/.claude/skills/agent-backend-create-mutation.md +319 -0
  20. package/.claude/skills/agent-designer-create-wireframe.md +341 -0
  21. package/.claude/skills/agent-frontend-create-page.md +413 -0
  22. package/.claude/skills/agents/README.md +238 -0
  23. package/dist/clone-web.js +1 -1
  24. package/dist/clone-web.js.map +1 -1
  25. package/folders.yaml +1 -1
  26. package/one/.obsidian/workspace.json +38 -38
  27. package/one/connections/api/queries-reference.md +842 -0
  28. package/one/connections/api-reference.md +1011 -0
  29. package/one/connections/integration-examples.md +875 -0
  30. package/one/connections/integration-guide.md +869 -0
  31. package/one/connections/integration-phase2.md +736 -0
  32. package/one/events/API_ROUTES_FIXES_SUMMARY.md +262 -0
  33. package/one/events/ASTRO-INTEGRATION-EXAMPLES.md +636 -0
  34. package/one/events/BEFORE_AFTER_COMPARISON.md +960 -0
  35. package/one/events/CONNECTIONS_DEMO.md +501 -0
  36. package/one/events/DELIVERABLES.md +432 -0
  37. package/one/events/DEMO-GROUPS-PAGE.md +392 -0
  38. package/one/events/DEMO-TESTING-SUMMARY.md +518 -0
  39. package/one/events/DEMO_COMPONENTS.md +487 -0
  40. package/one/events/DEMO_HOOKS_INDEX.md +334 -0
  41. package/one/events/DEMO_INFRASTRUCTURE.md +905 -0
  42. package/one/events/DEMO_INFRASTRUCTURE_SUMMARY.md +570 -0
  43. package/one/events/DEMO_INTEGRATION_CHECKLIST.md +431 -0
  44. package/one/events/DEMO_QUICK_REFERENCE.md +441 -0
  45. package/one/events/DEMO_SETUP.md +476 -0
  46. package/one/events/EFFECT_TS_API_PATTERN.md +478 -0
  47. package/one/events/GROUPS_DEMO_IMPLEMENTATION.md +414 -0
  48. package/one/events/HOOKS-DEMO.md +441 -0
  49. package/one/events/ONTOLOGY-HOOKS-README.md +700 -0
  50. package/one/events/ONTOLOGY-INTEGRATION-MANIFEST.md +365 -0
  51. package/one/events/QA-CHECKLIST.md +674 -0
  52. package/one/events/QUICK-START-ONTOLOGY.md +408 -0
  53. package/one/events/SEARCH_DEMO_CODE_REFERENCE.md +639 -0
  54. package/one/events/SEARCH_DEMO_DELIVERY.md +415 -0
  55. package/one/events/SEARCH_DEMO_SUMMARY.md +303 -0
  56. package/one/events/SEARCH_DEMO_VISUAL_GUIDE.md +381 -0
  57. package/one/events/TEST-PLAN-INDEX.md +346 -0
  58. package/one/events/TEST-PLAN.md +1417 -0
  59. package/one/events/TESTING-DELIVERY.txt +372 -0
  60. package/one/events/TRANSITIONS-QUICK-START.md +141 -0
  61. package/one/events/TYPESCRIPT_FIXES.md +152 -0
  62. package/one/events/TYPESCRIPT_FIXES_COMPLETE.txt +412 -0
  63. package/one/events/TYPESCRIPT_FIXES_INDEX.md +341 -0
  64. package/one/events/VIEW-TRANSITIONS.md +428 -0
  65. package/one/events/backend-integration-tests.md +606 -0
  66. package/one/events/backend-structure-diagram.txt +393 -0
  67. package/one/events/backend-structure-summary.txt +269 -0
  68. package/one/events/cloudflare-pages-infrastructure-setup.md +264 -0
  69. package/one/events/convex-analysis-index.md +304 -0
  70. package/one/events/convex-structure-analysis.md +700 -0
  71. package/one/events/design-spec-complete.md +208 -0
  72. package/one/events/ontology-test-examples.md +562 -0
  73. package/one/events/phase1-backend-implementation-complete.md +518 -0
  74. package/one/events/test-dashboard.md +345 -0
  75. package/one/events/test-index.md +361 -0
  76. package/one/events/test-report-ontology.md +582 -0
  77. package/one/events/testing-summary.md +344 -0
  78. package/one/groups/features.md +2878 -0
  79. package/one/groups/strategy copy.md +869 -0
  80. package/one/knowledge/backend-api-reference.md +710 -0
  81. package/one/knowledge/documentation-summary.md +285 -0
  82. package/one/knowledge/lessons-learned.md +294 -4
  83. package/one/knowledge/ontology-visual-guide.md +360 -0
  84. package/one/knowledge/ontology.md +9 -17
  85. package/one/things/demo-accessibility-animations.md +999 -0
  86. package/one/things/demo-components.md +1304 -0
  87. package/one/things/demo-design-summary.md +629 -0
  88. package/one/things/demo-design-system.md +919 -0
  89. package/one/things/demo-page-layouts.md +989 -0
  90. package/one/things/designs/accessibility-audit.md +790 -0
  91. package/one/things/designs/component-specifications.md +757 -0
  92. package/one/things/designs/design-overview.md +318 -0
  93. package/one/things/designs/design-tokens.md +414 -0
  94. package/one/things/designs/wireframes-dashboard.md +653 -0
  95. package/one/things/docs/api-requests.md +923 -0
  96. package/one/things/features/0 All Features.md +2 -0
  97. package/one/things/implementation/backend-guide.md +412 -0
  98. package/one/things/plans/2-backend-agnostic-frontend.md +11 -8
  99. package/one/things/plans/ai-elements.md +1259 -0
  100. package/one/things/plans/ai-integration.md +947 -0
  101. package/one/things/plans/ai-sdk.md +761 -0
  102. package/one/things/plans/app.md +1 -1
  103. package/one/things/plans/architecture-summary.md +283 -0
  104. package/one/things/plans/async-ai-agents.md +215 -0
  105. package/one/things/plans/backend-agnostic-frontend.md +11 -6
  106. package/one/things/plans/backend-cleanup-quickstart.md +346 -0
  107. package/one/things/plans/backend-ontology-conformance.md +416 -0
  108. package/one/things/plans/backend-status.md +541 -0
  109. package/one/things/plans/backend-structure.md +799 -0
  110. package/one/things/plans/backend-target-structure.md +438 -0
  111. package/one/things/plans/backend.md +1133 -0
  112. package/one/things/plans/better-auth-any-backend.md +11 -11
  113. package/one/things/plans/cli-updates-required.md +280 -0
  114. package/one/things/plans/complete-step-by-step.md +1302 -0
  115. package/one/things/plans/convex-agents.md +1005 -0
  116. package/one/things/plans/deployment-architecture.md +426 -0
  117. package/one/things/plans/development-plan.md +1220 -0
  118. package/one/things/plans/effect.md +808 -48
  119. package/one/things/plans/integrate-frontend-and-backend.md +579 -0
  120. package/one/things/plans/mcp-clear-context-prompt.md +60 -0
  121. package/one/things/plans/mcp-simple.md +228 -0
  122. package/one/things/plans/one.md +8 -7
  123. package/one/things/plans/ontology-6-dimensions.md +20 -14
  124. package/one/things/plans/quick-wins.md +1273 -0
  125. package/one/things/plans/readme-backend-cleanup.md +361 -0
  126. package/one/things/plans/separate-demo.md +830 -0
  127. package/one/things/plans/separate.md +3 -3
  128. package/one/things/plans/sequence.md +1897 -0
  129. package/one/things/plans/sync-checklist.md +321 -0
  130. package/one/things/plans/unified-implementation-plan.md +3 -3
  131. package/one/things/plans/update-demos.md +513 -0
  132. package/package.json +1 -1
  133. package/.claude/agents/backend-specialist.md +0 -169
  134. package/.claude/agents/designer.md +0 -216
  135. package/.claude/agents/frontend-specialist.md +0 -236
  136. package/.claude/commands/done.md +0 -35
  137. package/.claude/commands/infer.md +0 -138
  138. package/.claude/commands/next.md +0 -53
  139. package/.claude/commands/one copy.md +0 -565
  140. package/.claude/commands/one-template.md +0 -106
  141. package/.claude/commands/one-v1.md +0 -609
  142. package/.claude/hooks/__pycache__/knowledge-post.cpython-313.pyc +0 -0
  143. package/.claude/hooks/__pycache__/knowledge-pre.cpython-313.pyc +0 -0
  144. package/.claude/hooks/__pycache__/todo.cpython-313.pyc +0 -0
  145. package/one/groups/nine-padel-customers.md +0 -138
  146. package/one/groups/nine-padel-data-structure.md +0 -167
  147. package/one/groups/nine-padel-ontology-specification.md +0 -359
  148. package/one/groups/nine-padel-ontology.md +0 -143
  149. package/one/groups/nine-padel-strategy.md +0 -234
  150. package/one/groups/nine-padel.md +0 -211
  151. package/one/groups/nine-padle-contents.baked.md +0 -1252
  152. package/one/groups/nine-padle-contents.md +0 -6
  153. package/one/things/features/1-1-agent-prompts/design.md +0 -470
  154. package/one/things/features/1-1-agent-prompts/tests.md +0 -264
  155. package/one/things/features/1-2-yaml-orchestrator/design.md +0 -497
  156. package/one/things/features/1-2-yaml-orchestrator/tests.md +0 -227
  157. package/one/things/features/1-3-event-coordination/design.md +0 -544
  158. package/one/things/features/1-3-event-coordination/tests.md +0 -223
  159. package/one/things/features/1-4-knowledge-management/design.md +0 -609
  160. package/one/things/features/1-4-knowledge-management/tests.md +0 -195
  161. package/one/things/features/1-5-quality-loops/design.md +0 -797
  162. package/one/things/features/1-5-quality-loops/tests.md +0 -212
  163. package/one/things/features/1-6-numbering-structure/design.md +0 -610
  164. package/one/things/features/1-6-numbering-structure/tests.md +0 -213
  165. package/one/things/features/dataprovider-interface/1-tests.md +0 -1522
@@ -0,0 +1,875 @@
1
+ # External Integration Examples
2
+
3
+ **Purpose:** Reference implementations for integrating ONE Platform with external systems
4
+ **Status:** Template patterns (implement when needed)
5
+ **Last Updated:** 2025-10-25
6
+
7
+ ---
8
+
9
+ ## Overview
10
+
11
+ This document provides copy-paste patterns for common external integrations. All patterns follow the 6-dimension ontology and use protocol metadata where applicable.
12
+
13
+ **Integration Categories:**
14
+
15
+ 1. **Protocol-Based** - A2A, ACP, AP2, X402, AG-UI
16
+ 2. **External Agents** - ElizaOS, ChatGPT plugins, custom agents
17
+ 3. **External Workflows** - n8n, Zapier, Make automation
18
+ 4. **External APIs** - Third-party services (Stripe, OpenAI, etc.)
19
+
20
+ ---
21
+
22
+ ## Pattern 1: A2A Protocol - Delegate Task to External Agent
23
+
24
+ **Use Case:** ONE agent delegates a task to an external ElizaOS agent
25
+
26
+ ```typescript
27
+ // backend/convex/mutations/protocols/a2a.ts
28
+ import { mutation } from "../../_generated/server";
29
+ import { v } from "convex/values";
30
+
31
+ /**
32
+ * Delegate task to external agent via A2A protocol
33
+ *
34
+ * Creates:
35
+ * - external_agent entity (if doesn't exist)
36
+ * - delegated connection (oneAgent → externalAgent)
37
+ * - task_event with protocol: "a2a"
38
+ */
39
+ export const delegateTask = mutation({
40
+ args: {
41
+ groupId: v.id("groups"),
42
+ oneAgentId: v.id("entities"),
43
+ externalPlatform: v.string(), // "elizaos", "chatgpt", etc.
44
+ externalAgentId: v.string(),
45
+ task: v.string(),
46
+ parameters: v.any()
47
+ },
48
+ handler: async (ctx, args) => {
49
+ // 1. Get or create external_agent entity
50
+ let externalAgent = await ctx.db
51
+ .query("entities")
52
+ .withIndex("group_type", q =>
53
+ q.eq("groupId", args.groupId).eq("type", "external_agent")
54
+ )
55
+ .filter(q =>
56
+ q.and(
57
+ q.eq(q.field("properties.platform"), args.externalPlatform),
58
+ q.eq(q.field("properties.agentId"), args.externalAgentId)
59
+ )
60
+ )
61
+ .first();
62
+
63
+ if (!externalAgent) {
64
+ const externalAgentEntityId = await ctx.db.insert("entities", {
65
+ groupId: args.groupId,
66
+ type: "external_agent",
67
+ name: `${args.externalPlatform} Agent (${args.externalAgentId})`,
68
+ properties: {
69
+ platform: args.externalPlatform,
70
+ agentId: args.externalAgentId,
71
+ protocol: "a2a",
72
+ capabilities: [], // To be filled later
73
+ status: "active"
74
+ },
75
+ status: "active",
76
+ createdAt: Date.now(),
77
+ updatedAt: Date.now()
78
+ });
79
+
80
+ externalAgent = await ctx.db.get(externalAgentEntityId);
81
+ }
82
+
83
+ if (!externalAgent) {
84
+ throw new Error("Failed to create external agent entity");
85
+ }
86
+
87
+ // 2. Create delegated connection
88
+ const connectionId = await ctx.db.insert("connections", {
89
+ groupId: args.groupId,
90
+ fromEntityId: args.oneAgentId,
91
+ toEntityId: externalAgent._id,
92
+ relationshipType: "delegated",
93
+ metadata: {
94
+ protocol: "a2a",
95
+ task: args.task,
96
+ parameters: args.parameters,
97
+ status: "pending",
98
+ delegatedAt: Date.now()
99
+ },
100
+ createdAt: Date.now()
101
+ });
102
+
103
+ // 3. Log task_event
104
+ await ctx.db.insert("events", {
105
+ groupId: args.groupId,
106
+ type: "task_event",
107
+ actorId: args.oneAgentId,
108
+ targetId: externalAgent._id,
109
+ timestamp: Date.now(),
110
+ metadata: {
111
+ action: "delegated",
112
+ protocol: "a2a",
113
+ task: args.task,
114
+ connectionId: connectionId,
115
+ parameters: args.parameters
116
+ }
117
+ });
118
+
119
+ // 4. Call external agent API
120
+ try {
121
+ const response = await fetch(
122
+ `https://agent.${args.externalPlatform}.com/api/tasks`,
123
+ {
124
+ method: "POST",
125
+ headers: {
126
+ "Content-Type": "application/json",
127
+ "Authorization": `Bearer ${process.env[`${args.externalPlatform.toUpperCase()}_API_KEY`]}`
128
+ },
129
+ body: JSON.stringify({
130
+ task: args.task,
131
+ parameters: args.parameters,
132
+ callbackUrl: `${process.env.CONVEX_SITE_URL}/api/a2a/callback`
133
+ })
134
+ }
135
+ );
136
+
137
+ if (!response.ok) {
138
+ throw new Error(`External agent API error: ${response.statusText}`);
139
+ }
140
+
141
+ const result = await response.json();
142
+
143
+ // Update connection with external task ID
144
+ await ctx.db.patch(connectionId, {
145
+ metadata: {
146
+ ...externalAgent.properties,
147
+ externalTaskId: result.taskId,
148
+ status: "in_progress"
149
+ }
150
+ });
151
+
152
+ return {
153
+ success: true,
154
+ connectionId,
155
+ externalTaskId: result.taskId
156
+ };
157
+ } catch (error) {
158
+ // Log failure event
159
+ await ctx.db.insert("events", {
160
+ groupId: args.groupId,
161
+ type: "task_event",
162
+ actorId: args.oneAgentId,
163
+ targetId: externalAgent._id,
164
+ timestamp: Date.now(),
165
+ metadata: {
166
+ action: "delegation_failed",
167
+ protocol: "a2a",
168
+ error: error instanceof Error ? error.message : "Unknown error"
169
+ }
170
+ });
171
+
172
+ throw error;
173
+ }
174
+ }
175
+ });
176
+
177
+ /**
178
+ * Handle A2A callback from external agent
179
+ *
180
+ * Called by external agent when task is complete
181
+ */
182
+ export const handleCallback = mutation({
183
+ args: {
184
+ connectionId: v.id("connections"),
185
+ status: v.union(v.literal("completed"), v.literal("failed")),
186
+ result: v.any()
187
+ },
188
+ handler: async (ctx, args) => {
189
+ const connection = await ctx.db.get(args.connectionId);
190
+ if (!connection) {
191
+ throw new Error("Connection not found");
192
+ }
193
+
194
+ // Update connection status
195
+ await ctx.db.patch(args.connectionId, {
196
+ metadata: {
197
+ ...connection.metadata,
198
+ status: args.status,
199
+ result: args.result,
200
+ completedAt: Date.now()
201
+ }
202
+ });
203
+
204
+ // Log completion event
205
+ await ctx.db.insert("events", {
206
+ groupId: connection.groupId,
207
+ type: "task_event",
208
+ actorId: connection.toEntityId,
209
+ targetId: connection.fromEntityId,
210
+ timestamp: Date.now(),
211
+ metadata: {
212
+ action: args.status === "completed" ? "task_completed" : "task_failed",
213
+ protocol: "a2a",
214
+ connectionId: args.connectionId,
215
+ result: args.result
216
+ }
217
+ });
218
+
219
+ return { success: true };
220
+ }
221
+ });
222
+ ```
223
+
224
+ **Frontend Usage:**
225
+
226
+ ```tsx
227
+ // web/src/components/agents/TaskDelegation.tsx
228
+ import { useMutation } from "convex/react";
229
+ import { api } from "@/convex/_generated/api";
230
+ import { Button } from "@/components/ui/button";
231
+
232
+ export function TaskDelegation({ agentId, groupId }) {
233
+ const delegateTask = useMutation(api.mutations.protocols.a2a.delegateTask);
234
+
235
+ const handleDelegate = async () => {
236
+ const result = await delegateTask({
237
+ groupId,
238
+ oneAgentId: agentId,
239
+ externalPlatform: "elizaos",
240
+ externalAgentId: "agent_research_123",
241
+ task: "research_market_trends",
242
+ parameters: {
243
+ industry: "fitness",
244
+ timeframe: "last_30_days",
245
+ sources: ["google_trends", "social_media"]
246
+ }
247
+ });
248
+
249
+ console.log("Task delegated:", result);
250
+ };
251
+
252
+ return (
253
+ <Button onClick={handleDelegate}>
254
+ Delegate Research Task to ElizaOS
255
+ </Button>
256
+ );
257
+ }
258
+ ```
259
+
260
+ ---
261
+
262
+ ## Pattern 2: ACP Protocol - Agent-Initiated Purchase
263
+
264
+ **Use Case:** External agent (ChatGPT, Claude) purchases a product
265
+
266
+ ```typescript
267
+ // backend/convex/mutations/protocols/acp.ts
268
+ import { mutation } from "../../_generated/server";
269
+ import { v } from "convex/values";
270
+
271
+ /**
272
+ * Handle agent purchase via ACP protocol
273
+ *
274
+ * Creates:
275
+ * - external_agent entity (if doesn't exist)
276
+ * - transacted connection (agent → product)
277
+ * - commerce_event with protocol: "acp"
278
+ */
279
+ export const handleAgentPurchase = mutation({
280
+ args: {
281
+ productId: v.id("entities"),
282
+ agentPlatform: v.string(), // "chatgpt", "claude", etc.
283
+ agentUserId: v.string(),
284
+ paymentMethod: v.string(),
285
+ paymentDetails: v.any()
286
+ },
287
+ handler: async (ctx, args) => {
288
+ // 1. Get product (must be type: "product")
289
+ const product = await ctx.db.get(args.productId);
290
+ if (!product || product.type !== "product") {
291
+ throw new Error("Invalid product");
292
+ }
293
+
294
+ // 2. Get or create external_agent entity
295
+ let agentThing = await ctx.db
296
+ .query("entities")
297
+ .withIndex("group_type", q =>
298
+ q.eq("groupId", product.groupId).eq("type", "external_agent")
299
+ )
300
+ .filter(q =>
301
+ q.and(
302
+ q.eq(q.field("properties.platform"), args.agentPlatform),
303
+ q.eq(q.field("properties.userId"), args.agentUserId)
304
+ )
305
+ )
306
+ .first();
307
+
308
+ if (!agentThing) {
309
+ const agentEntityId = await ctx.db.insert("entities", {
310
+ groupId: product.groupId,
311
+ type: "external_agent",
312
+ name: `${args.agentPlatform} Agent (${args.agentUserId})`,
313
+ properties: {
314
+ platform: args.agentPlatform,
315
+ userId: args.agentUserId,
316
+ protocol: "acp"
317
+ },
318
+ status: "active",
319
+ createdAt: Date.now(),
320
+ updatedAt: Date.now()
321
+ });
322
+
323
+ agentThing = await ctx.db.get(agentEntityId);
324
+ }
325
+
326
+ if (!agentThing) {
327
+ throw new Error("Failed to create agent entity");
328
+ }
329
+
330
+ // 3. Log commerce event (purchase initiated)
331
+ const eventId = await ctx.db.insert("events", {
332
+ groupId: product.groupId,
333
+ type: "commerce_event",
334
+ actorId: agentThing._id,
335
+ targetId: product._id,
336
+ timestamp: Date.now(),
337
+ metadata: {
338
+ protocol: "acp",
339
+ eventType: "purchase_initiated",
340
+ agentPlatform: args.agentPlatform,
341
+ productId: args.productId,
342
+ amount: product.properties.price,
343
+ currency: product.properties.currency || "USD"
344
+ }
345
+ });
346
+
347
+ // 4. Process payment (integrate with Stripe, etc.)
348
+ try {
349
+ const paymentResult = await processPayment({
350
+ amount: product.properties.price,
351
+ currency: product.properties.currency || "USD",
352
+ method: args.paymentMethod,
353
+ details: args.paymentDetails
354
+ });
355
+
356
+ // 5. Create transacted connection
357
+ await ctx.db.insert("connections", {
358
+ groupId: product.groupId,
359
+ fromEntityId: agentThing._id,
360
+ toEntityId: product._id,
361
+ relationshipType: "transacted",
362
+ metadata: {
363
+ protocol: "acp",
364
+ transactionType: "purchase",
365
+ amount: product.properties.price,
366
+ currency: product.properties.currency || "USD",
367
+ paymentId: paymentResult.id,
368
+ status: "completed"
369
+ },
370
+ createdAt: Date.now()
371
+ });
372
+
373
+ // 6. Log completion event
374
+ await ctx.db.insert("events", {
375
+ groupId: product.groupId,
376
+ type: "commerce_event",
377
+ actorId: agentThing._id,
378
+ targetId: product._id,
379
+ timestamp: Date.now(),
380
+ metadata: {
381
+ protocol: "acp",
382
+ eventType: "purchase_completed",
383
+ paymentId: paymentResult.id,
384
+ transactionId: paymentResult.transactionId
385
+ }
386
+ });
387
+
388
+ return {
389
+ success: true,
390
+ transactionId: paymentResult.transactionId,
391
+ paymentId: paymentResult.id
392
+ };
393
+ } catch (error) {
394
+ // Log failure event
395
+ await ctx.db.insert("events", {
396
+ groupId: product.groupId,
397
+ type: "commerce_event",
398
+ actorId: agentThing._id,
399
+ targetId: product._id,
400
+ timestamp: Date.now(),
401
+ metadata: {
402
+ protocol: "acp",
403
+ eventType: "purchase_failed",
404
+ error: error instanceof Error ? error.message : "Unknown error"
405
+ }
406
+ });
407
+
408
+ throw error;
409
+ }
410
+ }
411
+ });
412
+
413
+ // Helper function (integrate with your payment provider)
414
+ async function processPayment(args: {
415
+ amount: number;
416
+ currency: string;
417
+ method: string;
418
+ details: any;
419
+ }) {
420
+ // Stripe integration example
421
+ // const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
422
+ // const paymentIntent = await stripe.paymentIntents.create({ ... });
423
+ // return { id: paymentIntent.id, transactionId: paymentIntent.id };
424
+
425
+ return {
426
+ id: `pay_${Date.now()}`,
427
+ transactionId: `txn_${Date.now()}`
428
+ };
429
+ }
430
+ ```
431
+
432
+ **REST API Endpoint (when Hono is implemented):**
433
+
434
+ ```typescript
435
+ // backend/convex/http.ts (Hono)
436
+ app.post("/api/protocols/acp/purchase", async (c) => {
437
+ const body = await c.req.json();
438
+
439
+ const result = await c.env.ctx.runMutation(
440
+ api.mutations.protocols.acp.handleAgentPurchase,
441
+ {
442
+ productId: body.productId,
443
+ agentPlatform: body.agentPlatform,
444
+ agentUserId: body.agentUserId,
445
+ paymentMethod: body.paymentMethod,
446
+ paymentDetails: body.paymentDetails
447
+ }
448
+ );
449
+
450
+ return c.json(result);
451
+ });
452
+ ```
453
+
454
+ ---
455
+
456
+ ## Pattern 3: X402 Protocol - HTTP Micropayments
457
+
458
+ **Use Case:** Verify blockchain payment before granting API access
459
+
460
+ ```typescript
461
+ // backend/convex/mutations/protocols/x402.ts
462
+ import { mutation } from "../../_generated/server";
463
+ import { v } from "convex/values";
464
+
465
+ /**
466
+ * Verify X402 payment and grant API access
467
+ *
468
+ * Creates:
469
+ * - payment_event with protocol: "x402"
470
+ * - transacted connection (user → resource)
471
+ */
472
+ export const verifyPayment = mutation({
473
+ args: {
474
+ groupId: v.id("groups"),
475
+ userId: v.id("entities"),
476
+ resourceId: v.id("entities"),
477
+ payment: v.object({
478
+ scheme: v.union(v.literal("permit"), v.literal("transfer")),
479
+ network: v.string(), // "base", "ethereum", etc.
480
+ amount: v.string(),
481
+ signature: v.string(),
482
+ permitData: v.optional(v.any())
483
+ })
484
+ },
485
+ handler: async (ctx, args) => {
486
+ // 1. Log payment request event
487
+ const requestEventId = await ctx.db.insert("events", {
488
+ groupId: args.groupId,
489
+ type: "payment_event",
490
+ actorId: args.userId,
491
+ targetId: args.resourceId,
492
+ timestamp: Date.now(),
493
+ metadata: {
494
+ protocol: "x402",
495
+ status: "requested",
496
+ scheme: args.payment.scheme,
497
+ network: args.payment.network,
498
+ amount: args.payment.amount
499
+ }
500
+ });
501
+
502
+ // 2. Verify payment on blockchain
503
+ try {
504
+ const isValid = await verifyX402Payment(args.payment);
505
+ if (!isValid) {
506
+ throw new Error("Invalid X402 payment signature");
507
+ }
508
+
509
+ // 3. Log payment verified event
510
+ await ctx.db.insert("events", {
511
+ groupId: args.groupId,
512
+ type: "payment_event",
513
+ actorId: args.userId,
514
+ targetId: args.resourceId,
515
+ timestamp: Date.now(),
516
+ metadata: {
517
+ protocol: "x402",
518
+ status: "verified",
519
+ requestEventId: requestEventId,
520
+ transactionHash: args.payment.signature
521
+ }
522
+ });
523
+
524
+ // 4. Create transacted connection
525
+ await ctx.db.insert("connections", {
526
+ groupId: args.groupId,
527
+ fromEntityId: args.userId,
528
+ toEntityId: args.resourceId,
529
+ relationshipType: "transacted",
530
+ metadata: {
531
+ protocol: "x402",
532
+ transactionType: "micropayment",
533
+ amount: args.payment.amount,
534
+ network: args.payment.network,
535
+ transactionHash: args.payment.signature
536
+ },
537
+ createdAt: Date.now()
538
+ });
539
+
540
+ // 5. Grant access (return API token or execute request)
541
+ return {
542
+ accessGranted: true,
543
+ token: generateApiToken(),
544
+ expiresIn: 3600 // 1 hour
545
+ };
546
+ } catch (error) {
547
+ // Log failure event
548
+ await ctx.db.insert("events", {
549
+ groupId: args.groupId,
550
+ type: "payment_event",
551
+ actorId: args.userId,
552
+ targetId: args.resourceId,
553
+ timestamp: Date.now(),
554
+ metadata: {
555
+ protocol: "x402",
556
+ status: "verification_failed",
557
+ error: error instanceof Error ? error.message : "Unknown error"
558
+ }
559
+ });
560
+
561
+ throw error;
562
+ }
563
+ }
564
+ });
565
+
566
+ // Helper functions
567
+ async function verifyX402Payment(payment: any): Promise<boolean> {
568
+ // Implement blockchain verification logic
569
+ // Example: Verify permit signature with viem/ethers
570
+ return true; // Placeholder
571
+ }
572
+
573
+ function generateApiToken(): string {
574
+ // Generate temporary API token
575
+ return `token_${Date.now()}_${Math.random().toString(36).slice(2)}`;
576
+ }
577
+ ```
578
+
579
+ ---
580
+
581
+ ## Pattern 4: External Workflow Integration (n8n, Zapier)
582
+
583
+ **Use Case:** Trigger n8n workflow when event occurs
584
+
585
+ ```typescript
586
+ // backend/convex/mutations/integrations/n8n.ts
587
+ import { mutation } from "../../_generated/server";
588
+ import { v } from "convex/values";
589
+
590
+ /**
591
+ * Trigger n8n workflow
592
+ *
593
+ * Creates:
594
+ * - external_workflow entity (if doesn't exist)
595
+ * - workflow_triggered event
596
+ */
597
+ export const triggerWorkflow = mutation({
598
+ args: {
599
+ groupId: v.id("groups"),
600
+ workflowName: v.string(),
601
+ webhookUrl: v.string(),
602
+ payload: v.any()
603
+ },
604
+ handler: async (ctx, args) => {
605
+ // 1. Get or create external_workflow entity
606
+ let workflow = await ctx.db
607
+ .query("entities")
608
+ .withIndex("group_type", q =>
609
+ q.eq("groupId", args.groupId).eq("type", "external_workflow")
610
+ )
611
+ .filter(q => q.eq(q.field("name"), args.workflowName))
612
+ .first();
613
+
614
+ if (!workflow) {
615
+ const workflowId = await ctx.db.insert("entities", {
616
+ groupId: args.groupId,
617
+ type: "external_workflow",
618
+ name: args.workflowName,
619
+ properties: {
620
+ platform: "n8n",
621
+ webhookUrl: args.webhookUrl
622
+ },
623
+ status: "active",
624
+ createdAt: Date.now(),
625
+ updatedAt: Date.now()
626
+ });
627
+
628
+ workflow = await ctx.db.get(workflowId);
629
+ }
630
+
631
+ if (!workflow) {
632
+ throw new Error("Failed to create workflow entity");
633
+ }
634
+
635
+ // 2. Trigger webhook
636
+ try {
637
+ const response = await fetch(args.webhookUrl, {
638
+ method: "POST",
639
+ headers: { "Content-Type": "application/json" },
640
+ body: JSON.stringify(args.payload)
641
+ });
642
+
643
+ if (!response.ok) {
644
+ throw new Error(`Webhook failed: ${response.statusText}`);
645
+ }
646
+
647
+ // 3. Log workflow_triggered event
648
+ await ctx.db.insert("events", {
649
+ groupId: args.groupId,
650
+ type: "workflow_event",
651
+ actorId: workflow._id,
652
+ timestamp: Date.now(),
653
+ metadata: {
654
+ action: "triggered",
655
+ workflow: args.workflowName,
656
+ platform: "n8n",
657
+ payload: args.payload,
658
+ status: "success"
659
+ }
660
+ });
661
+
662
+ return { success: true };
663
+ } catch (error) {
664
+ // Log failure event
665
+ await ctx.db.insert("events", {
666
+ groupId: args.groupId,
667
+ type: "workflow_event",
668
+ actorId: workflow._id,
669
+ timestamp: Date.now(),
670
+ metadata: {
671
+ action: "trigger_failed",
672
+ workflow: args.workflowName,
673
+ error: error instanceof Error ? error.message : "Unknown error"
674
+ }
675
+ });
676
+
677
+ throw error;
678
+ }
679
+ }
680
+ });
681
+ ```
682
+
683
+ ---
684
+
685
+ ## Pattern 5: External API Integration (Stripe, OpenAI)
686
+
687
+ **Use Case:** Call external API service (Stripe payment processing)
688
+
689
+ ```typescript
690
+ // backend/convex/mutations/integrations/stripe.ts
691
+ import { mutation } from "../../_generated/server";
692
+ import { v } from "convex/values";
693
+
694
+ /**
695
+ * Process payment via Stripe
696
+ *
697
+ * Creates:
698
+ * - transacted connection (user → product)
699
+ * - payment_event
700
+ */
701
+ export const processPayment = mutation({
702
+ args: {
703
+ groupId: v.id("groups"),
704
+ userId: v.id("entities"),
705
+ productId: v.id("entities"),
706
+ amount: v.number(),
707
+ currency: v.string(),
708
+ paymentMethodId: v.string()
709
+ },
710
+ handler: async (ctx, args) => {
711
+ // Get product
712
+ const product = await ctx.db.get(args.productId);
713
+ if (!product) {
714
+ throw new Error("Product not found");
715
+ }
716
+
717
+ // Log payment initiated
718
+ await ctx.db.insert("events", {
719
+ groupId: args.groupId,
720
+ type: "payment_event",
721
+ actorId: args.userId,
722
+ targetId: args.productId,
723
+ timestamp: Date.now(),
724
+ metadata: {
725
+ action: "initiated",
726
+ provider: "stripe",
727
+ amount: args.amount,
728
+ currency: args.currency
729
+ }
730
+ });
731
+
732
+ try {
733
+ // Call Stripe API
734
+ const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
735
+ const paymentIntent = await stripe.paymentIntents.create({
736
+ amount: Math.round(args.amount * 100), // Convert to cents
737
+ currency: args.currency,
738
+ payment_method: args.paymentMethodId,
739
+ confirm: true
740
+ });
741
+
742
+ // Create transacted connection
743
+ await ctx.db.insert("connections", {
744
+ groupId: args.groupId,
745
+ fromEntityId: args.userId,
746
+ toEntityId: args.productId,
747
+ relationshipType: "transacted",
748
+ metadata: {
749
+ provider: "stripe",
750
+ paymentIntentId: paymentIntent.id,
751
+ amount: args.amount,
752
+ currency: args.currency,
753
+ status: paymentIntent.status
754
+ },
755
+ createdAt: Date.now()
756
+ });
757
+
758
+ // Log success event
759
+ await ctx.db.insert("events", {
760
+ groupId: args.groupId,
761
+ type: "payment_event",
762
+ actorId: args.userId,
763
+ targetId: args.productId,
764
+ timestamp: Date.now(),
765
+ metadata: {
766
+ action: "completed",
767
+ provider: "stripe",
768
+ paymentIntentId: paymentIntent.id,
769
+ amount: args.amount,
770
+ currency: args.currency
771
+ }
772
+ });
773
+
774
+ return {
775
+ success: true,
776
+ paymentIntentId: paymentIntent.id,
777
+ status: paymentIntent.status
778
+ };
779
+ } catch (error) {
780
+ // Log failure event
781
+ await ctx.db.insert("events", {
782
+ groupId: args.groupId,
783
+ type: "payment_event",
784
+ actorId: args.userId,
785
+ targetId: args.productId,
786
+ timestamp: Date.now(),
787
+ metadata: {
788
+ action: "failed",
789
+ provider: "stripe",
790
+ error: error instanceof Error ? error.message : "Unknown error"
791
+ }
792
+ });
793
+
794
+ throw error;
795
+ }
796
+ }
797
+ });
798
+ ```
799
+
800
+ ---
801
+
802
+ ## Integration Testing Pattern
803
+
804
+ ```typescript
805
+ // web/test/integration/external-api.test.ts
806
+ import { describe, it, expect } from "vitest";
807
+ import { ConvexHttpClient } from "convex/browser";
808
+ import { api } from "../../../backend/convex/_generated/api";
809
+
810
+ const convex = new ConvexHttpClient(process.env.PUBLIC_CONVEX_URL!);
811
+
812
+ describe("External Integration: A2A Protocol", () => {
813
+ it("should delegate task to external agent", async () => {
814
+ const result = await convex.mutation(
815
+ api.mutations.protocols.a2a.delegateTask,
816
+ {
817
+ groupId: testGroupId,
818
+ oneAgentId: testAgentId,
819
+ externalPlatform: "elizaos",
820
+ externalAgentId: "agent_research_123",
821
+ task: "research_market_trends",
822
+ parameters: {
823
+ industry: "fitness",
824
+ timeframe: "last_30_days"
825
+ }
826
+ }
827
+ );
828
+
829
+ expect(result.success).toBe(true);
830
+ expect(result.connectionId).toBeDefined();
831
+ expect(result.externalTaskId).toBeDefined();
832
+ });
833
+
834
+ it("should log protocol metadata in events", async () => {
835
+ const events = await convex.query(api.queries.events.list, {
836
+ groupId: testGroupId
837
+ });
838
+
839
+ const a2aEvent = events.find(e =>
840
+ e.metadata?.protocol === "a2a" &&
841
+ e.metadata?.action === "delegated"
842
+ );
843
+
844
+ expect(a2aEvent).toBeDefined();
845
+ expect(a2aEvent?.metadata?.task).toBe("research_market_trends");
846
+ });
847
+ });
848
+ ```
849
+
850
+ ---
851
+
852
+ ## Key Principles
853
+
854
+ 1. **Always create entities** - External systems represented as things (external_agent, external_workflow, external_connection)
855
+ 2. **Use protocol metadata** - Store protocol identifier in metadata.protocol field
856
+ 3. **Log all events** - Track every integration action with proper event types
857
+ 4. **Handle errors gracefully** - Log failure events, implement retries
858
+ 5. **Multi-tenant isolation** - All integrations scoped to groupId
859
+ 6. **Test end-to-end** - Verify complete flows including external API calls
860
+
861
+ ---
862
+
863
+ **Next Steps:**
864
+
865
+ 1. Implement Hono REST API layer (when external API needed)
866
+ 2. Add protocol-specific endpoints (A2A, ACP, X402, AP2)
867
+ 3. Create SDKs for external developers
868
+ 4. Write comprehensive integration tests
869
+ 5. Document API patterns for partners
870
+
871
+ **See Also:**
872
+
873
+ - `/Users/toc/Server/ONE/one/connections/integration-phase2.md` - Integration layer documentation
874
+ - `/Users/toc/Server/ONE/one/connections/protocols.md` - Protocol specifications
875
+ - `/Users/toc/Server/ONE/one/knowledge/specifications.md` - Protocol integration patterns