@wowok/agent-mcp 2.3.13 → 2.3.16

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 (194) hide show
  1. package/dist/config/index.d.ts +1 -0
  2. package/dist/config/index.js +1 -0
  3. package/dist/config/runtime.d.ts +26 -0
  4. package/dist/config/runtime.js +217 -0
  5. package/dist/customer/industry-risks.d.ts +36 -0
  6. package/dist/customer/industry-risks.js +424 -0
  7. package/dist/customer/info-puzzle.d.ts +102 -0
  8. package/dist/customer/info-puzzle.js +312 -0
  9. package/dist/customer/order-monitor.d.ts +75 -0
  10. package/dist/customer/order-monitor.js +327 -0
  11. package/dist/customer/order-strategy.d.ts +36 -0
  12. package/dist/customer/order-strategy.js +373 -0
  13. package/dist/customer/post-purchase.d.ts +42 -0
  14. package/dist/customer/post-purchase.js +350 -0
  15. package/dist/customer/reminder-system.d.ts +42 -0
  16. package/dist/customer/reminder-system.js +295 -0
  17. package/dist/customer/risk-assessment.d.ts +8 -0
  18. package/dist/customer/risk-assessment.js +337 -0
  19. package/dist/customer/types.d.ts +193 -0
  20. package/dist/customer/types.js +13 -0
  21. package/dist/customer/user-preferences.d.ts +67 -0
  22. package/dist/customer/user-preferences.js +451 -0
  23. package/dist/experience/experience-reuse.d.ts +10 -0
  24. package/dist/experience/experience-reuse.js +103 -0
  25. package/dist/experience/index.d.ts +6 -0
  26. package/dist/experience/index.js +5 -0
  27. package/dist/experience/intent-distill.d.ts +3 -0
  28. package/dist/experience/intent-distill.js +83 -0
  29. package/dist/experience/realtime-feedback.d.ts +5 -0
  30. package/dist/experience/realtime-feedback.js +77 -0
  31. package/dist/experience/types.d.ts +50 -0
  32. package/dist/experience/types.js +1 -0
  33. package/dist/experience/user-profile.d.ts +25 -0
  34. package/dist/experience/user-profile.js +171 -0
  35. package/dist/harness/checkpoint.d.ts +8 -0
  36. package/dist/harness/checkpoint.js +129 -0
  37. package/dist/harness/index.d.ts +33 -0
  38. package/dist/harness/index.js +75 -0
  39. package/dist/harness/plan.d.ts +18 -0
  40. package/dist/harness/plan.js +252 -0
  41. package/dist/harness/recover.d.ts +17 -0
  42. package/dist/harness/recover.js +139 -0
  43. package/dist/harness/types.d.ts +137 -0
  44. package/dist/harness/types.js +1 -0
  45. package/dist/harness/verify.d.ts +42 -0
  46. package/dist/harness/verify.js +237 -0
  47. package/dist/index.js +667 -201
  48. package/dist/knowledge/acquisition-flywheel.d.ts +50 -0
  49. package/dist/knowledge/acquisition-flywheel.js +183 -0
  50. package/dist/knowledge/arbitration-trust.d.ts +24 -0
  51. package/dist/knowledge/arbitration-trust.js +117 -0
  52. package/dist/knowledge/audit-rules.d.ts +28 -0
  53. package/dist/knowledge/audit-rules.js +141 -0
  54. package/dist/knowledge/demand-matching.d.ts +29 -0
  55. package/dist/knowledge/demand-matching.js +132 -0
  56. package/dist/knowledge/dynamic-pricing.d.ts +31 -0
  57. package/dist/knowledge/dynamic-pricing.js +87 -0
  58. package/dist/knowledge/flywheel-loop.d.ts +87 -0
  59. package/dist/knowledge/flywheel-loop.js +378 -0
  60. package/dist/knowledge/glossary.d.ts +18 -0
  61. package/dist/knowledge/glossary.js +209 -0
  62. package/dist/knowledge/index.d.ts +64 -0
  63. package/dist/knowledge/index.js +66 -0
  64. package/dist/knowledge/industry-evolution.d.ts +82 -0
  65. package/dist/knowledge/industry-evolution.js +323 -0
  66. package/dist/knowledge/industry-generalizer.d.ts +17 -0
  67. package/dist/knowledge/industry-generalizer.js +381 -0
  68. package/dist/knowledge/industry-registry.d.ts +49 -0
  69. package/dist/knowledge/industry-registry.js +167 -0
  70. package/dist/knowledge/intent-metrics.d.ts +42 -0
  71. package/dist/knowledge/intent-metrics.js +566 -0
  72. package/dist/knowledge/process-model.d.ts +24 -0
  73. package/dist/knowledge/process-model.js +160 -0
  74. package/dist/knowledge/reputation-rules.d.ts +42 -0
  75. package/dist/knowledge/reputation-rules.js +99 -0
  76. package/dist/knowledge/reward-templates.d.ts +25 -0
  77. package/dist/knowledge/reward-templates.js +125 -0
  78. package/dist/knowledge/safety-rules.d.ts +36 -0
  79. package/dist/knowledge/safety-rules.js +171 -0
  80. package/dist/knowledge/tool-constraints.d.ts +30 -0
  81. package/dist/knowledge/tool-constraints.js +185 -0
  82. package/dist/knowledge/trust-metrics.d.ts +37 -0
  83. package/dist/knowledge/trust-metrics.js +138 -0
  84. package/dist/loop-engineering/aggregate.d.ts +50 -0
  85. package/dist/loop-engineering/aggregate.js +132 -0
  86. package/dist/loop-engineering/diagnose.d.ts +22 -0
  87. package/dist/loop-engineering/diagnose.js +273 -0
  88. package/dist/loop-engineering/improve.d.ts +26 -0
  89. package/dist/loop-engineering/improve.js +229 -0
  90. package/dist/loop-engineering/index.d.ts +4 -0
  91. package/dist/loop-engineering/index.js +4 -0
  92. package/dist/loop-engineering/pipeline.d.ts +17 -0
  93. package/dist/loop-engineering/pipeline.js +56 -0
  94. package/dist/mode-market/index.d.ts +3 -0
  95. package/dist/mode-market/index.js +3 -0
  96. package/dist/mode-market/registry.d.ts +53 -0
  97. package/dist/mode-market/registry.js +124 -0
  98. package/dist/mode-market/review.d.ts +27 -0
  99. package/dist/mode-market/review.js +214 -0
  100. package/dist/mode-market/submission.d.ts +25 -0
  101. package/dist/mode-market/submission.js +85 -0
  102. package/dist/project/graph.d.ts +71 -0
  103. package/dist/project/graph.js +314 -0
  104. package/dist/project/index.d.ts +62 -0
  105. package/dist/project/index.js +167 -0
  106. package/dist/project/namespace.d.ts +62 -0
  107. package/dist/project/namespace.js +181 -0
  108. package/dist/project/query.d.ts +40 -0
  109. package/dist/project/query.js +110 -0
  110. package/dist/safety/confirm-gate.d.ts +15 -0
  111. package/dist/safety/confirm-gate.js +44 -0
  112. package/dist/safety/index.d.ts +3 -0
  113. package/dist/safety/index.js +3 -0
  114. package/dist/safety/preview.d.ts +2 -0
  115. package/dist/safety/preview.js +36 -0
  116. package/dist/schema/call/allocation.d.ts +55 -40
  117. package/dist/schema/call/arbitration.d.ts +201 -186
  118. package/dist/schema/call/base.d.ts +2104 -24
  119. package/dist/schema/call/base.js +168 -22
  120. package/dist/schema/call/bridge-handler.js +36 -18
  121. package/dist/schema/call/bridge.d.ts +777 -120
  122. package/dist/schema/call/bridge.js +13 -2
  123. package/dist/schema/call/contact.d.ts +15 -0
  124. package/dist/schema/call/demand.d.ts +69 -54
  125. package/dist/schema/call/guard.d.ts +125 -80
  126. package/dist/schema/call/handler.d.ts +5 -1
  127. package/dist/schema/call/handler.js +108 -3
  128. package/dist/schema/call/index.d.ts +1 -0
  129. package/dist/schema/call/index.js +1 -0
  130. package/dist/schema/call/machine.d.ts +830 -800
  131. package/dist/schema/call/order.d.ts +27 -12
  132. package/dist/schema/call/payment.d.ts +15 -0
  133. package/dist/schema/call/permission.d.ts +15 -0
  134. package/dist/schema/call/personal.d.ts +15 -0
  135. package/dist/schema/call/progress.d.ts +21 -6
  136. package/dist/schema/call/proof.d.ts +42 -12
  137. package/dist/schema/call/proof.js +3 -3
  138. package/dist/schema/call/repository.d.ts +91 -76
  139. package/dist/schema/call/reward.d.ts +51 -36
  140. package/dist/schema/call/semantic.d.ts +24 -0
  141. package/dist/schema/call/semantic.js +981 -0
  142. package/dist/schema/call/service.d.ts +444 -429
  143. package/dist/schema/call/treasury.d.ts +219 -204
  144. package/dist/schema/common/index.js +3 -3
  145. package/dist/schema/local/index.d.ts +341 -74
  146. package/dist/schema/local/index.js +44 -7
  147. package/dist/schema/messenger/index.d.ts +1034 -92
  148. package/dist/schema/messenger/index.js +18 -0
  149. package/dist/schema/operations.d.ts +2634 -1817
  150. package/dist/schema/operations.js +16 -5
  151. package/dist/schema/query/index.d.ts +2293 -2289
  152. package/dist/schema/query/index.js +34 -28
  153. package/dist/schemas/account_operation.output.json +28 -16
  154. package/dist/schemas/account_operation.schema.json +2 -2
  155. package/dist/schemas/bridge_operation.output.json +520 -0
  156. package/dist/schemas/bridge_operation.schema.json +15 -0
  157. package/dist/schemas/guard2file.schema.json +15 -0
  158. package/dist/schemas/index.json +1 -1
  159. package/dist/schemas/local_info_operation.output.json +26 -0
  160. package/dist/schemas/local_info_operation.schema.json +1 -1
  161. package/dist/schemas/local_mark_operation.output.json +27 -1
  162. package/dist/schemas/local_mark_operation.schema.json +4 -4
  163. package/dist/schemas/machineNode2file.schema.json +15 -0
  164. package/dist/schemas/messenger_operation.output.json +549 -0
  165. package/dist/schemas/messenger_operation.schema.json +21 -0
  166. package/dist/schemas/onchain_events.output.json +3 -0
  167. package/dist/schemas/onchain_operations.output.json +814 -37
  168. package/dist/schemas/onchain_operations.schema.json +117 -40
  169. package/dist/schemas/onchain_operations_allocation.schema.json +26 -9
  170. package/dist/schemas/onchain_operations_arbitration.schema.json +26 -9
  171. package/dist/schemas/onchain_operations_contact.schema.json +26 -9
  172. package/dist/schemas/onchain_operations_demand.schema.json +26 -9
  173. package/dist/schemas/onchain_operations_gen_passport.schema.json +51 -17
  174. package/dist/schemas/onchain_operations_guard.schema.json +26 -9
  175. package/dist/schemas/onchain_operations_machine.schema.json +92 -32
  176. package/dist/schemas/onchain_operations_order.schema.json +26 -9
  177. package/dist/schemas/onchain_operations_payment.schema.json +26 -9
  178. package/dist/schemas/onchain_operations_permission.schema.json +26 -9
  179. package/dist/schemas/onchain_operations_personal.schema.json +26 -9
  180. package/dist/schemas/onchain_operations_progress.schema.json +26 -9
  181. package/dist/schemas/onchain_operations_repository.schema.json +26 -9
  182. package/dist/schemas/onchain_operations_reward.schema.json +26 -9
  183. package/dist/schemas/onchain_operations_service.schema.json +26 -9
  184. package/dist/schemas/onchain_operations_treasury.schema.json +26 -9
  185. package/dist/schemas/onchain_table_data.output.json +224 -69
  186. package/dist/schemas/onchain_table_data.schema.json +2 -2
  187. package/dist/schemas/query_toolkit.schema.json +5 -1
  188. package/dist/telemetry/index.d.ts +19 -0
  189. package/dist/telemetry/index.js +112 -0
  190. package/dist/telemetry/redact.d.ts +2 -0
  191. package/dist/telemetry/redact.js +23 -0
  192. package/dist/telemetry/storage.d.ts +8 -0
  193. package/dist/telemetry/storage.js +80 -0
  194. package/package.json +6 -3
