@wowok/agent-mcp 2.3.12 → 2.3.14

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 (93) hide show
  1. package/dist/harness/checkpoint.d.ts +8 -0
  2. package/dist/harness/checkpoint.js +129 -0
  3. package/dist/harness/index.d.ts +33 -0
  4. package/dist/harness/index.js +75 -0
  5. package/dist/harness/plan.d.ts +18 -0
  6. package/dist/harness/plan.js +252 -0
  7. package/dist/harness/recover.d.ts +17 -0
  8. package/dist/harness/recover.js +139 -0
  9. package/dist/harness/types.d.ts +137 -0
  10. package/dist/harness/types.js +1 -0
  11. package/dist/harness/verify.d.ts +42 -0
  12. package/dist/harness/verify.js +237 -0
  13. package/dist/index.js +134 -52
  14. package/dist/loop-engineering/aggregate.d.ts +50 -0
  15. package/dist/loop-engineering/aggregate.js +132 -0
  16. package/dist/loop-engineering/diagnose.d.ts +21 -0
  17. package/dist/loop-engineering/diagnose.js +179 -0
  18. package/dist/loop-engineering/improve.d.ts +26 -0
  19. package/dist/loop-engineering/improve.js +178 -0
  20. package/dist/loop-engineering/index.d.ts +4 -0
  21. package/dist/loop-engineering/index.js +4 -0
  22. package/dist/loop-engineering/pipeline.d.ts +17 -0
  23. package/dist/loop-engineering/pipeline.js +56 -0
  24. package/dist/mode-market/index.d.ts +3 -0
  25. package/dist/mode-market/index.js +3 -0
  26. package/dist/mode-market/registry.d.ts +53 -0
  27. package/dist/mode-market/registry.js +124 -0
  28. package/dist/mode-market/review.d.ts +27 -0
  29. package/dist/mode-market/review.js +214 -0
  30. package/dist/mode-market/submission.d.ts +25 -0
  31. package/dist/mode-market/submission.js +85 -0
  32. package/dist/schema/call/allocation.d.ts +40 -40
  33. package/dist/schema/call/arbitration.d.ts +90 -90
  34. package/dist/schema/call/base.d.ts +1054 -0
  35. package/dist/schema/call/base.js +100 -22
  36. package/dist/schema/call/bridge-handler.js +36 -18
  37. package/dist/schema/call/bridge.d.ts +115 -115
  38. package/dist/schema/call/handler.d.ts +2 -1
  39. package/dist/schema/call/handler.js +94 -3
  40. package/dist/schema/call/index.d.ts +1 -0
  41. package/dist/schema/call/index.js +1 -0
  42. package/dist/schema/call/machine.d.ts +144 -144
  43. package/dist/schema/call/order.d.ts +12 -12
  44. package/dist/schema/call/progress.d.ts +6 -6
  45. package/dist/schema/call/proof.js +7 -6
  46. package/dist/schema/call/reward.d.ts +6 -6
  47. package/dist/schema/call/semantic.d.ts +23 -0
  48. package/dist/schema/call/semantic.js +764 -0
  49. package/dist/schema/call/service.d.ts +142 -142
  50. package/dist/schema/call/treasury.d.ts +204 -204
  51. package/dist/schema/local/index.d.ts +113 -2
  52. package/dist/schema/local/index.js +11 -1
  53. package/dist/schema/messenger/index.d.ts +435 -95
  54. package/dist/schema/messenger/index.js +20 -8
  55. package/dist/schema/operations.d.ts +988 -495
  56. package/dist/schema/operations.js +14 -3
  57. package/dist/schema/query/index.d.ts +346 -342
  58. package/dist/schema/query/index.js +4 -1
  59. package/dist/schemas/account_operation.output.json +3 -0
  60. package/dist/schemas/account_operation.schema.json +1 -1
  61. package/dist/schemas/index.json +1 -1
  62. package/dist/schemas/local_info_operation.output.json +3 -0
  63. package/dist/schemas/local_mark_operation.output.json +3 -0
  64. package/dist/schemas/messenger_operation.output.json +21 -0
  65. package/dist/schemas/messenger_operation.schema.json +43 -8
  66. package/dist/schemas/onchain_events.output.json +3 -0
  67. package/dist/schemas/onchain_operations.output.json +464 -21
  68. package/dist/schemas/onchain_operations.schema.json +21 -17
  69. package/dist/schemas/onchain_operations_allocation.schema.json +11 -9
  70. package/dist/schemas/onchain_operations_arbitration.schema.json +11 -9
  71. package/dist/schemas/onchain_operations_contact.schema.json +11 -9
  72. package/dist/schemas/onchain_operations_demand.schema.json +11 -9
  73. package/dist/schemas/onchain_operations_gen_passport.schema.json +21 -17
  74. package/dist/schemas/onchain_operations_guard.schema.json +11 -9
  75. package/dist/schemas/onchain_operations_machine.schema.json +11 -9
  76. package/dist/schemas/onchain_operations_order.schema.json +11 -9
  77. package/dist/schemas/onchain_operations_payment.schema.json +11 -9
  78. package/dist/schemas/onchain_operations_permission.schema.json +11 -9
  79. package/dist/schemas/onchain_operations_personal.schema.json +11 -9
  80. package/dist/schemas/onchain_operations_progress.schema.json +11 -9
  81. package/dist/schemas/onchain_operations_repository.schema.json +11 -9
  82. package/dist/schemas/onchain_operations_reward.schema.json +11 -9
  83. package/dist/schemas/onchain_operations_service.schema.json +11 -9
  84. package/dist/schemas/onchain_operations_treasury.schema.json +11 -9
  85. package/dist/schemas/onchain_table_data.output.json +3 -0
  86. package/dist/schemas/query_toolkit.schema.json +5 -1
  87. package/dist/telemetry/index.d.ts +19 -0
  88. package/dist/telemetry/index.js +112 -0
  89. package/dist/telemetry/redact.d.ts +2 -0
  90. package/dist/telemetry/redact.js +23 -0
  91. package/dist/telemetry/storage.d.ts +8 -0
  92. package/dist/telemetry/storage.js +80 -0
  93. package/package.json +6 -3