@@ -0,0 +1,981 @@
1
+ import { auditService } from "../../knowledge/index.js";
2
+ import { getExperienceFeedback, recordOperationOutcome } from "../../experience/index.js";
3
+ import { isEnabled as isRuntimeEnabled, listServices } from "../../config/index.js";
4
+ import { generateReminders } from "../../customer/reminder-system.js";
5
+ import { getProfile } from "../../experience/user-profile.js";
6
+ import { injectEvolutionContext, recordIndustrySignal } from "../../knowledge/flywheel-loop.js";
7
+ function booleanFromSignals(positive, negative) {
8
+ if (positive)
9
+ return true;
10
+ if (negative)
11
+ return false;
12
+ return undefined;
13
+ }
14
+ const ERROR_RULES = [
15
+ {
16
+ patterns: [/insufficient\s*(gas|balance|coin|fund)/i, /ENOTENOUGH/i, /not\s*enough\s*(coin|gas|balance)/i, /gas\s*budget/i],
17
+ error_code: "insufficient_balance",
18
+ retryable: true,
19
+ recovery_hint: "Claim faucet tokens via account_operation (faucet) then retry the call",
20
+ },
21
+ {
22
+ 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],
23
+ error_code: "network_error",
24
+ retryable: true,
25
+ recovery_hint: "Retry the call; if it persists, switch RPC endpoint or check connectivity",
26
+ },
27
+ {
28
+ patterns: [/faucet/i, /too\s*many\s*requests/i, /rate\s*limit/i, /429/i],
29
+ error_code: "network_error",
30
+ retryable: true,
31
+ recovery_hint: "Faucet rate limit hit (HTTP 429). Wait a few minutes and retry. To check existing balance, use account_balance query.",
32
+ },
33
+ {
34
+ patterns: [/guard.*(reject|fail|denied)/i, /verification\s*failed/i, /submission.*(invalid|fail|required)/i, /passport.*(invalid|fail)/i, /move[._-]?abort.*guard/i],
35
+ error_code: "guard_rejected",
36
+ retryable: false,
37
+ recovery_hint: "Fill the Guard submission data (see the 'submission' field) and resubmit via call_with_submission",
38
+ },
39
+ {
40
+ patterns: [/already\s*publish/i, /immutable/i, /cannot\s*(modify|change|mutate)/i, /locked/i, /is\s*published/i],
41
+ error_code: "immutable_violation",
42
+ retryable: false,
43
+ recovery_hint: "Object is in an immutable state (e.g. Service already published). Recreate the object if a different config is needed",
44
+ },
45
+ {
46
+ patterns: [/permission/i, /unauthorized/i, /forbidden/i, /not\s*(the\s*)?owner/i, /access\s*denied/i],
47
+ error_code: "permission_denied",
48
+ retryable: false,
49
+ recovery_hint: "Use an account with the required permission, or pass permission_guard IDs via env.permission_guard",
50
+ },
51
+ {
52
+ patterns: [/not\s*found/i, /does\s*not\s*exist/i, /ENOTFOUND/i, /no\s*such\s*object/i, /unknown\s*object/i],
53
+ error_code: "object_not_found",
54
+ retryable: false,
55
+ recovery_hint: "Verify the object ID/name with query_toolkit; local_mark names are case-sensitive",
56
+ },
57
+ {
58
+ patterns: [/state\s*(conflict|mismatch)/i, /already\s*exist/i, /conflict/i, /duplicate/i, /version\s*mismatch/i],
59
+ error_code: "state_conflict",
60
+ retryable: false,
61
+ recovery_hint: "Object state conflicts with the operation. Query the current state with query_toolkit and adjust parameters",
62
+ },
63
+ {
64
+ patterns: [/invalid/i, /missing\s*(field|param|required)/i, /required/i, /expected/i, /malformed/i, /parse\s*error/i, /type\s*mismatch/i],
65
+ error_code: "invalid_parameter",
66
+ retryable: false,
67
+ recovery_hint: "Check parameter format against the tool schema; consult wowok-tools Skill for the operation's requirements",
68
+ },
69
+ ];
70
+ export function classifyError(errorMsg) {
71
+ if (!errorMsg) {
72
+ return { error_code: "unknown", retryable: false };
73
+ }
74
+ for (const rule of ERROR_RULES) {
75
+ if (rule.patterns.some((p) => p.test(errorMsg))) {
76
+ return {
77
+ error_code: rule.error_code,
78
+ retryable: rule.retryable,
79
+ recovery_hint: rule.recovery_hint,
80
+ };
81
+ }
82
+ }
83
+ return {
84
+ error_code: "unknown",
85
+ retryable: false,
86
+ recovery_hint: "Inspect the full error message; consult wowok-tools Skill for the operation's requirements",
87
+ };
88
+ }
89
+ const INTENT_RULES = [
90
+ { operation_type: "service", signals: (d) => d?.publish === true, intent: "publish_service", confidence: 0.95 },
91
+ { operation_type: "service", signals: (d) => d?.name && d?.publish === undefined, intent: "create_service", confidence: 0.9 },
92
+ { operation_type: "service", intent: "modify_service", confidence: 0.7 },
93
+ { operation_type: "machine", intent: "configure_machine", confidence: 0.9 },
94
+ { operation_type: "progress", intent: "update_progress", confidence: 0.9 },
95
+ { operation_type: "order", signals: (d) => !!d?.arb, intent: "apply_arbitration", confidence: 0.9 },
96
+ { operation_type: "order", intent: "manage_order", confidence: 0.85 },
97
+ { operation_type: "payment", intent: "send_payment", confidence: 0.95 },
98
+ { operation_type: "reward", intent: "manage_reward", confidence: 0.9 },
99
+ { operation_type: "demand", intent: "post_demand", confidence: 0.9 },
100
+ { operation_type: "treasury", intent: "manage_treasury", confidence: 0.9 },
101
+ { operation_type: "allocation", intent: "allocate_funds", confidence: 0.9 },
102
+ { operation_type: "permission", intent: "manage_permission", confidence: 0.9 },
103
+ { operation_type: "guard", intent: "configure_guard", confidence: 0.9 },
104
+ { operation_type: "arbitration", intent: "manage_arbitration", confidence: 0.9 },
105
+ { operation_type: "contact", intent: "manage_contact", confidence: 0.9 },
106
+ { operation_type: "repository", intent: "manage_repository", confidence: 0.9 },
107
+ { operation_type: "personal", intent: "manage_personal", confidence: 0.9 },
108
+ { operation_type: "gen_passport", intent: "generate_passport", confidence: 0.95 },
109
+ { operation_type: "bridge_cross_chain_wow_to_evm", intent: "cross_chain_wow_to_evm_deposit", confidence: 0.95 },
110
+ { operation_type: "bridge_cross_chain_evm_to_wow", intent: "cross_chain_evm_to_wow_deposit", confidence: 0.95 },
111
+ { operation_type: "bridge_claim_wow_to_evm", intent: "claim_wow_to_evm", confidence: 0.95 },
112
+ { operation_type: "bridge_withdraw", intent: "withdraw_from_evm_account", confidence: 0.9 },
113
+ { operation_type: "bridge_query_active_evm_account", intent: "query_bridge_status", confidence: 0.85 },
114
+ { operation_type: "bridge_query_supported_evm_chains", intent: "query_bridge_status", confidence: 0.85 },
115
+ { operation_type: "bridge_query_supported_tokens", intent: "query_bridge_status", confidence: 0.85 },
116
+ { operation_type: "bridge_query_transfer_list", intent: "query_bridge_status", confidence: 0.85 },
117
+ { operation_type: "bridge_query_transfer_status", intent: "query_bridge_status", confidence: 0.85 },
118
+ { operation_type: "bridge_manage_evm_rpc", intent: "manage_evm_rpc", confidence: 0.9 },
119
+ { operation_type: "account_new", intent: "create_account", confidence: 0.95 },
120
+ { operation_type: "account_faucet", intent: "claim_faucet", confidence: 0.95 },
121
+ { operation_type: "account_balance", intent: "query_balance", confidence: 0.9 },
122
+ { operation_type: "mark_add", intent: "create_local_mark", confidence: 0.9 },
123
+ { operation_type: "mark_remove", intent: "remove_local_mark", confidence: 0.9 },
124
+ { operation_type: "mark_query", intent: "query_local_marks", confidence: 0.9 },
125
+ { operation_type: "local_info", intent: "query_local_info", confidence: 0.9 },
126
+ { operation_type: "query_toolkit", intent: "query_objects", confidence: 0.85 },
127
+ { operation_type: "onchain_events", intent: "query_events", confidence: 0.85 },
128
+ { operation_type: "onchain_table_data", intent: "query_table_data", confidence: 0.85 },
129
+ ];
130
+ export function inferIntent(operation_type, data) {
131
+ const rules = INTENT_RULES.filter((r) => r.operation_type === operation_type);
132
+ const signaled = rules.find((r) => r.signals && r.signals(data));
133
+ if (signaled)
134
+ return signaled.intent;
135
+ const fallback = rules.find((r) => !r.signals);
136
+ return fallback?.intent ?? operation_type;
137
+ }
138
+ function inferStatus(safeResult) {
139
+ if (safeResult && typeof safeResult === "object" && "error" in safeResult)
140
+ return "failed";
141
+ if (safeResult && typeof safeResult === "object" && "digest" in safeResult) {
142
+ return safeResult?.effects?.status?.status === "success" ? "success" : "failed";
143
+ }
144
+ return "success";
145
+ }
146
+ const OBJECT_TYPE_TO_ROLE = {
147
+ service: "Service",
148
+ machine: "Machine",
149
+ progress: "Progress",
150
+ permission: "Permission",
151
+ guard: "Guard",
152
+ order: "Order",
153
+ arb: "Arbitration",
154
+ arbcase: "ArbCase",
155
+ messenger: "Messenger",
156
+ contact: "Contact",
157
+ demand: "Demand",
158
+ reward: "Reward",
159
+ personal: "Personal",
160
+ repository: "Repository",
161
+ treasury: "Treasury",
162
+ discount: "Discount",
163
+ allocation: "Allocation",
164
+ };
165
+ export function objectTypeToRole(objectType) {
166
+ if (!objectType)
167
+ return "Other";
168
+ const base = objectType.replace(/<.*>/, "").trim();
169
+ const segments = base.split("::");
170
+ const last = (segments[segments.length - 1] || "").toLowerCase();
171
+ return OBJECT_TYPE_TO_ROLE[last] ?? "Other";
172
+ }
173
+ export function tagObjectRoles(objectChanges) {
174
+ if (!Array.isArray(objectChanges))
175
+ return [];
176
+ return objectChanges
177
+ .filter((c) => c && (c.objectId || c.object?.objectId))
178
+ .map((c) => {
179
+ const id = c.objectId || c.object?.objectId;
180
+ const type = c.objectType || c.object?.objectType || "";
181
+ const changeType = c.type || "";
182
+ return {
183
+ id,
184
+ role: objectTypeToRole(type),
185
+ immutable: type.includes("Service") && changeType === "published",
186
+ };
187
+ });
188
+ }
189
+ const GAS_COIN_PATTERNS = [/::sui::SUI$/i, /::wow::WOW$/i];
190
+ const SMALL_AMOUNT_THRESHOLD = BigInt(1_000_000);
191
+ function isNegative(amount) {
192
+ return String(amount ?? "0").startsWith("-");
193
+ }
194
+ function hasEventMatch(events, pattern) {
195
+ if (!Array.isArray(events))
196
+ return false;
197
+ return events.some((e) => pattern.test(String(e?.type ?? e?.event_type ?? "")));
198
+ }
199
+ function isGasCoin(coinType) {
200
+ if (!coinType)
201
+ return false;
202
+ return GAS_COIN_PATTERNS.some((p) => p.test(coinType));
203
+ }
204
+ function absAmount(amount) {
205
+ try {
206
+ return BigInt(String(amount).replace("-", "") || "0");
207
+ }
208
+ catch {
209
+ return BigInt(0);
210
+ }
211
+ }
212
+ const FUND_ROLE_RULES = [
213
+ {
214
+ when: (ctx) => hasEventMatch(ctx.events, /order::OrderPaidEvent/i),
215
+ role: "payment",
216
+ confidence: 0.95,
217
+ },
218
+ {
219
+ when: (ctx) => hasEventMatch(ctx.events, /order::OrderRefundedEvent|order::RefundEvent/i),
220
+ role: "refund",
221
+ confidence: 0.95,
222
+ },
223
+ {
224
+ when: (ctx) => hasEventMatch(ctx.events, /reward::RewardClaimedEvent|reward::ClaimedEvent/i),
225
+ role: "reward",
226
+ confidence: 0.95,
227
+ },
228
+ {
229
+ when: (ctx) => hasEventMatch(ctx.events, /arbitration::CompensationEvent|arbitration::RefundEvent/i),
230
+ role: "compensation",
231
+ confidence: 0.9,
232
+ },
233
+ {
234
+ when: (ctx) => hasEventMatch(ctx.events, /treasury::DepositEvent/i),
235
+ role: "deposit",
236
+ confidence: 0.95,
237
+ },
238
+ {
239
+ when: (ctx) => hasEventMatch(ctx.events, /treasury::WithdrawEvent|treasury::ReleaseEvent/i),
240
+ role: "release",
241
+ confidence: 0.9,
242
+ },
243
+ {
244
+ when: (ctx) => ctx.operation_type === "payment" && isNegative(ctx.amount),
245
+ role: "payment",
246
+ confidence: 0.95,
247
+ },
248
+ {
249
+ when: (ctx) => ctx.operation_type === "payment" && !isNegative(ctx.amount),
250
+ role: "refund",
251
+ confidence: 0.9,
252
+ },
253
+ {
254
+ when: (ctx) => ctx.operation_type === "reward" && isNegative(ctx.amount),
255
+ role: "reward",
256
+ confidence: 0.95,
257
+ },
258
+ {
259
+ when: (ctx) => ctx.operation_type === "reward" && !isNegative(ctx.amount),
260
+ role: "release",
261
+ confidence: 0.9,
262
+ },
263
+ {
264
+ when: (ctx) => ctx.operation_type === "treasury" && isNegative(ctx.amount),
265
+ role: "deposit",
266
+ confidence: 0.95,
267
+ },
268
+ {
269
+ when: (ctx) => ctx.operation_type === "treasury" && !isNegative(ctx.amount),
270
+ role: "release",
271
+ confidence: 0.9,
272
+ },
273
+ {
274
+ when: (ctx) => ctx.operation_type === "allocation" && isNegative(ctx.amount),
275
+ role: "payment",
276
+ confidence: 0.85,
277
+ },
278
+ {
279
+ when: (ctx) => ctx.operation_type === "allocation" && !isNegative(ctx.amount),
280
+ role: "release",
281
+ confidence: 0.85,
282
+ },
283
+ {
284
+ when: (ctx) => ctx.operation_type === "arbitration" && (ctx.data?.compensation !== undefined || ctx.data?.arb === true),
285
+ role: "compensation",
286
+ confidence: 0.9,
287
+ },
288
+ {
289
+ when: (ctx) => ctx.operation_type === "order" && isNegative(ctx.amount) && ctx.data?.buy !== undefined,
290
+ role: "payment",
291
+ confidence: 0.9,
292
+ },
293
+ {
294
+ when: (ctx) => ctx.operation_type === "order" && !isNegative(ctx.amount) && (ctx.data?.refund !== undefined || ctx.data?.arb !== undefined),
295
+ role: "refund",
296
+ confidence: 0.85,
297
+ },
298
+ {
299
+ when: (ctx) => {
300
+ if (isNegative(ctx.amount))
301
+ return false;
302
+ const amt = absAmount(ctx.amount);
303
+ return isGasCoin(ctx.coinType) && amt > BigInt(0) && amt < SMALL_AMOUNT_THRESHOLD;
304
+ },
305
+ role: "gas",
306
+ confidence: 0.7,
307
+ },
308
+ {
309
+ when: (ctx) => {
310
+ if (isNegative(ctx.amount))
311
+ return false;
312
+ return ctx.sender !== undefined && ctx.recipient !== undefined && ctx.sender === ctx.recipient && ctx.sender !== "";
313
+ },
314
+ role: "change",
315
+ confidence: 0.7,
316
+ },
317
+ {
318
+ when: (ctx) => isNegative(ctx.amount),
319
+ role: "payment",
320
+ confidence: 0.7,
321
+ },
322
+ {
323
+ when: (ctx) => !isNegative(ctx.amount) && absAmount(ctx.amount) === BigInt(0),
324
+ role: "other",
325
+ confidence: 0.5,
326
+ },
327
+ {
328
+ when: (ctx) => !isNegative(ctx.amount),
329
+ role: "release",
330
+ confidence: 0.7,
331
+ },
332
+ {
333
+ when: () => true,
334
+ role: "other",
335
+ confidence: 0.3,
336
+ },
337
+ ];
338
+ export function tagFundRoles(balanceChanges, operation_type, data, events) {
339
+ if (!Array.isArray(balanceChanges))
340
+ return [];
341
+ return balanceChanges
342
+ .filter((c) => c && (c.amount !== undefined || c.coinType))
343
+ .map((c) => {
344
+ const ctx = {
345
+ operation_type,
346
+ amount: String(c.amount ?? "0"),
347
+ coinType: c.coinType,
348
+ data: data ?? {},
349
+ events,
350
+ sender: c.sender,
351
+ recipient: c.recipient,
352
+ };
353
+ const rule = FUND_ROLE_RULES.find((r) => r.when(ctx));
354
+ const role = rule?.role ?? "other";
355
+ return {
356
+ amount: ctx.amount,
357
+ coinType: c.coinType || "",
358
+ role,
359
+ from: c.sender ?? null,
360
+ to: c.recipient ?? null,
361
+ };
362
+ });
363
+ }
364
+ const EVENT_SEMANTIC_RULES = [
365
+ {
366
+ pattern: /::service::ServiceCreatedEvent/i,
367
+ business_meaning: "A new Service was created (not yet published)",
368
+ category: "lifecycle",
369
+ side_effect: "Service exists in draft state; configure Machine and publish when ready",
370
+ },
371
+ {
372
+ pattern: /::service::ServicePublishedEvent/i,
373
+ business_meaning: "Service has been published and is now immutable",
374
+ category: "lifecycle",
375
+ side_effect: "Customers can now place orders against this Service",
376
+ },
377
+ {
378
+ pattern: /::service::ServiceModifiedEvent/i,
379
+ business_meaning: "Service configuration was modified",
380
+ category: "state_change",
381
+ },
382
+ {
383
+ pattern: /::machine::MachineCreatedEvent/i,
384
+ business_meaning: "A new Machine (workflow template) was created",
385
+ category: "lifecycle",
386
+ },
387
+ {
388
+ pattern: /::machine::MachineBoundEvent/i,
389
+ business_meaning: "Machine was bound to a Service",
390
+ category: "state_change",
391
+ side_effect: "Orders placed on this Service will follow the Machine's state graph",
392
+ },
393
+ {
394
+ pattern: /::machine::MachinePublishedEvent/i,
395
+ business_meaning: "Machine was published and is now immutable",
396
+ category: "lifecycle",
397
+ },
398
+ {
399
+ pattern: /::order::OrderCreatedEvent/i,
400
+ business_meaning: "A new Order was placed by a customer",
401
+ category: "lifecycle",
402
+ side_effect: "Order is pending payment; merchant should await payment before proceeding",
403
+ },
404
+ {
405
+ pattern: /::order::OrderPaidEvent/i,
406
+ business_meaning: "Order has been paid by the customer",
407
+ category: "fund_flow",
408
+ side_effect: "Funds are escrowed; merchant can advance the order to delivery",
409
+ },
410
+ {
411
+ pattern: /::order::OrderAdvancedEvent/i,
412
+ business_meaning: "Order advanced to the next state in the Machine graph",
413
+ category: "state_change",
414
+ },
415
+ {
416
+ pattern: /::order::OrderCompletedEvent/i,
417
+ business_meaning: "Order has been completed",
418
+ category: "lifecycle",
419
+ side_effect: "Allocation can be executed to distribute funds to recipients",
420
+ },
421
+ {
422
+ pattern: /::order::OrderRefundedEvent|::order::RefundEvent/i,
423
+ business_meaning: "Order was refunded",
424
+ category: "fund_flow",
425
+ side_effect: "Escrowed funds returned to the customer",
426
+ },
427
+ {
428
+ pattern: /::order::OrderCancelledEvent/i,
429
+ business_meaning: "Order was cancelled",
430
+ category: "lifecycle",
431
+ },
432
+ {
433
+ pattern: /::reward::RewardCreatedEvent/i,
434
+ business_meaning: "A new Reward pool was created",
435
+ category: "lifecycle",
436
+ },
437
+ {
438
+ pattern: /::reward::RewardClaimedEvent|::reward::ClaimedEvent/i,
439
+ business_meaning: "Reward was claimed by a claimant",
440
+ category: "fund_flow",
441
+ side_effect: "Funds transferred from the reward pool to the claimant",
442
+ },
443
+ {
444
+ pattern: /::treasury::DepositEvent/i,
445
+ business_meaning: "Funds were deposited into the Treasury",
446
+ category: "fund_flow",
447
+ },
448
+ {
449
+ pattern: /::treasury::WithdrawEvent|::treasury::ReleaseEvent/i,
450
+ business_meaning: "Funds were withdrawn from the Treasury",
451
+ category: "fund_flow",
452
+ },
453
+ {
454
+ pattern: /::demand::DemandCreatedEvent/i,
455
+ business_meaning: "A new Demand (bounty) was posted",
456
+ category: "lifecycle",
457
+ },
458
+ {
459
+ pattern: /::demand::PresenterSubmittedEvent|::demand::PresentedEvent/i,
460
+ business_meaning: "A presenter submitted a solution for the Demand",
461
+ category: "state_change",
462
+ },
463
+ {
464
+ pattern: /::permission::PermissionGrantedEvent/i,
465
+ business_meaning: "Permission was granted to an address",
466
+ category: "permission",
467
+ },
468
+ {
469
+ pattern: /::permission::PermissionRevokedEvent/i,
470
+ business_meaning: "Permission was revoked from an address",
471
+ category: "permission",
472
+ },
473
+ {
474
+ pattern: /::guard::GuardRejectedEvent|::guard::RejectedEvent/i,
475
+ business_meaning: "Guard verification rejected the operation",
476
+ category: "guard",
477
+ side_effect: "Operation was blocked; user must satisfy the Guard's submission requirements",
478
+ },
479
+ {
480
+ pattern: /::guard::GuardPassedEvent|::guard::AcceptedEvent/i,
481
+ business_meaning: "Guard verification passed",
482
+ category: "guard",
483
+ },
484
+ {
485
+ pattern: /::arbitration::ArbitrationRequestedEvent|::arbitration::RequestedEvent/i,
486
+ business_meaning: "Arbitration was requested for an Order",
487
+ category: "state_change",
488
+ side_effect: "Order is now in dispute; arbiter will rule on the outcome",
489
+ },
490
+ {
491
+ pattern: /::arbitration::ArbitrationResolvedEvent|::arbitration::ResolvedEvent|::arbitration::CompensationEvent/i,
492
+ business_meaning: "Arbitration was resolved (compensation or refund awarded)",
493
+ category: "fund_flow",
494
+ side_effect: "Funds redistributed per arbiter's ruling",
495
+ },
496
+ {
497
+ pattern: /::allocation::AllocatedEvent|::allocation::DistributedEvent/i,
498
+ business_meaning: "Funds were distributed to allocation recipients",
499
+ category: "fund_flow",
500
+ },
501
+ {
502
+ pattern: /::progress::ProgressUpdatedEvent|::progress::UpdatedEvent/i,
503
+ business_meaning: "Order progress was updated",
504
+ category: "state_change",
505
+ },
506
+ ];
507
+ function extractRelatedObject(event) {
508
+ if (!event || typeof event !== "object")
509
+ return undefined;
510
+ const fields = event.fields ?? event.payload ?? event;
511
+ if (typeof fields !== "object")
512
+ return undefined;
513
+ for (const key of ["object_id", "objectId", "id", "parent", "service", "order", "machine", "reward", "treasury"]) {
514
+ const v = fields[key];
515
+ if (typeof v === "string" && v.startsWith("0x") && v.length >= 6)
516
+ return v;
517
+ }
518
+ return undefined;
519
+ }
520
+ export function eventToSemantic(event) {
521
+ const eventType = String(event?.type ?? event?.event_type ?? "");
522
+ const rule = EVENT_SEMANTIC_RULES.find((r) => r.pattern.test(eventType));
523
+ if (!rule) {
524
+ return {
525
+ event_type: eventType,
526
+ business_meaning: "Unknown event",
527
+ category: "other",
528
+ };
529
+ }
530
+ const related = rule.extractRelatedObject ? rule.extractRelatedObject(event) : extractRelatedObject(event);
531
+ const result = {
532
+ event_type: eventType,
533
+ business_meaning: rule.business_meaning,
534
+ category: rule.category,
535
+ };
536
+ if (related)
537
+ result.related_object = related;
538
+ if (rule.side_effect)
539
+ result.side_effect = rule.side_effect;
540
+ return result;
541
+ }
542
+ export function annotateEvents(events) {
543
+ if (!Array.isArray(events))
544
+ return [];
545
+ return events.map(eventToSemantic);
546
+ }
547
+ const NEXT_ACTION_RULES = [
548
+ {
549
+ when: (ot) => ot === "service",
550
+ action: "publish the Service when configuration is complete",
551
+ reason: "Service must be published before customers can order",
552
+ tool: "onchain_operations (service with publish:true)",
553
+ priority: "recommended",
554
+ },
555
+ {
556
+ when: (ot) => ot === "service",
557
+ action: "add Machine nodes to define the service workflow",
558
+ reason: "Machine drives order state transitions",
559
+ tool: "onchain_operations (machine)",
560
+ priority: "recommended",
561
+ },
562
+ {
563
+ when: (ot) => ot === "machine",
564
+ action: "bind Progress to track order execution",
565
+ reason: "Progress provides customer-visible status updates",
566
+ tool: "onchain_operations (progress)",
567
+ priority: "recommended",
568
+ },
569
+ {
570
+ when: (ot) => ot === "order",
571
+ action: "wait for customer payment or proceed to allocation",
572
+ reason: "Order lifecycle: payment → allocation → completion",
573
+ priority: "optional",
574
+ },
575
+ {
576
+ when: (ot, data) => ot === "order" && data?.transfer_to !== undefined,
577
+ action: "inform the end customer about the supplier/sub-contractor who will fulfill this order",
578
+ reason: "O-5 procurement sub-order transparency: customers have the right to know who fulfills their order",
579
+ tool: "messenger_operation (notify customer)",
580
+ priority: "recommended",
581
+ },
582
+ {
583
+ when: (ot) => ot === "demand",
584
+ action: "wait for presenter submissions or evaluate existing ones",
585
+ reason: "Demand lifecycle: presenters submit solutions for reward",
586
+ priority: "optional",
587
+ },
588
+ {
589
+ when: (ot) => ot === "reward",
590
+ action: "deposit funds into the reward pool",
591
+ reason: "Reward pool must be funded before claimants can withdraw",
592
+ tool: "onchain_operations (treasury)",
593
+ priority: "recommended",
594
+ },
595
+ {
596
+ when: (ot) => ot === "bridge_cross_chain_wow_to_evm",
597
+ action: "poll query_transfer_status until bridge signs (~1-5 min), then call claim_wow_to_evm to complete",
598
+ reason: "Cross-chain WOW→EVM is a 2-step process: deposit first, then claim after bridge confirmation",
599
+ tool: "bridge_operation (query_transfer_status, then claim_wow_to_evm)",
600
+ priority: "required",
601
+ },
602
+ {
603
+ when: (ot) => ot === "bridge_cross_chain_evm_to_wow",
604
+ action: "poll query_transfer_status to monitor auto-claim progress (~10-20 min)",
605
+ reason: "EVM→WOW cross-chain auto-claims; monitor progress but no manual action needed",
606
+ tool: "bridge_operation (query_transfer_status)",
607
+ priority: "recommended",
608
+ },
609
+ {
610
+ when: (ot) => ot === "bridge_claim_wow_to_evm",
611
+ action: "verify recipient EVM balance updated",
612
+ reason: "Claim completes the cross-chain transfer; verify funds arrived on EVM side",
613
+ tool: "bridge_operation (query_active_evm_account)",
614
+ priority: "recommended",
615
+ },
616
+ {
617
+ when: (ot) => ot === "bridge_withdraw",
618
+ action: "verify WOW balance updated",
619
+ reason: "Withdrawal moves funds from active EVM account to WOW; verify balance",
620
+ tool: "account_operation (balance)",
621
+ priority: "recommended",
622
+ },
623
+ {
624
+ when: (ot) => ot === "account_new",
625
+ action: "claim faucet tokens for gas if on testnet, then proceed to create Service",
626
+ reason: "New account needs gas tokens before on-chain operations",
627
+ tool: "account_operation (faucet)",
628
+ priority: "recommended",
629
+ },
630
+ {
631
+ when: (ot) => ot === "account_faucet",
632
+ action: "proceed to create Permission and Service objects",
633
+ reason: "Account is now funded; start building your service",
634
+ tool: "onchain_operations (permission, service)",
635
+ priority: "recommended",
636
+ },
637
+ {
638
+ when: (ot) => ot === "query_toolkit",
639
+ action: "use the queried object data to plan next operations",
640
+ reason: "Query results reveal current object states for decision-making",
641
+ priority: "optional",
642
+ },
643
+ ];
644
+ function inferNextActions(operation_type, data, status) {
645
+ return NEXT_ACTION_RULES
646
+ .filter((r) => r.when(operation_type, data, status))
647
+ .map((r) => ({
648
+ action: r.action,
649
+ reason: r.reason,
650
+ tool: r.tool,
651
+ priority: r.priority,
652
+ }));
653
+ }
654
+ function inferWarnings(operation_type, data, _safeResult) {
655
+ const warnings = [];
656
+ if (operation_type === "service" && data?.order_allocators === undefined) {
657
+ warnings.push("order_allocators not configured; order funds cannot be distributed automatically");
658
+ }
659
+ if (operation_type === "reward" && (data?.balance === "0" || data?.balance === 0)) {
660
+ warnings.push("Reward pool balance is zero; claimants cannot withdraw");
661
+ }
662
+ if (operation_type === "order" && data?.transfer_to !== undefined) {
663
+ warnings.push("[TRANSPARENCY] Order ownership is being transferred (likely to a supplier/sub-contractor). " +
664
+ "Ensure the end customer is informed about who fulfills their order — this builds trust and is required for procurement sub-orders.");
665
+ }
666
+ return warnings;
667
+ }
668
+ function composeSummary(intent, status, created, modified, released) {
669
+ const intentVerb = intent.replace(/_/g, " ");
670
+ if (status === "failed")
671
+ return `Failed to ${intentVerb}`;
672
+ if (status === "pending_input")
673
+ return `${intentVerb} requires Guard submission to proceed`;
674
+ const parts = [];
675
+ if (created.length)
676
+ parts.push(`created ${created.length} object(s)`);
677
+ if (modified.length)
678
+ parts.push(`modified ${modified.length} object(s)`);
679
+ if (released.length) {
680
+ if (intent === "allocate_funds") {
681
+ const details = released.map(f => {
682
+ const amt = f.amount;
683
+ const coin = shortCoinType(f.coinType);
684
+ const recipient = f.to ? shortAddr(f.to) : null;
685
+ const sender = f.from ? shortAddr(f.from) : null;
686
+ if (recipient)
687
+ return `${amt} ${coin} → ${recipient}`;
688
+ if (sender)
689
+ return `${amt} ${coin} from ${sender}`;
690
+ return `${amt} ${coin}`;
691
+ }).join("; ");
692
+ parts.push(`distributed: ${details}`);
693
+ }
694
+ else {
695
+ parts.push(`${released.length} fund movement(s)`);
696
+ }
697
+ }
698
+ return `Successfully ${intentVerb}${parts.length ? ` (${parts.join(", ")})` : ""}`;
699
+ }
700
+ function shortAddr(addr) {
701
+ if (addr.length > 14) {
702
+ return addr.slice(0, 8) + "..." + addr.slice(-4);
703
+ }
704
+ return addr;
705
+ }
706
+ function shortCoinType(coinType) {
707
+ if (!coinType)
708
+ return "coin";
709
+ const parts = coinType.split("::");
710
+ return parts[parts.length - 1] || coinType;
711
+ }
712
+ function buildCustomerAdvice(operation_type, data, safeResult) {
713
+ if (!isRuntimeEnabled("customer_intelligence"))
714
+ return undefined;
715
+ let stage;
716
+ if (operation_type === "order") {
717
+ stage = "preorder";
718
+ }
719
+ else if (operation_type === "query_toolkit" || operation_type === "onchain_table_data" || operation_type === "onchain_events") {
720
+ stage = "browse";
721
+ }
722
+ else if (operation_type === "service") {
723
+ stage = "evaluate";
724
+ }
725
+ else {
726
+ return undefined;
727
+ }
728
+ const serviceId = data?.service_name ?? data?.service_id ?? data?.service ?? data?.name;
729
+ const orderId = data?.order_name ?? data?.order_id ?? data?.order;
730
+ let servicePrice;
731
+ if (data?.price !== undefined) {
732
+ try {
733
+ servicePrice = BigInt(String(data.price));
734
+ }
735
+ catch { }
736
+ }
737
+ if (servicePrice === undefined && safeResult?.price !== undefined) {
738
+ try {
739
+ servicePrice = BigInt(String(safeResult.price));
740
+ }
741
+ catch { }
742
+ }
743
+ const hasArbitration = booleanFromSignals(data?.arb_name !== undefined || data?.arbitration !== undefined, data?.arb === false);
744
+ const hasCompensation = booleanFromSignals(data?.compensation_fund !== undefined || data?.compensation !== undefined, false);
745
+ const hasRefundPath = booleanFromSignals(data?.refund !== undefined, false);
746
+ const hasMessenger = booleanFromSignals(data?.um_name !== undefined || data?.messenger !== undefined, false);
747
+ const noArbitration = hasArbitration === false;
748
+ const noCompensation = hasCompensation === false;
749
+ const riskScore = typeof data?.risk_score === "number" ? data.risk_score
750
+ : typeof safeResult?.risk_score === "number" ? safeResult.risk_score : undefined;
751
+ const riskLevel = data?.risk_level ?? safeResult?.risk_level;
752
+ const profile = getProfile();
753
+ const userMinTrust = profile.risk_appetite === "conservative" ? 70
754
+ : profile.risk_appetite === "aggressive" ? 30 : 50;
755
+ const ctx = {
756
+ stage,
757
+ service_id: serviceId,
758
+ order_id: orderId,
759
+ service_price: servicePrice,
760
+ has_arbitration: hasArbitration,
761
+ has_compensation: hasCompensation,
762
+ has_refund_path: hasRefundPath,
763
+ has_messenger: hasMessenger,
764
+ risk_score: riskScore,
765
+ risk_level: riskLevel,
766
+ user_min_trust_score: userMinTrust,
767
+ user_require_arbitration: profile.risk_appetite === "conservative",
768
+ user_require_compensation: profile.risk_appetite === "conservative",
769
+ };
770
+ const reminders = generateReminders(ctx);
771
+ const recommendations = [];
772
+ for (const r of reminders) {
773
+ if (r.action)
774
+ recommendations.push(r.action);
775
+ }
776
+ if (noArbitration && !recommendations.some((r) => r.includes("仲裁"))) {
777
+ recommendations.push("要求商家配置 Arbitration 服务后再下单");
778
+ }
779
+ if (noCompensation && !recommendations.some((r) => r.includes("赔偿金"))) {
780
+ recommendations.push("要求商家设置 compensation_fund(赔偿金)以保障订单失败时自动赔付");
781
+ }
782
+ const advice = {
783
+ recommendations,
784
+ reminders: reminders.map((r) => ({
785
+ id: r.id,
786
+ stage: r.stage,
787
+ priority: r.priority,
788
+ message: r.message,
789
+ action: r.action,
790
+ })),
791
+ };
792
+ if (riskScore !== undefined)
793
+ advice.risk_score = riskScore;
794
+ if (riskLevel !== undefined)
795
+ advice.risk_level = riskLevel;
796
+ return advice;
797
+ }
798
+ export function buildSemantic(safeResult, context) {
799
+ if (!context)
800
+ return undefined;
801
+ const intent = inferIntent(context.operation_type, context.data);
802
+ const status = inferStatus(safeResult);
803
+ const objectChanges = safeResult?.objectChanges || [];
804
+ const balanceChanges = safeResult?.balanceChanges || [];
805
+ const events = safeResult?.events || [];
806
+ const created = tagObjectRoles(objectChanges.filter((c) => c?.type === "created"));
807
+ const modified = tagObjectRoles(objectChanges.filter((c) => c?.type === "mutated" || c?.type === "published"));
808
+ const released = tagFundRoles(balanceChanges, context.operation_type, context.data, events);
809
+ const annotatedEvents = annotateEvents(events);
810
+ const next_actions = inferNextActions(context.operation_type, context.data, status);
811
+ const warnings = inferWarnings(context.operation_type, context.data, safeResult);
812
+ if (context.pre_warnings && context.pre_warnings.length > 0) {
813
+ warnings.push(...context.pre_warnings);
814
+ }
815
+ if (context.operation_type === "service" && context.data?.publish === true) {
816
+ const findings = auditService(context.data);
817
+ for (const f of findings) {
818
+ const prefix = f.severity === "error" ? "[AUDIT ERROR] " : f.severity === "warning" ? "[AUDIT] " : "[INFO] ";
819
+ warnings.push(prefix + f.message);
820
+ }
821
+ }
822
+ let experience;
823
+ if (isRuntimeEnabled("experience_layer")) {
824
+ try {
825
+ const feedback = getExperienceFeedback(context.operation_type, context.data, intent);
826
+ if (feedback) {
827
+ experience = feedback;
828
+ }
829
+ const outcome = status === "success" ? "success" : status === "failed" ? "failed" : "partial";
830
+ const referencedObjects = [...created, ...modified].map((o) => o.id).filter(Boolean);
831
+ recordOperationOutcome(context.operation_type, context.data, intent, outcome, undefined, referencedObjects);
832
+ }
833
+ catch {
834
+ }
835
+ }
836
+ let evolution_context;
837
+ if (isRuntimeEnabled("industry_evolution")) {
838
+ try {
839
+ const industryHint = (typeof context.data?.industry === "string" && context.data.industry.trim())
840
+ ? context.data.industry.trim()
841
+ : undefined;
842
+ if (industryHint) {
843
+ const outcome = status === "success"
844
+ ? { success: true }
845
+ : { success: false, error_code: inferErrorCodeForSignal(safeResult) };
846
+ recordIndustrySignal(industryHint, { type: context.operation_type, data: context.data }, outcome);
847
+ }
848
+ if (industryHint) {
849
+ const evoCtx = injectEvolutionContext(undefined, industryHint);
850
+ if (evoCtx && (evoCtx.industry_signal || evoCtx.evolution_advice || evoCtx.confidence > 0)) {
851
+ evolution_context = evoCtx;
852
+ }
853
+ }
854
+ }
855
+ catch {
856
+ }
857
+ }
858
+ let service_status;
859
+ if (isRuntimeEnabled("semantic_rich")) {
860
+ try {
861
+ const all = listServices();
862
+ const active = all.filter((s) => s.enabled).map((s) => s.name);
863
+ const inactive = all.filter((s) => !s.enabled).map((s) => s.name);
864
+ service_status = {
865
+ active,
866
+ inactive: inactive.length ? inactive : undefined,
867
+ };
868
+ }
869
+ catch {
870
+ }
871
+ }
872
+ let customer_advice;
873
+ try {
874
+ customer_advice = buildCustomerAdvice(context.operation_type, context.data, safeResult);
875
+ }
876
+ catch {
877
+ }
878
+ return {
879
+ intent,
880
+ status,
881
+ summary: composeSummary(intent, status, created, modified, released),
882
+ created: created.length ? created : undefined,
883
+ modified: modified.length ? modified : undefined,
884
+ released: released.length ? released : undefined,
885
+ events: annotatedEvents.length ? annotatedEvents : undefined,
886
+ next_actions: next_actions.length ? next_actions : undefined,
887
+ warnings: warnings.length ? warnings : undefined,
888
+ experience,
889
+ service_status,
890
+ customer_advice,
891
+ evolution_context,
892
+ };
893
+ }
894
+ function inferErrorCodeForSignal(safeResult) {
895
+ if (!safeResult)
896
+ return undefined;
897
+ if (typeof safeResult.error === "string")
898
+ return safeResult.error.slice(0, 64);
899
+ return undefined;
900
+ }
901
+ export function buildDataSemantic(data, context, isError, errorMsg) {
902
+ if (!context)
903
+ return undefined;
904
+ const intent = inferIntent(context.operation_type, context.data);
905
+ const warnings = [];
906
+ let status;
907
+ if (isError) {
908
+ status = "failed";
909
+ }
910
+ else {
911
+ status = "success";
912
+ if (Array.isArray(data) && data.length === 0) {
913
+ status = "partial";
914
+ warnings.push("no results found");
915
+ }
916
+ else if (data === null || data === undefined) {
917
+ status = "partial";
918
+ warnings.push("no results found");
919
+ }
920
+ else if (typeof data === "object" && !Array.isArray(data)) {
921
+ const values = Object.values(data);
922
+ if (values.length > 0 && values.every((v) => (Array.isArray(v) ? v.length === 0 : v === null || v === undefined))) {
923
+ status = "partial";
924
+ warnings.push("no results found");
925
+ }
926
+ }
927
+ }
928
+ const next_actions = inferNextActions(context.operation_type, context.data, status);
929
+ let annotatedEvents;
930
+ if (!isError && context.operation_type === "onchain_events") {
931
+ const eventsArray = Array.isArray(data) ? data : (data?.data && Array.isArray(data.data) ? data.data : null);
932
+ if (eventsArray) {
933
+ annotatedEvents = annotateEvents(eventsArray);
934
+ if (annotatedEvents.length === 0)
935
+ annotatedEvents = undefined;
936
+ }
937
+ }
938
+ const intentVerb = intent.replace(/_/g, " ");
939
+ let summary;
940
+ if (status === "failed") {
941
+ summary = `Failed to ${intentVerb}`;
942
+ }
943
+ else if (status === "partial") {
944
+ summary = `${intentVerb} completed with no results`;
945
+ }
946
+ else {
947
+ summary = `Successfully ${intentVerb}`;
948
+ }
949
+ let service_status;
950
+ if (isRuntimeEnabled("semantic_rich")) {
951
+ try {
952
+ const all = listServices();
953
+ const active = all.filter((s) => s.enabled).map((s) => s.name);
954
+ const inactive = all.filter((s) => !s.enabled).map((s) => s.name);
955
+ service_status = {
956
+ active,
957
+ inactive: inactive.length ? inactive : undefined,
958
+ };
959
+ }
960
+ catch {
961
+ }
962
+ }
963
+ let customer_advice;
964
+ if (!isError) {
965
+ try {
966
+ customer_advice = buildCustomerAdvice(context.operation_type, context.data, data);
967
+ }
968
+ catch {
969
+ }
970
+ }
971
+ return {
972
+ intent,
973
+ status,
974
+ summary,
975
+ events: annotatedEvents,
976
+ next_actions: next_actions.length ? next_actions : undefined,
977
+ warnings: warnings.length ? warnings : undefined,
978
+ service_status,
979
+ customer_advice,
980
+ };
981
+ }