@@ -0,0 +1,764 @@
1
+ const ERROR_RULES = [
2
+ {
3
+ patterns: [/insufficient\s*(gas|balance|coin|fund)/i, /ENOTENOUGH/i, /not\s*enough\s*(coin|gas|balance)/i, /gas\s*budget/i],
4
+ error_code: "insufficient_balance",
5
+ retryable: true,
6
+ recovery_hint: "Claim faucet tokens via account_operation (faucet) then retry the call",
7
+ },
8
+ {
9
+ patterns: [/network/i, /timeout/i, /ECONNRESET/i, /ETIMEDOUT/i, /RPC\s*(error|failed|unreachable)/i, /socket\s*hang\s*up/i, /fetch\s*failed/i],
10
+ error_code: "network_error",
11
+ retryable: true,
12
+ recovery_hint: "Retry the call; if it persists, switch RPC endpoint or check connectivity",
13
+ },
14
+ {
15
+ patterns: [/guard.*(reject|fail|denied)/i, /verification\s*failed/i, /submission.*(invalid|fail|required)/i, /passport.*(invalid|fail)/i, /move[._-]?abort.*guard/i],
16
+ error_code: "guard_rejected",
17
+ retryable: false,
18
+ recovery_hint: "Fill the Guard submission data (see the 'submission' field) and resubmit via call_with_submission",
19
+ },
20
+ {
21
+ patterns: [/already\s*publish/i, /immutable/i, /cannot\s*(modify|change|mutate)/i, /locked/i, /is\s*published/i],
22
+ error_code: "immutable_violation",
23
+ retryable: false,
24
+ recovery_hint: "Object is in an immutable state (e.g. Service already published). Recreate the object if a different config is needed",
25
+ },
26
+ {
27
+ patterns: [/permission/i, /unauthorized/i, /forbidden/i, /not\s*(the\s*)?owner/i, /access\s*denied/i],
28
+ error_code: "permission_denied",
29
+ retryable: false,
30
+ recovery_hint: "Use an account with the required permission, or pass permission_guard IDs via env.permission_guard",
31
+ },
32
+ {
33
+ patterns: [/not\s*found/i, /does\s*not\s*exist/i, /ENOTFOUND/i, /no\s*such\s*object/i, /unknown\s*object/i],
34
+ error_code: "object_not_found",
35
+ retryable: false,
36
+ recovery_hint: "Verify the object ID/name with query_toolkit; local_mark names are case-sensitive",
37
+ },
38
+ {
39
+ patterns: [/state\s*(conflict|mismatch)/i, /already\s*exist/i, /conflict/i, /duplicate/i, /version\s*mismatch/i],
40
+ error_code: "state_conflict",
41
+ retryable: false,
42
+ recovery_hint: "Object state conflicts with the operation. Query the current state with query_toolkit and adjust parameters",
43
+ },
44
+ {
45
+ patterns: [/invalid/i, /missing\s*(field|param|required)/i, /required/i, /expected/i, /malformed/i, /parse\s*error/i, /type\s*mismatch/i],
46
+ error_code: "invalid_parameter",
47
+ retryable: false,
48
+ recovery_hint: "Check parameter format against the tool schema; consult wowok-tools Skill for the operation's requirements",
49
+ },
50
+ ];
51
+ export function classifyError(errorMsg) {
52
+ if (!errorMsg) {
53
+ return { error_code: "unknown", retryable: false };
54
+ }
55
+ for (const rule of ERROR_RULES) {
56
+ if (rule.patterns.some((p) => p.test(errorMsg))) {
57
+ return {
58
+ error_code: rule.error_code,
59
+ retryable: rule.retryable,
60
+ recovery_hint: rule.recovery_hint,
61
+ };
62
+ }
63
+ }
64
+ return {
65
+ error_code: "unknown",
66
+ retryable: false,
67
+ recovery_hint: "Inspect the full error message; consult wowok-tools Skill for the operation's requirements",
68
+ };
69
+ }
70
+ const INTENT_RULES = [
71
+ { operation_type: "service", signals: (d) => d?.publish === true, intent: "publish_service", confidence: 0.95 },
72
+ { operation_type: "service", signals: (d) => d?.name && d?.publish === undefined, intent: "create_service", confidence: 0.9 },
73
+ { operation_type: "service", intent: "modify_service", confidence: 0.7 },
74
+ { operation_type: "machine", intent: "configure_machine", confidence: 0.9 },
75
+ { operation_type: "progress", intent: "update_progress", confidence: 0.9 },
76
+ { operation_type: "order", signals: (d) => !!d?.arb, intent: "apply_arbitration", confidence: 0.9 },
77
+ { operation_type: "order", intent: "manage_order", confidence: 0.85 },
78
+ { operation_type: "payment", intent: "send_payment", confidence: 0.95 },
79
+ { operation_type: "reward", intent: "manage_reward", confidence: 0.9 },
80
+ { operation_type: "demand", intent: "post_demand", confidence: 0.9 },
81
+ { operation_type: "treasury", intent: "manage_treasury", confidence: 0.9 },
82
+ { operation_type: "allocation", intent: "allocate_funds", confidence: 0.9 },
83
+ { operation_type: "permission", intent: "manage_permission", confidence: 0.9 },
84
+ { operation_type: "guard", intent: "configure_guard", confidence: 0.9 },
85
+ { operation_type: "arbitration", intent: "manage_arbitration", confidence: 0.9 },
86
+ { operation_type: "contact", intent: "manage_contact", confidence: 0.9 },
87
+ { operation_type: "repository", intent: "manage_repository", confidence: 0.9 },
88
+ { operation_type: "personal", intent: "manage_personal", confidence: 0.9 },
89
+ { operation_type: "gen_passport", intent: "generate_passport", confidence: 0.95 },
90
+ { operation_type: "bridge_cross_chain_wow_to_evm", intent: "cross_chain_wow_to_evm_deposit", confidence: 0.95 },
91
+ { operation_type: "bridge_cross_chain_evm_to_wow", intent: "cross_chain_evm_to_wow_deposit", confidence: 0.95 },
92
+ { operation_type: "bridge_claim_wow_to_evm", intent: "claim_wow_to_evm", confidence: 0.95 },
93
+ { operation_type: "bridge_withdraw", intent: "withdraw_from_evm_account", confidence: 0.9 },
94
+ { operation_type: "bridge_query_active_evm_account", intent: "query_bridge_status", confidence: 0.85 },
95
+ { operation_type: "bridge_query_supported_evm_chains", intent: "query_bridge_status", confidence: 0.85 },
96
+ { operation_type: "bridge_query_supported_tokens", intent: "query_bridge_status", confidence: 0.85 },
97
+ { operation_type: "bridge_query_transfer_list", intent: "query_bridge_status", confidence: 0.85 },
98
+ { operation_type: "bridge_query_transfer_status", intent: "query_bridge_status", confidence: 0.85 },
99
+ { operation_type: "bridge_manage_evm_rpc", intent: "manage_evm_rpc", confidence: 0.9 },
100
+ { operation_type: "account_new", intent: "create_account", confidence: 0.95 },
101
+ { operation_type: "account_faucet", intent: "claim_faucet", confidence: 0.95 },
102
+ { operation_type: "account_balance", intent: "query_balance", confidence: 0.9 },
103
+ { operation_type: "mark_add", intent: "create_local_mark", confidence: 0.9 },
104
+ { operation_type: "mark_remove", intent: "remove_local_mark", confidence: 0.9 },
105
+ { operation_type: "mark_query", intent: "query_local_marks", confidence: 0.9 },
106
+ { operation_type: "local_info", intent: "query_local_info", confidence: 0.9 },
107
+ { operation_type: "query_toolkit", intent: "query_objects", confidence: 0.85 },
108
+ { operation_type: "onchain_events", intent: "query_events", confidence: 0.85 },
109
+ { operation_type: "onchain_table_data", intent: "query_table_data", confidence: 0.85 },
110
+ ];
111
+ export function inferIntent(operation_type, data) {
112
+ const rules = INTENT_RULES.filter((r) => r.operation_type === operation_type);
113
+ const signaled = rules.find((r) => r.signals && r.signals(data));
114
+ if (signaled)
115
+ return signaled.intent;
116
+ const fallback = rules.find((r) => !r.signals);
117
+ return fallback?.intent ?? operation_type;
118
+ }
119
+ function inferStatus(safeResult) {
120
+ if (safeResult && typeof safeResult === "object" && "error" in safeResult)
121
+ return "failed";
122
+ if (safeResult && typeof safeResult === "object" && "digest" in safeResult) {
123
+ return safeResult?.effects?.status?.status === "success" ? "success" : "failed";
124
+ }
125
+ return "success";
126
+ }
127
+ const OBJECT_TYPE_TO_ROLE = {
128
+ service: "Service",
129
+ machine: "Machine",
130
+ progress: "Progress",
131
+ permission: "Permission",
132
+ guard: "Guard",
133
+ order: "Order",
134
+ arb: "Arbitration",
135
+ arbcase: "ArbCase",
136
+ messenger: "Messenger",
137
+ contact: "Contact",
138
+ demand: "Demand",
139
+ reward: "Reward",
140
+ personal: "Personal",
141
+ repository: "Repository",
142
+ treasury: "Treasury",
143
+ discount: "Discount",
144
+ allocation: "Allocation",
145
+ };
146
+ export function objectTypeToRole(objectType) {
147
+ if (!objectType)
148
+ return "Other";
149
+ const base = objectType.replace(/<.*>/, "").trim();
150
+ const segments = base.split("::");
151
+ const last = (segments[segments.length - 1] || "").toLowerCase();
152
+ return OBJECT_TYPE_TO_ROLE[last] ?? "Other";
153
+ }
154
+ export function tagObjectRoles(objectChanges) {
155
+ if (!Array.isArray(objectChanges))
156
+ return [];
157
+ return objectChanges
158
+ .filter((c) => c && (c.objectId || c.object?.objectId))
159
+ .map((c) => {
160
+ const id = c.objectId || c.object?.objectId;
161
+ const type = c.objectType || c.object?.objectType || "";
162
+ const changeType = c.type || "";
163
+ return {
164
+ id,
165
+ role: objectTypeToRole(type),
166
+ immutable: type.includes("Service") && changeType === "published",
167
+ };
168
+ });
169
+ }
170
+ const GAS_COIN_PATTERNS = [/::sui::SUI$/i, /::wow::WOW$/i];
171
+ const SMALL_AMOUNT_THRESHOLD = BigInt(1_000_000);
172
+ function isNegative(amount) {
173
+ return String(amount ?? "0").startsWith("-");
174
+ }
175
+ function hasEventMatch(events, pattern) {
176
+ if (!Array.isArray(events))
177
+ return false;
178
+ return events.some((e) => pattern.test(String(e?.type ?? e?.event_type ?? "")));
179
+ }
180
+ function isGasCoin(coinType) {
181
+ if (!coinType)
182
+ return false;
183
+ return GAS_COIN_PATTERNS.some((p) => p.test(coinType));
184
+ }
185
+ function absAmount(amount) {
186
+ try {
187
+ return BigInt(String(amount).replace("-", "") || "0");
188
+ }
189
+ catch {
190
+ return BigInt(0);
191
+ }
192
+ }
193
+ const FUND_ROLE_RULES = [
194
+ {
195
+ when: (ctx) => hasEventMatch(ctx.events, /order::OrderPaidEvent/i),
196
+ role: "payment",
197
+ confidence: 0.95,
198
+ },
199
+ {
200
+ when: (ctx) => hasEventMatch(ctx.events, /order::OrderRefundedEvent|order::RefundEvent/i),
201
+ role: "refund",
202
+ confidence: 0.95,
203
+ },
204
+ {
205
+ when: (ctx) => hasEventMatch(ctx.events, /reward::RewardClaimedEvent|reward::ClaimedEvent/i),
206
+ role: "reward",
207
+ confidence: 0.95,
208
+ },
209
+ {
210
+ when: (ctx) => hasEventMatch(ctx.events, /arbitration::CompensationEvent|arbitration::RefundEvent/i),
211
+ role: "compensation",
212
+ confidence: 0.9,
213
+ },
214
+ {
215
+ when: (ctx) => hasEventMatch(ctx.events, /treasury::DepositEvent/i),
216
+ role: "deposit",
217
+ confidence: 0.95,
218
+ },
219
+ {
220
+ when: (ctx) => hasEventMatch(ctx.events, /treasury::WithdrawEvent|treasury::ReleaseEvent/i),
221
+ role: "release",
222
+ confidence: 0.9,
223
+ },
224
+ {
225
+ when: (ctx) => ctx.operation_type === "payment" && isNegative(ctx.amount),
226
+ role: "payment",
227
+ confidence: 0.95,
228
+ },
229
+ {
230
+ when: (ctx) => ctx.operation_type === "payment" && !isNegative(ctx.amount),
231
+ role: "refund",
232
+ confidence: 0.9,
233
+ },
234
+ {
235
+ when: (ctx) => ctx.operation_type === "reward" && isNegative(ctx.amount),
236
+ role: "reward",
237
+ confidence: 0.95,
238
+ },
239
+ {
240
+ when: (ctx) => ctx.operation_type === "reward" && !isNegative(ctx.amount),
241
+ role: "release",
242
+ confidence: 0.9,
243
+ },
244
+ {
245
+ when: (ctx) => ctx.operation_type === "treasury" && isNegative(ctx.amount),
246
+ role: "deposit",
247
+ confidence: 0.95,
248
+ },
249
+ {
250
+ when: (ctx) => ctx.operation_type === "treasury" && !isNegative(ctx.amount),
251
+ role: "release",
252
+ confidence: 0.9,
253
+ },
254
+ {
255
+ when: (ctx) => ctx.operation_type === "allocation" && isNegative(ctx.amount),
256
+ role: "payment",
257
+ confidence: 0.85,
258
+ },
259
+ {
260
+ when: (ctx) => ctx.operation_type === "allocation" && !isNegative(ctx.amount),
261
+ role: "release",
262
+ confidence: 0.85,
263
+ },
264
+ {
265
+ when: (ctx) => ctx.operation_type === "arbitration" && (ctx.data?.compensation !== undefined || ctx.data?.arb === true),
266
+ role: "compensation",
267
+ confidence: 0.9,
268
+ },
269
+ {
270
+ when: (ctx) => ctx.operation_type === "order" && isNegative(ctx.amount) && ctx.data?.buy !== undefined,
271
+ role: "payment",
272
+ confidence: 0.9,
273
+ },
274
+ {
275
+ when: (ctx) => ctx.operation_type === "order" && !isNegative(ctx.amount) && (ctx.data?.refund !== undefined || ctx.data?.arb !== undefined),
276
+ role: "refund",
277
+ confidence: 0.85,
278
+ },
279
+ {
280
+ when: (ctx) => {
281
+ if (isNegative(ctx.amount))
282
+ return false;
283
+ const amt = absAmount(ctx.amount);
284
+ return isGasCoin(ctx.coinType) && amt > BigInt(0) && amt < SMALL_AMOUNT_THRESHOLD;
285
+ },
286
+ role: "gas",
287
+ confidence: 0.7,
288
+ },
289
+ {
290
+ when: (ctx) => {
291
+ if (isNegative(ctx.amount))
292
+ return false;
293
+ return ctx.sender !== undefined && ctx.recipient !== undefined && ctx.sender === ctx.recipient && ctx.sender !== "";
294
+ },
295
+ role: "change",
296
+ confidence: 0.7,
297
+ },
298
+ {
299
+ when: (ctx) => isNegative(ctx.amount),
300
+ role: "payment",
301
+ confidence: 0.7,
302
+ },
303
+ {
304
+ when: (ctx) => !isNegative(ctx.amount) && absAmount(ctx.amount) === BigInt(0),
305
+ role: "other",
306
+ confidence: 0.5,
307
+ },
308
+ {
309
+ when: (ctx) => !isNegative(ctx.amount),
310
+ role: "release",
311
+ confidence: 0.7,
312
+ },
313
+ {
314
+ when: () => true,
315
+ role: "other",
316
+ confidence: 0.3,
317
+ },
318
+ ];
319
+ export function tagFundRoles(balanceChanges, operation_type, data, events) {
320
+ if (!Array.isArray(balanceChanges))
321
+ return [];
322
+ return balanceChanges
323
+ .filter((c) => c && (c.amount !== undefined || c.coinType))
324
+ .map((c) => {
325
+ const ctx = {
326
+ operation_type,
327
+ amount: String(c.amount ?? "0"),
328
+ coinType: c.coinType,
329
+ data: data ?? {},
330
+ events,
331
+ sender: c.sender,
332
+ recipient: c.recipient,
333
+ };
334
+ const rule = FUND_ROLE_RULES.find((r) => r.when(ctx));
335
+ const role = rule?.role ?? "other";
336
+ return {
337
+ amount: ctx.amount,
338
+ coinType: c.coinType || "",
339
+ role,
340
+ from: c.sender ?? null,
341
+ to: c.recipient ?? null,
342
+ };
343
+ });
344
+ }
345
+ const EVENT_SEMANTIC_RULES = [
346
+ {
347
+ pattern: /::service::ServiceCreatedEvent/i,
348
+ business_meaning: "A new Service was created (not yet published)",
349
+ category: "lifecycle",
350
+ side_effect: "Service exists in draft state; configure Machine and publish when ready",
351
+ },
352
+ {
353
+ pattern: /::service::ServicePublishedEvent/i,
354
+ business_meaning: "Service has been published and is now immutable",
355
+ category: "lifecycle",
356
+ side_effect: "Customers can now place orders against this Service",
357
+ },
358
+ {
359
+ pattern: /::service::ServiceModifiedEvent/i,
360
+ business_meaning: "Service configuration was modified",
361
+ category: "state_change",
362
+ },
363
+ {
364
+ pattern: /::machine::MachineCreatedEvent/i,
365
+ business_meaning: "A new Machine (workflow template) was created",
366
+ category: "lifecycle",
367
+ },
368
+ {
369
+ pattern: /::machine::MachineBoundEvent/i,
370
+ business_meaning: "Machine was bound to a Service",
371
+ category: "state_change",
372
+ side_effect: "Orders placed on this Service will follow the Machine's state graph",
373
+ },
374
+ {
375
+ pattern: /::machine::MachinePublishedEvent/i,
376
+ business_meaning: "Machine was published and is now immutable",
377
+ category: "lifecycle",
378
+ },
379
+ {
380
+ pattern: /::order::OrderCreatedEvent/i,
381
+ business_meaning: "A new Order was placed by a customer",
382
+ category: "lifecycle",
383
+ side_effect: "Order is pending payment; merchant should await payment before proceeding",
384
+ },
385
+ {
386
+ pattern: /::order::OrderPaidEvent/i,
387
+ business_meaning: "Order has been paid by the customer",
388
+ category: "fund_flow",
389
+ side_effect: "Funds are escrowed; merchant can advance the order to delivery",
390
+ },
391
+ {
392
+ pattern: /::order::OrderAdvancedEvent/i,
393
+ business_meaning: "Order advanced to the next state in the Machine graph",
394
+ category: "state_change",
395
+ },
396
+ {
397
+ pattern: /::order::OrderCompletedEvent/i,
398
+ business_meaning: "Order has been completed",
399
+ category: "lifecycle",
400
+ side_effect: "Allocation can be executed to distribute funds to recipients",
401
+ },
402
+ {
403
+ pattern: /::order::OrderRefundedEvent|::order::RefundEvent/i,
404
+ business_meaning: "Order was refunded",
405
+ category: "fund_flow",
406
+ side_effect: "Escrowed funds returned to the customer",
407
+ },
408
+ {
409
+ pattern: /::order::OrderCancelledEvent/i,
410
+ business_meaning: "Order was cancelled",
411
+ category: "lifecycle",
412
+ },
413
+ {
414
+ pattern: /::reward::RewardCreatedEvent/i,
415
+ business_meaning: "A new Reward pool was created",
416
+ category: "lifecycle",
417
+ },
418
+ {
419
+ pattern: /::reward::RewardClaimedEvent|::reward::ClaimedEvent/i,
420
+ business_meaning: "Reward was claimed by a claimant",
421
+ category: "fund_flow",
422
+ side_effect: "Funds transferred from the reward pool to the claimant",
423
+ },
424
+ {
425
+ pattern: /::treasury::DepositEvent/i,
426
+ business_meaning: "Funds were deposited into the Treasury",
427
+ category: "fund_flow",
428
+ },
429
+ {
430
+ pattern: /::treasury::WithdrawEvent|::treasury::ReleaseEvent/i,
431
+ business_meaning: "Funds were withdrawn from the Treasury",
432
+ category: "fund_flow",
433
+ },
434
+ {
435
+ pattern: /::demand::DemandCreatedEvent/i,
436
+ business_meaning: "A new Demand (bounty) was posted",
437
+ category: "lifecycle",
438
+ },
439
+ {
440
+ pattern: /::demand::PresenterSubmittedEvent|::demand::PresentedEvent/i,
441
+ business_meaning: "A presenter submitted a solution for the Demand",
442
+ category: "state_change",
443
+ },
444
+ {
445
+ pattern: /::permission::PermissionGrantedEvent/i,
446
+ business_meaning: "Permission was granted to an address",
447
+ category: "permission",
448
+ },
449
+ {
450
+ pattern: /::permission::PermissionRevokedEvent/i,
451
+ business_meaning: "Permission was revoked from an address",
452
+ category: "permission",
453
+ },
454
+ {
455
+ pattern: /::guard::GuardRejectedEvent|::guard::RejectedEvent/i,
456
+ business_meaning: "Guard verification rejected the operation",
457
+ category: "guard",
458
+ side_effect: "Operation was blocked; user must satisfy the Guard's submission requirements",
459
+ },
460
+ {
461
+ pattern: /::guard::GuardPassedEvent|::guard::AcceptedEvent/i,
462
+ business_meaning: "Guard verification passed",
463
+ category: "guard",
464
+ },
465
+ {
466
+ pattern: /::arbitration::ArbitrationRequestedEvent|::arbitration::RequestedEvent/i,
467
+ business_meaning: "Arbitration was requested for an Order",
468
+ category: "state_change",
469
+ side_effect: "Order is now in dispute; arbiter will rule on the outcome",
470
+ },
471
+ {
472
+ pattern: /::arbitration::ArbitrationResolvedEvent|::arbitration::ResolvedEvent|::arbitration::CompensationEvent/i,
473
+ business_meaning: "Arbitration was resolved (compensation or refund awarded)",
474
+ category: "fund_flow",
475
+ side_effect: "Funds redistributed per arbiter's ruling",
476
+ },
477
+ {
478
+ pattern: /::allocation::AllocatedEvent|::allocation::DistributedEvent/i,
479
+ business_meaning: "Funds were distributed to allocation recipients",
480
+ category: "fund_flow",
481
+ },
482
+ {
483
+ pattern: /::progress::ProgressUpdatedEvent|::progress::UpdatedEvent/i,
484
+ business_meaning: "Order progress was updated",
485
+ category: "state_change",
486
+ },
487
+ ];
488
+ function extractRelatedObject(event) {
489
+ if (!event || typeof event !== "object")
490
+ return undefined;
491
+ const fields = event.fields ?? event.payload ?? event;
492
+ if (typeof fields !== "object")
493
+ return undefined;
494
+ for (const key of ["object_id", "objectId", "id", "parent", "service", "order", "machine", "reward", "treasury"]) {
495
+ const v = fields[key];
496
+ if (typeof v === "string" && v.startsWith("0x") && v.length >= 6)
497
+ return v;
498
+ }
499
+ return undefined;
500
+ }
501
+ export function eventToSemantic(event) {
502
+ const eventType = String(event?.type ?? event?.event_type ?? "");
503
+ const rule = EVENT_SEMANTIC_RULES.find((r) => r.pattern.test(eventType));
504
+ if (!rule) {
505
+ return {
506
+ event_type: eventType,
507
+ business_meaning: "Unknown event",
508
+ category: "other",
509
+ };
510
+ }
511
+ const related = rule.extractRelatedObject ? rule.extractRelatedObject(event) : extractRelatedObject(event);
512
+ const result = {
513
+ event_type: eventType,
514
+ business_meaning: rule.business_meaning,
515
+ category: rule.category,
516
+ };
517
+ if (related)
518
+ result.related_object = related;
519
+ if (rule.side_effect)
520
+ result.side_effect = rule.side_effect;
521
+ return result;
522
+ }
523
+ export function annotateEvents(events) {
524
+ if (!Array.isArray(events))
525
+ return [];
526
+ return events.map(eventToSemantic);
527
+ }
528
+ const NEXT_ACTION_RULES = [
529
+ {
530
+ when: (ot) => ot === "service",
531
+ action: "publish the Service when configuration is complete",
532
+ reason: "Service must be published before customers can order",
533
+ tool: "onchain_operations (service with publish:true)",
534
+ priority: "recommended",
535
+ },
536
+ {
537
+ when: (ot) => ot === "service",
538
+ action: "add Machine nodes to define the service workflow",
539
+ reason: "Machine drives order state transitions",
540
+ tool: "onchain_operations (machine)",
541
+ priority: "recommended",
542
+ },
543
+ {
544
+ when: (ot) => ot === "machine",
545
+ action: "bind Progress to track order execution",
546
+ reason: "Progress provides customer-visible status updates",
547
+ tool: "onchain_operations (progress)",
548
+ priority: "recommended",
549
+ },
550
+ {
551
+ when: (ot) => ot === "order",
552
+ action: "wait for customer payment or proceed to allocation",
553
+ reason: "Order lifecycle: payment → allocation → completion",
554
+ priority: "optional",
555
+ },
556
+ {
557
+ when: (ot) => ot === "demand",
558
+ action: "wait for presenter submissions or evaluate existing ones",
559
+ reason: "Demand lifecycle: presenters submit solutions for reward",
560
+ priority: "optional",
561
+ },
562
+ {
563
+ when: (ot) => ot === "reward",
564
+ action: "deposit funds into the reward pool",
565
+ reason: "Reward pool must be funded before claimants can withdraw",
566
+ tool: "onchain_operations (treasury)",
567
+ priority: "recommended",
568
+ },
569
+ {
570
+ when: (ot) => ot === "bridge_cross_chain_wow_to_evm",
571
+ action: "poll query_transfer_status until bridge signs (~1-5 min), then call claim_wow_to_evm to complete",
572
+ reason: "Cross-chain WOW→EVM is a 2-step process: deposit first, then claim after bridge confirmation",
573
+ tool: "bridge_operation (query_transfer_status, then claim_wow_to_evm)",
574
+ priority: "required",
575
+ },
576
+ {
577
+ when: (ot) => ot === "bridge_cross_chain_evm_to_wow",
578
+ action: "poll query_transfer_status to monitor auto-claim progress (~10-20 min)",
579
+ reason: "EVM→WOW cross-chain auto-claims; monitor progress but no manual action needed",
580
+ tool: "bridge_operation (query_transfer_status)",
581
+ priority: "recommended",
582
+ },
583
+ {
584
+ when: (ot) => ot === "bridge_claim_wow_to_evm",
585
+ action: "verify recipient EVM balance updated",
586
+ reason: "Claim completes the cross-chain transfer; verify funds arrived on EVM side",
587
+ tool: "bridge_operation (query_active_evm_account)",
588
+ priority: "recommended",
589
+ },
590
+ {
591
+ when: (ot) => ot === "bridge_withdraw",
592
+ action: "verify WOW balance updated",
593
+ reason: "Withdrawal moves funds from active EVM account to WOW; verify balance",
594
+ tool: "account_operation (balance)",
595
+ priority: "recommended",
596
+ },
597
+ {
598
+ when: (ot) => ot === "account_new",
599
+ action: "claim faucet tokens for gas if on testnet, then proceed to create Service",
600
+ reason: "New account needs gas tokens before on-chain operations",
601
+ tool: "account_operation (faucet)",
602
+ priority: "recommended",
603
+ },
604
+ {
605
+ when: (ot) => ot === "account_faucet",
606
+ action: "proceed to create Permission and Service objects",
607
+ reason: "Account is now funded; start building your service",
608
+ tool: "onchain_operations (permission, service)",
609
+ priority: "recommended",
610
+ },
611
+ {
612
+ when: (ot) => ot === "query_toolkit",
613
+ action: "use the queried object data to plan next operations",
614
+ reason: "Query results reveal current object states for decision-making",
615
+ priority: "optional",
616
+ },
617
+ ];
618
+ function inferNextActions(operation_type, data, status) {
619
+ return NEXT_ACTION_RULES
620
+ .filter((r) => r.when(operation_type, data, status))
621
+ .map((r) => ({
622
+ action: r.action,
623
+ reason: r.reason,
624
+ tool: r.tool,
625
+ priority: r.priority,
626
+ }));
627
+ }
628
+ function inferWarnings(operation_type, data, _safeResult) {
629
+ const warnings = [];
630
+ if (operation_type === "service" && data?.order_allocators === undefined) {
631
+ warnings.push("order_allocators not configured; order funds cannot be distributed automatically");
632
+ }
633
+ if (operation_type === "reward" && (data?.balance === "0" || data?.balance === 0)) {
634
+ warnings.push("Reward pool balance is zero; claimants cannot withdraw");
635
+ }
636
+ return warnings;
637
+ }
638
+ function composeSummary(intent, status, created, modified, released) {
639
+ const intentVerb = intent.replace(/_/g, " ");
640
+ if (status === "failed")
641
+ return `Failed to ${intentVerb}`;
642
+ if (status === "pending_input")
643
+ return `${intentVerb} requires Guard submission to proceed`;
644
+ const parts = [];
645
+ if (created.length)
646
+ parts.push(`created ${created.length} object(s)`);
647
+ if (modified.length)
648
+ parts.push(`modified ${modified.length} object(s)`);
649
+ if (released.length) {
650
+ if (intent === "allocate_funds") {
651
+ const details = released.map(f => {
652
+ const amt = f.amount;
653
+ const coin = shortCoinType(f.coinType);
654
+ const recipient = f.to ? shortAddr(f.to) : null;
655
+ const sender = f.from ? shortAddr(f.from) : null;
656
+ if (recipient)
657
+ return `${amt} ${coin} → ${recipient}`;
658
+ if (sender)
659
+ return `${amt} ${coin} from ${sender}`;
660
+ return `${amt} ${coin}`;
661
+ }).join("; ");
662
+ parts.push(`distributed: ${details}`);
663
+ }
664
+ else {
665
+ parts.push(`${released.length} fund movement(s)`);
666
+ }
667
+ }
668
+ return `Successfully ${intentVerb}${parts.length ? ` (${parts.join(", ")})` : ""}`;
669
+ }
670
+ function shortAddr(addr) {
671
+ if (addr.length > 14) {
672
+ return addr.slice(0, 8) + "..." + addr.slice(-4);
673
+ }
674
+ return addr;
675
+ }
676
+ function shortCoinType(coinType) {
677
+ if (!coinType)
678
+ return "coin";
679
+ const parts = coinType.split("::");
680
+ return parts[parts.length - 1] || coinType;
681
+ }
682
+ export function buildSemantic(safeResult, context) {
683
+ if (!context)
684
+ return undefined;
685
+ const intent = inferIntent(context.operation_type, context.data);
686
+ const status = inferStatus(safeResult);
687
+ const objectChanges = safeResult?.objectChanges || [];
688
+ const balanceChanges = safeResult?.balanceChanges || [];
689
+ const events = safeResult?.events || [];
690
+ const created = tagObjectRoles(objectChanges.filter((c) => c?.type === "created"));
691
+ const modified = tagObjectRoles(objectChanges.filter((c) => c?.type === "mutated" || c?.type === "published"));
692
+ const released = tagFundRoles(balanceChanges, context.operation_type, context.data, events);
693
+ const annotatedEvents = annotateEvents(events);
694
+ const next_actions = inferNextActions(context.operation_type, context.data, status);
695
+ const warnings = inferWarnings(context.operation_type, context.data, safeResult);
696
+ return {
697
+ intent,
698
+ status,
699
+ summary: composeSummary(intent, status, created, modified, released),
700
+ created: created.length ? created : undefined,
701
+ modified: modified.length ? modified : undefined,
702
+ released: released.length ? released : undefined,
703
+ events: annotatedEvents.length ? annotatedEvents : undefined,
704
+ next_actions: next_actions.length ? next_actions : undefined,
705
+ warnings: warnings.length ? warnings : undefined,
706
+ };
707
+ }
708
+ export function buildDataSemantic(data, context, isError, errorMsg) {
709
+ if (!context)
710
+ return undefined;
711
+ const intent = inferIntent(context.operation_type, context.data);
712
+ const warnings = [];
713
+ let status;
714
+ if (isError) {
715
+ status = "failed";
716
+ }
717
+ else {
718
+ status = "success";
719
+ if (Array.isArray(data) && data.length === 0) {
720
+ status = "partial";
721
+ warnings.push("no results found");
722
+ }
723
+ else if (data === null || data === undefined) {
724
+ status = "partial";
725
+ warnings.push("no results found");
726
+ }
727
+ else if (typeof data === "object" && !Array.isArray(data)) {
728
+ const values = Object.values(data);
729
+ if (values.length > 0 && values.every((v) => (Array.isArray(v) ? v.length === 0 : v === null || v === undefined))) {
730
+ status = "partial";
731
+ warnings.push("no results found");
732
+ }
733
+ }
734
+ }
735
+ const next_actions = inferNextActions(context.operation_type, context.data, status);
736
+ let annotatedEvents;
737
+ if (!isError && context.operation_type === "onchain_events") {
738
+ const eventsArray = Array.isArray(data) ? data : (data?.data && Array.isArray(data.data) ? data.data : null);
739
+ if (eventsArray) {
740
+ annotatedEvents = annotateEvents(eventsArray);
741
+ if (annotatedEvents.length === 0)
742
+ annotatedEvents = undefined;
743
+ }
744
+ }
745
+ const intentVerb = intent.replace(/_/g, " ");
746
+ let summary;
747
+ if (status === "failed") {
748
+ summary = `Failed to ${intentVerb}`;
749
+ }
750
+ else if (status === "partial") {
751
+ summary = `${intentVerb} completed with no results`;
752
+ }
753
+ else {
754
+ summary = `Successfully ${intentVerb}`;
755
+ }
756
+ return {
757
+ intent,
758
+ status,
759
+ summary,
760
+ events: annotatedEvents,
761
+ next_actions: next_actions.length ? next_actions : undefined,
762
+ warnings: warnings.length ? warnings : undefined,
763
+ };
764
+ }