@wowok/agent-mcp 2.7.0 → 2.7.2

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 (427) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/customer-advice.js +1 -130
  4. package/dist/customer/index.js +1 -11
  5. package/dist/customer/industry-risks.js +1 -438
  6. package/dist/customer/info-puzzle.js +1 -681
  7. package/dist/customer/order-monitor.js +1 -328
  8. package/dist/customer/order-strategy.js +1 -373
  9. package/dist/customer/post-purchase.js +1 -351
  10. package/dist/customer/preorder-compare.js +1 -34
  11. package/dist/customer/reminder-system.js +1 -316
  12. package/dist/customer/risk-assessment.d.ts +5 -1
  13. package/dist/customer/risk-assessment.js +1 -397
  14. package/dist/customer/types.js +1 -13
  15. package/dist/customer/user-preferences.js +1 -460
  16. package/dist/evaluation/arbitration-game.d.ts +23 -0
  17. package/dist/evaluation/arbitration-game.js +1 -0
  18. package/dist/evaluation/builtins/demand-match.d.ts +15 -0
  19. package/dist/evaluation/builtins/demand-match.js +1 -0
  20. package/dist/evaluation/builtins/index.d.ts +3 -0
  21. package/dist/evaluation/builtins/index.js +1 -0
  22. package/dist/evaluation/builtins/service-risk.d.ts +6 -0
  23. package/dist/evaluation/builtins/service-risk.js +1 -0
  24. package/dist/evaluation/capability.d.ts +50 -0
  25. package/dist/evaluation/capability.js +1 -0
  26. package/dist/evaluation/composer.d.ts +13 -0
  27. package/dist/evaluation/composer.js +1 -0
  28. package/dist/evaluation/engine.d.ts +18 -0
  29. package/dist/evaluation/engine.js +1 -0
  30. package/dist/evaluation/extract.d.ts +30 -0
  31. package/dist/evaluation/extract.js +1 -0
  32. package/dist/evaluation/game-strategy.d.ts +27 -0
  33. package/dist/evaluation/game-strategy.js +1 -0
  34. package/dist/evaluation/gap.d.ts +2 -0
  35. package/dist/evaluation/gap.js +1 -0
  36. package/dist/evaluation/index.d.ts +12 -0
  37. package/dist/evaluation/index.js +1 -0
  38. package/dist/evaluation/node-game.d.ts +62 -0
  39. package/dist/evaluation/node-game.js +1 -0
  40. package/dist/evaluation/region.d.ts +10 -0
  41. package/dist/evaluation/region.js +1 -0
  42. package/dist/evaluation/types.d.ts +77 -0
  43. package/dist/evaluation/types.js +1 -0
  44. package/dist/evaluation/user-injection.d.ts +6 -0
  45. package/dist/evaluation/user-injection.js +1 -0
  46. package/dist/examples/education-contact-create.json +40 -0
  47. package/dist/examples/freelance-contact-create.json +40 -0
  48. package/dist/examples/insurance-machine-create.json +1 -1
  49. package/dist/examples/insurance-service-allocators.json +1 -1
  50. package/dist/examples/machine-publish.json +1 -1
  51. package/dist/examples/rental-ziroom-service-create.json +1 -1
  52. package/dist/examples/retail-adv-guard-messenger-proof-create.json +1 -1
  53. package/dist/examples/retail-myshop-service-create.json +1 -1
  54. package/dist/examples/retail-myshop-service-customer-required.json +1 -1
  55. package/dist/examples/subscription-contact-create.json +40 -0
  56. package/dist/examples/threebody-machine-create.json +1 -1
  57. package/dist/examples/travel-machine-create.json +1 -1
  58. package/dist/examples/travel-service-create.json +1 -1
  59. package/dist/experience/experience-reuse.js +1 -103
  60. package/dist/experience/index.js +1 -5
  61. package/dist/experience/intent-distill.js +1 -83
  62. package/dist/experience/realtime-feedback.js +1 -94
  63. package/dist/experience/types.js +1 -1
  64. package/dist/experience/user-profile.js +1 -171
  65. package/dist/extensions/business-modules.js +1 -287
  66. package/dist/extensions/capability-manifest.js +1 -781
  67. package/dist/extensions/constraint-registry.js +1 -198
  68. package/dist/extensions/index.js +1 -6
  69. package/dist/extensions/metric-registry.js +1 -257
  70. package/dist/extensions/mode-evaluator.js +1 -170
  71. package/dist/extensions/modes.js +1 -499
  72. package/dist/extensions/registry.js +1 -717
  73. package/dist/extensions/types.js +1 -1
  74. package/dist/harness/auto-escalation.js +1 -68
  75. package/dist/harness/checkpoint.js +1 -129
  76. package/dist/harness/index.js +1 -78
  77. package/dist/harness/plan.js +1 -276
  78. package/dist/harness/recover.js +1 -139
  79. package/dist/harness/types.js +1 -1
  80. package/dist/harness/verify.js +1 -237
  81. package/dist/index.js +1 -273
  82. package/dist/intent/enrich.d.ts +1 -0
  83. package/dist/intent/enrich.js +1 -0
  84. package/dist/intent/index.d.ts +23 -0
  85. package/dist/intent/index.js +1 -0
  86. package/dist/intent/matcher.d.ts +2 -0
  87. package/dist/intent/matcher.js +1 -0
  88. package/dist/intent/store.d.ts +19 -0
  89. package/dist/intent/store.js +1 -0
  90. package/dist/intent/types.d.ts +33 -0
  91. package/dist/intent/types.js +1 -0
  92. package/dist/knowledge/acquisition-flywheel.js +1 -192
  93. package/dist/knowledge/allocation-confirm.js +1 -534
  94. package/dist/knowledge/allocation-context.js +1 -249
  95. package/dist/knowledge/allocation-ledger.js +1 -463
  96. package/dist/knowledge/allocation-puzzle.js +1 -298
  97. package/dist/knowledge/allocation-risk.js +1 -568
  98. package/dist/knowledge/allocation-templates.js +1 -970
  99. package/dist/knowledge/allocation-translation.js +1 -585
  100. package/dist/knowledge/arb-risk.js +1 -210
  101. package/dist/knowledge/arbitration-confirm.js +1 -559
  102. package/dist/knowledge/arbitration-context.js +1 -505
  103. package/dist/knowledge/arbitration-ledger.js +1 -521
  104. package/dist/knowledge/arbitration-puzzle.js +1 -304
  105. package/dist/knowledge/arbitration-risk.js +1 -433
  106. package/dist/knowledge/arbitration-templates.js +1 -276
  107. package/dist/knowledge/arbitration-translation.js +1 -487
  108. package/dist/knowledge/arbitration-trust.js +1 -117
  109. package/dist/knowledge/audit-rules.js +1 -141
  110. package/dist/knowledge/bridge-risk.js +1 -263
  111. package/dist/knowledge/contact-risk.js +1 -200
  112. package/dist/knowledge/contact-templates.d.ts +27 -0
  113. package/dist/knowledge/contact-templates.js +1 -0
  114. package/dist/knowledge/demand-confirm.js +1 -206
  115. package/dist/knowledge/demand-matching.js +1 -132
  116. package/dist/knowledge/demand-risk.js +1 -240
  117. package/dist/knowledge/demand-translation.js +1 -354
  118. package/dist/knowledge/deployment-scanner.js +1 -823
  119. package/dist/knowledge/dynamic-pricing.js +1 -87
  120. package/dist/knowledge/examples-scanner-cli.js +1 -26
  121. package/dist/knowledge/examples-scanner.js +1 -825
  122. package/dist/knowledge/flywheel-loop.js +1 -404
  123. package/dist/knowledge/fund-layer.js +1 -973
  124. package/dist/knowledge/glossary.js +1 -211
  125. package/dist/knowledge/guard-confirm.js +1 -406
  126. package/dist/knowledge/guard-context.js +1 -287
  127. package/dist/knowledge/guard-design-patterns.js +1 -360
  128. package/dist/knowledge/guard-ledger.js +1 -260
  129. package/dist/knowledge/guard-lint.js +1 -670
  130. package/dist/knowledge/guard-migration.js +1 -228
  131. package/dist/knowledge/guard-puzzle.js +1 -805
  132. package/dist/knowledge/guard-render.js +1 -700
  133. package/dist/knowledge/guard-risk.js +1 -1879
  134. package/dist/knowledge/guard-submission-prompt.js +1 -171
  135. package/dist/knowledge/guard-templates.js +1 -1105
  136. package/dist/knowledge/guard-translation.js +1 -1119
  137. package/dist/knowledge/index.js +1 -436
  138. package/dist/knowledge/industry-evolution.js +1 -323
  139. package/dist/knowledge/industry-generalizer.js +1 -381
  140. package/dist/knowledge/industry-registry.js +1 -174
  141. package/dist/knowledge/intent-metrics.d.ts +4 -3
  142. package/dist/knowledge/intent-metrics.js +1 -566
  143. package/dist/knowledge/machine-confirm.js +1 -559
  144. package/dist/knowledge/machine-context.js +1 -833
  145. package/dist/knowledge/machine-ledger.js +1 -338
  146. package/dist/knowledge/machine-puzzle.js +1 -494
  147. package/dist/knowledge/machine-render.js +1 -565
  148. package/dist/knowledge/machine-risk.js +1 -670
  149. package/dist/knowledge/machine-templates.js +1 -1597
  150. package/dist/knowledge/machine-topology.js +1 -234
  151. package/dist/knowledge/machine-translation.js +1 -513
  152. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  153. package/dist/knowledge/mcp-schema-audit.d.ts +1 -1
  154. package/dist/knowledge/mcp-schema-audit.js +1 -773
  155. package/dist/knowledge/onchain-constants.js +1 -35
  156. package/dist/knowledge/order-confirm.js +1 -573
  157. package/dist/knowledge/order-context.js +1 -390
  158. package/dist/knowledge/order-ledger.js +1 -341
  159. package/dist/knowledge/order-puzzle.js +1 -255
  160. package/dist/knowledge/order-risk.js +1 -653
  161. package/dist/knowledge/order-templates.js +1 -368
  162. package/dist/knowledge/order-translation.js +1 -550
  163. package/dist/knowledge/overrides-loader.js +1 -65
  164. package/dist/knowledge/passport-confirm.js +1 -531
  165. package/dist/knowledge/passport-context.js +1 -306
  166. package/dist/knowledge/passport-ledger.js +1 -282
  167. package/dist/knowledge/passport-puzzle.js +1 -333
  168. package/dist/knowledge/passport-risk.js +1 -450
  169. package/dist/knowledge/passport-templates.js +1 -568
  170. package/dist/knowledge/passport-translation.js +1 -516
  171. package/dist/knowledge/payment-risk.js +1 -249
  172. package/dist/knowledge/permission-confirm.js +1 -426
  173. package/dist/knowledge/permission-context.js +1 -224
  174. package/dist/knowledge/permission-ledger.js +1 -403
  175. package/dist/knowledge/permission-puzzle.js +1 -173
  176. package/dist/knowledge/permission-risk.js +1 -411
  177. package/dist/knowledge/permission-templates.js +1 -234
  178. package/dist/knowledge/permission-translation.js +1 -350
  179. package/dist/knowledge/personal-risk.js +1 -212
  180. package/dist/knowledge/process-model.js +1 -160
  181. package/dist/knowledge/progress-confirm.js +1 -456
  182. package/dist/knowledge/progress-context.js +1 -452
  183. package/dist/knowledge/progress-ledger.js +1 -330
  184. package/dist/knowledge/progress-puzzle.js +1 -219
  185. package/dist/knowledge/progress-risk.js +1 -461
  186. package/dist/knowledge/progress-templates.js +1 -228
  187. package/dist/knowledge/progress-translation.js +1 -405
  188. package/dist/knowledge/proof-confirm.js +1 -187
  189. package/dist/knowledge/proof-risk.js +1 -207
  190. package/dist/knowledge/proof-translation.js +1 -283
  191. package/dist/knowledge/registrar-risk.js +1 -217
  192. package/dist/knowledge/repository-confirm.js +1 -286
  193. package/dist/knowledge/repository-risk.js +1 -373
  194. package/dist/knowledge/repository-translation.js +1 -445
  195. package/dist/knowledge/reputation-rules.js +1 -99
  196. package/dist/knowledge/resource-risk.js +1 -157
  197. package/dist/knowledge/reward-confirm.js +1 -526
  198. package/dist/knowledge/reward-context.js +1 -504
  199. package/dist/knowledge/reward-ledger.js +1 -502
  200. package/dist/knowledge/reward-puzzle.js +1 -300
  201. package/dist/knowledge/reward-risk.js +1 -627
  202. package/dist/knowledge/reward-templates.js +1 -197
  203. package/dist/knowledge/reward-translation.js +1 -501
  204. package/dist/knowledge/safety-rules.js +1 -404
  205. package/dist/knowledge/scenario-modes.js +1 -321
  206. package/dist/knowledge/service-confirm.js +1 -807
  207. package/dist/knowledge/service-context.js +1 -403
  208. package/dist/knowledge/service-ledger.js +1 -609
  209. package/dist/knowledge/service-puzzle.js +1 -236
  210. package/dist/knowledge/service-risk.js +1 -615
  211. package/dist/knowledge/service-templates.js +1 -456
  212. package/dist/knowledge/service-translation.js +1 -622
  213. package/dist/knowledge/template-registry.d.ts +1 -1
  214. package/dist/knowledge/template-registry.js +1 -341
  215. package/dist/knowledge/tool-constraints.js +1 -195
  216. package/dist/knowledge/tools-reference.js +1 -155
  217. package/dist/knowledge/treasury-confirm.js +1 -512
  218. package/dist/knowledge/treasury-context.js +1 -363
  219. package/dist/knowledge/treasury-ledger.js +1 -300
  220. package/dist/knowledge/treasury-puzzle.js +1 -216
  221. package/dist/knowledge/treasury-risk.js +1 -440
  222. package/dist/knowledge/treasury-templates.js +1 -358
  223. package/dist/knowledge/treasury-translation.js +1 -498
  224. package/dist/knowledge/trust-metrics.js +1 -198
  225. package/dist/knowledge/util-risk.js +1 -135
  226. package/dist/loop-engineering/aggregate.js +1 -132
  227. package/dist/loop-engineering/context-collect.js +1 -83
  228. package/dist/loop-engineering/diagnose.js +1 -273
  229. package/dist/loop-engineering/improve.js +1 -405
  230. package/dist/loop-engineering/index.js +1 -4
  231. package/dist/loop-engineering/pipeline.js +1 -56
  232. package/dist/mode-market/index.js +1 -3
  233. package/dist/mode-market/registry.js +1 -124
  234. package/dist/mode-market/review.js +1 -214
  235. package/dist/mode-market/submission.js +1 -85
  236. package/dist/participation/collaborator-interest.d.ts +23 -0
  237. package/dist/participation/collaborator-interest.js +1 -0
  238. package/dist/participation/customer-interest.d.ts +25 -0
  239. package/dist/participation/customer-interest.js +1 -0
  240. package/dist/participation/merchant-interest.js +1 -100
  241. package/dist/participation/radar-core.d.ts +13 -3
  242. package/dist/participation/radar-core.js +1 -269
  243. package/dist/participation/supplier-interest.d.ts +25 -0
  244. package/dist/participation/supplier-interest.js +1 -0
  245. package/dist/persona/analyzer.d.ts +16 -0
  246. package/dist/persona/analyzer.js +1 -0
  247. package/dist/persona/bridge.d.ts +5 -0
  248. package/dist/persona/bridge.js +1 -0
  249. package/dist/persona/defaults.d.ts +4 -0
  250. package/dist/persona/defaults.js +1 -0
  251. package/dist/persona/experience-bridge.d.ts +3 -0
  252. package/dist/persona/experience-bridge.js +1 -0
  253. package/dist/persona/index.d.ts +18 -0
  254. package/dist/persona/index.js +1 -0
  255. package/dist/persona/model.d.ts +7 -0
  256. package/dist/persona/model.js +1 -0
  257. package/dist/persona/store.d.ts +19 -0
  258. package/dist/persona/store.js +1 -0
  259. package/dist/persona/types.d.ts +45 -0
  260. package/dist/persona/types.js +1 -0
  261. package/dist/project/business-puzzle.js +1 -383
  262. package/dist/project/context-assembly.js +1 -254
  263. package/dist/project/deployment-bridge.js +1 -120
  264. package/dist/project/deployment-doc.js +1 -1126
  265. package/dist/project/edit-planner.js +1 -1342
  266. package/dist/project/evaluation.js +1 -2011
  267. package/dist/project/game-theory.js +1 -177
  268. package/dist/project/graph-builder.js +1 -656
  269. package/dist/project/graph.js +1 -340
  270. package/dist/project/handlers.d.ts +5 -0
  271. package/dist/project/handlers.js +1 -1762
  272. package/dist/project/index.d.ts +1 -0
  273. package/dist/project/index.js +1 -301
  274. package/dist/project/intent-analyzer.js +1 -149
  275. package/dist/project/machine-nodes.js +1 -36
  276. package/dist/project/merchant-guide.js +1 -264
  277. package/dist/project/migration.js +1 -125
  278. package/dist/project/mode-actions.js +1 -309
  279. package/dist/project/namespace.js +1 -206
  280. package/dist/project/participation-radar.js +1 -428
  281. package/dist/project/pipeline-actions.js +1 -109
  282. package/dist/project/project-store.js +1 -422
  283. package/dist/project/query.js +1 -153
  284. package/dist/project/reverse-mapping.d.ts +34 -0
  285. package/dist/project/reverse-mapping.js +1 -0
  286. package/dist/project/risk-aggregator.js +1 -295
  287. package/dist/project/rollback-policy.js +1 -290
  288. package/dist/project/semantic-assembler.js +1 -345
  289. package/dist/project/semantic-graph.js +1 -245
  290. package/dist/project/stage-gate.js +1 -369
  291. package/dist/project/substep-trace.js +1 -332
  292. package/dist/project/task-tracker.js +1 -78
  293. package/dist/role/derivation.d.ts +18 -0
  294. package/dist/role/derivation.js +1 -0
  295. package/dist/role/index.d.ts +5 -0
  296. package/dist/role/index.js +1 -0
  297. package/dist/role/model.d.ts +8 -0
  298. package/dist/role/model.js +1 -0
  299. package/dist/role/resolution.d.ts +11 -0
  300. package/dist/role/resolution.js +1 -0
  301. package/dist/role/types.d.ts +11 -0
  302. package/dist/role/types.js +1 -0
  303. package/dist/rules.d.ts +2 -0
  304. package/dist/rules.js +1 -9
  305. package/dist/safety/confirm-gate.js +1 -88
  306. package/dist/safety/index.js +1 -3
  307. package/dist/safety/preview.js +1 -52
  308. package/dist/schema/call/allocation.js +1 -34
  309. package/dist/schema/call/arbitration.js +1 -113
  310. package/dist/schema/call/base.d.ts +15 -15
  311. package/dist/schema/call/base.js +1 -370
  312. package/dist/schema/call/bridge-handler.js +1 -265
  313. package/dist/schema/call/bridge.d.ts +7 -7
  314. package/dist/schema/call/bridge.js +1 -458
  315. package/dist/schema/call/contact.js +1 -37
  316. package/dist/schema/call/demand.js +1 -47
  317. package/dist/schema/call/guard.js +1 -161
  318. package/dist/schema/call/handler.js +1 -322
  319. package/dist/schema/call/index.js +1 -20
  320. package/dist/schema/call/machine.js +1 -193
  321. package/dist/schema/call/order.js +1 -35
  322. package/dist/schema/call/payment.js +1 -37
  323. package/dist/schema/call/permission-handler.js +1 -54
  324. package/dist/schema/call/permission.js +1 -105
  325. package/dist/schema/call/personal.js +1 -78
  326. package/dist/schema/call/progress.js +1 -47
  327. package/dist/schema/call/proof.js +1 -33
  328. package/dist/schema/call/repository.js +1 -77
  329. package/dist/schema/call/reward.js +1 -30
  330. package/dist/schema/call/semantic.js +1 -1657
  331. package/dist/schema/call/service.js +1 -178
  332. package/dist/schema/call/treasury.js +1 -71
  333. package/dist/schema/common/index.js +1 -407
  334. package/dist/schema/config/index.js +1 -68
  335. package/dist/schema/evaluation/index.d.ts +4436 -0
  336. package/dist/schema/evaluation/index.js +1 -0
  337. package/dist/schema/index.d.ts +4 -0
  338. package/dist/schema/index.js +1 -13
  339. package/dist/schema/intent-radar/index.d.ts +284 -0
  340. package/dist/schema/intent-radar/index.js +1 -0
  341. package/dist/schema/local/index.d.ts +21 -21
  342. package/dist/schema/local/index.js +1 -927
  343. package/dist/schema/local/wip.js +1 -187
  344. package/dist/schema/messenger/index.d.ts +7 -7
  345. package/dist/schema/messenger/index.js +1 -475
  346. package/dist/schema/operations.d.ts +7 -7
  347. package/dist/schema/operations.js +1 -520
  348. package/dist/schema/persona/index.d.ts +1985 -0
  349. package/dist/schema/persona/index.js +1 -0
  350. package/dist/schema/project/index.d.ts +96 -50
  351. package/dist/schema/project/index.js +1 -2057
  352. package/dist/schema/query/index.d.ts +423 -7
  353. package/dist/schema/query/index.js +1 -1640
  354. package/dist/schema/schema-query/index.js +1 -104
  355. package/dist/schema/schema-version.js +1 -76
  356. package/dist/schema/sync-layer4.d.ts +1 -1
  357. package/dist/schema/sync-layer4.js +1 -282
  358. package/dist/schema/task-status.d.ts +168 -0
  359. package/dist/schema/task-status.js +1 -0
  360. package/dist/schema/trust/index.js +1 -314
  361. package/dist/schema/utils/guard-parser.js +1 -419
  362. package/dist/schema/utils/guard-query-utils.js +1 -46
  363. package/dist/schema/utils/node-parser.js +1 -369
  364. package/dist/schema/utils/object-type-utils.js +1 -35
  365. package/dist/schema/utils/permission-index-utils.js +1 -7
  366. package/dist/schema/utils/permission-machine-check.js +1 -121
  367. package/dist/schema/utils/skills-recommendation.js +1 -77
  368. package/dist/schema-query/index.js +1 -810
  369. package/dist/schemas/account_operation.output.json +5 -2
  370. package/dist/schemas/bridge_operation.output.json +5 -2
  371. package/dist/schemas/evaluation_operation.output.json +782 -0
  372. package/dist/schemas/evaluation_operation.schema.json +990 -0
  373. package/dist/schemas/index.json +25 -1
  374. package/dist/schemas/intent_radar.output.json +232 -0
  375. package/dist/schemas/intent_radar.schema.json +138 -0
  376. package/dist/schemas/local_info_operation.output.json +5 -2
  377. package/dist/schemas/local_mark_operation.output.json +5 -2
  378. package/dist/schemas/messenger_operation.output.json +5 -2
  379. package/dist/schemas/onchain_events.output.json +5 -2
  380. package/dist/schemas/onchain_operations.output.json +5 -2
  381. package/dist/schemas/onchain_operations.schema.json +6 -6
  382. package/dist/schemas/onchain_operations_allocation.schema.json +1 -1
  383. package/dist/schemas/onchain_operations_machine.schema.json +2 -2
  384. package/dist/schemas/onchain_operations_service.schema.json +3 -3
  385. package/dist/schemas/onchain_table_data.output.json +6 -3
  386. package/dist/schemas/persona_operation.output.json +392 -0
  387. package/dist/schemas/persona_operation.schema.json +250 -0
  388. package/dist/schemas/project_operation.output.json +28 -8
  389. package/dist/schemas/query_task_status.output.json +115 -0
  390. package/dist/schemas/query_task_status.schema.json +24 -0
  391. package/dist/schemas/query_toolkit.output.json +9 -6
  392. package/dist/schemas/trust_score.schema.json +1 -1
  393. package/dist/schemas/wowok_buildin_info.output.json +132 -0
  394. package/dist/schemas/wowok_buildin_info.schema.json +14 -0
  395. package/dist/telemetry/index.js +1 -112
  396. package/dist/telemetry/redact.js +1 -23
  397. package/dist/telemetry/storage.js +1 -80
  398. package/dist/tools/handlers/bridge.js +1 -1
  399. package/dist/tools/handlers/config.js +1 -74
  400. package/dist/tools/handlers/evaluation.d.ts +2 -0
  401. package/dist/tools/handlers/evaluation.js +1 -0
  402. package/dist/tools/handlers/file-export.js +1 -90
  403. package/dist/tools/handlers/intent-radar.d.ts +2 -0
  404. package/dist/tools/handlers/intent-radar.js +1 -0
  405. package/dist/tools/handlers/local.js +1 -53
  406. package/dist/tools/handlers/messenger.js +1 -188
  407. package/dist/tools/handlers/onchain.js +1 -1082
  408. package/dist/tools/handlers/persona.d.ts +4 -0
  409. package/dist/tools/handlers/persona.js +1 -0
  410. package/dist/tools/handlers/project.js +1 -211
  411. package/dist/tools/handlers/query.js +1 -434
  412. package/dist/tools/handlers/schema-query.js +1 -176
  413. package/dist/tools/handlers/task-status.d.ts +0 -168
  414. package/dist/tools/handlers/task-status.js +1 -55
  415. package/dist/tools/handlers/trust.js +1 -380
  416. package/dist/tools/handlers/wip.js +1 -90
  417. package/dist/tools/index.js +1 -1306
  418. package/dist/tools/retry.js +1 -85
  419. package/dist/tools/rules-hook.js +1 -23
  420. package/dist/tools/shared.js +1 -130
  421. package/dist/tools/types.js +1 -1
  422. package/dist/tools/upgrade-check.d.ts +19 -0
  423. package/dist/tools/upgrade-check.js +1 -0
  424. package/dist/tools/wip-deploy-assist.d.ts +1 -1
  425. package/dist/tools/wip-deploy-assist.js +1 -278
  426. package/dist/tools/wrap.js +1 -500
  427. package/package.json +5 -3
@@ -1,1657 +1 @@
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/index.js";
5
- import { getProfile } from "../../experience/user-profile.js";
6
- import { injectEvolutionContext, recordIndustrySignal } from "../../knowledge/flywheel-loop.js";
7
- import { WException, getMoveErrorDescription, WErrors } from "@wowok/wowok";
8
- import { GUARDQUERY } from "@wowok/wowok";
9
- import { assessGuardRisksForOperation, getRiskSummary } from "../../knowledge/guard-risk.js";
10
- import { derivePuzzleFromCallData, getPuzzleStatusBooleans, getPendingQuestions, generateConfirmationText, } from "../../knowledge/guard-puzzle.js";
11
- import { inferSceneFromAction } from "../../knowledge/guard-ledger.js";
12
- import { extractGenericTokenType, registryDisplayHint, } from "../../knowledge/fund-layer.js";
13
- import { matchSemanticPattern } from "../../knowledge/guard-translation.js";
14
- function booleanFromSignals(positive, negative) {
15
- if (positive)
16
- return true;
17
- if (negative)
18
- return false;
19
- return undefined;
20
- }
21
- function deriveAdviceRole(operationType, data) {
22
- switch (operationType) {
23
- case "order":
24
- case "personal":
25
- case "demand":
26
- return "user";
27
- case "service":
28
- case "machine":
29
- case "permission":
30
- case "reward":
31
- case "repository":
32
- case "allocator":
33
- case "treasury":
34
- return "merchant";
35
- case "arbitration":
36
- if (data?.vote !== undefined)
37
- return "arbitrator";
38
- if (data?.dispute !== undefined)
39
- return "user";
40
- return undefined;
41
- default:
42
- return undefined;
43
- }
44
- }
45
- const ERROR_RULES = [
46
- {
47
- patterns: [
48
- /too\s*many\s*requests/i,
49
- /rate\s*limit/i,
50
- /429/i,
51
- /throttl/i,
52
- /faucet.*rate/i,
53
- /request.*limit.*exceeded/i,
54
- ],
55
- error_code: "rate_limit",
56
- retryable: true,
57
- recovery_hint: "Rate limit hit (HTTP 429). Wait with exponential backoff and retry. To check existing balance, use account_balance query.",
58
- },
59
- {
60
- patterns: [
61
- /gas.*budget.*exceeded/i,
62
- /out\s*of\s*gas/i,
63
- /gas\s*exceeded/i,
64
- /insufficient\s*gas/i,
65
- /not\s*enough\s*gas/i,
66
- /could not automatically determine a budget/i,
67
- /dry run failed.*budget/i,
68
- /Maximum gas/i,
69
- ],
70
- error_code: "gas_exceeded",
71
- retryable: true,
72
- recovery_hint: "Gas budget exceeded. Increase the gas_budget parameter or claim more gas tokens, then retry",
73
- },
74
- {
75
- patterns: [
76
- /insufficient\s*(balance|coin|fund)/i,
77
- /ENOTENOUGH/i,
78
- /not\s*enough\s*(coin|balance)/i,
79
- /coin\s*not\s*enough/i,
80
- /balance\s*not\s*enough/i,
81
- /stock\s*not\s*enough/i,
82
- /fee\s*not\s*enough/i,
83
- /Insufficient balance/i,
84
- ],
85
- error_code: "insufficient_balance",
86
- retryable: true,
87
- recovery_hint: "Claim faucet tokens via account_operation (faucet) then retry the call",
88
- },
89
- {
90
- patterns: [
91
- /bcs.*(error|fail|invalid)/i,
92
- /BCS serialization/i,
93
- /serialization\s*(failure|error)/i,
94
- /deserialization\s*(failure|error)/i,
95
- /invalid bcs type/i,
96
- /Out of range.*bcs/i,
97
- /Length out of range/i,
98
- /parse object content failed/i,
99
- ],
100
- error_code: "bcs_error",
101
- retryable: false,
102
- recovery_hint: "BCS serialization/deserialization error. Verify data types and structure match the expected schema",
103
- },
104
- {
105
- patterns: [
106
- /signature.*(invalid|fail|error|verif)/i,
107
- /invalid\s*signature/i,
108
- /signature\s*verification\s*failed/i,
109
- /bad\s*signature/i,
110
- /signing\s*fail/i,
111
- /crypto.*signature/i,
112
- /ed25519.*(fail|error|invalid)/i,
113
- /secp256k1.*(fail|error|invalid)/i,
114
- ],
115
- error_code: "signature_error",
116
- retryable: false,
117
- recovery_hint: "Signature verification failed. Check that the correct private key and network configuration are correct",
118
- },
119
- {
120
- patterns: [
121
- /config.*(not set|not found|invalid|missing)/i,
122
- /RPC\s*not\s*configured/i,
123
- /network.*not\s*specified/i,
124
- /protocol network not specified/i,
125
- /account persistent storage not set/i,
126
- /config persistent storage not set/i,
127
- /account persistent storage not found/i,
128
- /no\s*rpc\s*url/i,
129
- ],
130
- error_code: "config_error",
131
- retryable: false,
132
- recovery_hint: "Configuration error. Verify that network, RPC endpoints, and required environment variables are properly configured",
133
- },
134
- {
135
- patterns: [
136
- /network/i,
137
- /timeout/i,
138
- /ECONNRESET/i,
139
- /ETIMEDOUT/i,
140
- /ECONNREFUSED/i,
141
- /EAI_AGAIN/i,
142
- /RPC\s*(error|failed|unreachable)/i,
143
- /socket\s*hang\s*up/i,
144
- /fetch\s*failed/i,
145
- /connection\s*(refused|reset|lost)/i,
146
- /dns\s*(error|fail)/i,
147
- ],
148
- error_code: "network_error",
149
- retryable: true,
150
- recovery_hint: "Retry the call; if it persists, switch RPC endpoint or check connectivity",
151
- },
152
- {
153
- patterns: [
154
- /guard.*(reject|fail|denied|verif)/i,
155
- /verification\s*failed/i,
156
- /submission.*(invalid|fail|required)/i,
157
- /passport.*(invalid|fail|verif)/i,
158
- /move[._-]?abort.*guard/i,
159
- /Guard count exceeded limit/i,
160
- /Submission size exceeded limit/i,
161
- /Submission not found/i,
162
- /Guard not found/i,
163
- /Impact guard not found/i,
164
- ],
165
- error_code: "guard_rejected",
166
- retryable: false,
167
- recovery_hint: "Fill the Guard submission data (see the 'submission' field) and resubmit via call_with_submission",
168
- },
169
- {
170
- patterns: [
171
- /WIP file verification failed/i,
172
- /Failed to load WIP file/i,
173
- /WIP.*hash\s*mismatch/i,
174
- /Invalid WIP file structure/i,
175
- /wip.*not\s*found/i,
176
- /wip.*unreachable/i,
177
- /wip_file.*error/i,
178
- ],
179
- error_code: "wip_verification_failed",
180
- retryable: false,
181
- recovery_hint: [
182
- "WIP file must be publicly accessible via HTTP(S) URL — local file paths cannot be stored on-chain.",
183
- "Deployment options (pick one):",
184
- " 1. GitHub Pages (free, stable): upload .wip file to a repo, enable Pages, use raw URL.",
185
- " Example: https://<user>.github.io/<repo>/<file>.wip",
186
- " Or raw URL: https://raw.githubusercontent.com/<user>/<repo>/<branch>/<file>.wip",
187
- " 2. IPFS (free, decentralized): upload via Pinata (https://pinata.cloud) or nft.storage.",
188
- " Use the ipfs://<CID> or https://<gateway>/ipfs/<CID> URL form.",
189
- " Common gateways: https://ipfs.io/ipfs/, https://cloudflare-ipfs.com/ipfs/, https://dweb.link/ipfs/",
190
- " 3. User's own website: serve the .wip file from your static site.",
191
- " 4. Generate a fresh WIP file locally first via wip_file (type='generate'), upload it, then re-submit the URL.",
192
- "After updating the sale's wip URL, re-run the operation."
193
- ].join("\n"),
194
- },
195
- {
196
- patterns: [
197
- /already\s*publish/i,
198
- /immutable/i,
199
- /cannot\s*(modify|change|mutate)/i,
200
- /locked/i,
201
- /is\s*published/i,
202
- /Service already published/i,
203
- /Machine already published/i,
204
- /setting lock duration not exceeded/i,
205
- ],
206
- error_code: "immutable_violation",
207
- retryable: false,
208
- recovery_hint: "Object is in an immutable state (e.g. Service already published). Recreate the object if a different config is needed",
209
- },
210
- {
211
- patterns: [
212
- /permission/i,
213
- /unauthorized/i,
214
- /forbidden/i,
215
- /not\s*(the\s*)?owner/i,
216
- /access\s*denied/i,
217
- /no permission/i,
218
- /Permission denied/i,
219
- /Not the builder/i,
220
- /Not admin/i,
221
- /No operation permission/i,
222
- /Not the holder/i,
223
- ],
224
- error_code: "permission_denied",
225
- retryable: false,
226
- recovery_hint: "Use an account with the required permission, or pass permission_guard IDs via env.permission_guard",
227
- },
228
- {
229
- patterns: [
230
- /not\s*found/i,
231
- /does\s*not\s*exist/i,
232
- /ENOTFOUND/i,
233
- /no\s*such\s*object/i,
234
- /unknown\s*object/i,
235
- /account not found/i,
236
- /address not found/i,
237
- /token not found/i,
238
- /Node not found/i,
239
- /Policy not found/i,
240
- /Reward not found/i,
241
- ],
242
- error_code: "object_not_found",
243
- retryable: false,
244
- recovery_hint: "Verify the object ID/name with query_toolkit; local_mark names are case-sensitive",
245
- },
246
- {
247
- patterns: [
248
- /state\s*(conflict|mismatch)/i,
249
- /already\s*exist/i,
250
- /conflict/i,
251
- /duplicate/i,
252
- /version\s*mismatch/i,
253
- /name exist/i,
254
- /Duplicate forward name/i,
255
- /Duplicate node previous/i,
256
- /already claimed/i,
257
- /already specified/i,
258
- /already accomplished/i,
259
- /already used/i,
260
- /Status does not match/i,
261
- /does not match/i,
262
- ],
263
- error_code: "state_conflict",
264
- retryable: false,
265
- recovery_hint: "Object state conflicts with the operation. Query the current state with query_toolkit and adjust parameters",
266
- },
267
- {
268
- patterns: [
269
- /invalid/i,
270
- /missing\s*(field|param|required)/i,
271
- /required/i,
272
- /expected/i,
273
- /malformed/i,
274
- /parse\s*error/i,
275
- /type\s*mismatch/i,
276
- /invalid argument/i,
277
- /Invalid value/i,
278
- /Invalid data value/i,
279
- /Invalid string value/i,
280
- /Invalid argument/i,
281
- /IsValid/i,
282
- /type does not match/i,
283
- /value type/i,
284
- ],
285
- error_code: "invalid_parameter",
286
- retryable: false,
287
- recovery_hint: "Check parameter format against the tool schema; consult wowok-tools Skill for the operation's requirements",
288
- },
289
- ];
290
- const WERROR_MAPPINGS = [
291
- {
292
- codes: [WErrors.AccountNotFound, WErrors.AddressNotFound, WErrors.TokenNotFoundLocally],
293
- error_code: "object_not_found",
294
- retryable: false,
295
- recovery_hint: "Verify the object ID/name with query_toolkit; local_mark names are case-sensitive",
296
- },
297
- {
298
- codes: [WErrors.NoPermission],
299
- error_code: "permission_denied",
300
- retryable: false,
301
- recovery_hint: "Use an account with the required permission, or pass permission_guard IDs via env.permission_guard",
302
- },
303
- {
304
- codes: [
305
- WErrors.IsValidDescription,
306
- WErrors.IsValidName,
307
- WErrors.IsValidName_AllowEmpty,
308
- WErrors.IsValidEndpoint,
309
- WErrors.IsValidAddress,
310
- WErrors.IsValidArgType,
311
- WErrors.IsValidTokenType,
312
- WErrors.IsValidUint,
313
- WErrors.IsValidInt,
314
- WErrors.IsValidU8,
315
- WErrors.IsValidU16,
316
- WErrors.IsValidU32,
317
- WErrors.IsValidU64,
318
- WErrors.IsValidU128,
319
- WErrors.IsValidU256,
320
- WErrors.IsValidRate,
321
- WErrors.IsValidArray,
322
- WErrors.IsValidObjects,
323
- WErrors.AllInvalid,
324
- WErrors.InvalidParam,
325
- WErrors.IsValidPermissionIndex,
326
- WErrors.IsValidKey,
327
- WErrors.IsValidIdentifier,
328
- WErrors.IsValidHttpUrl,
329
- WErrors.IsValidBizPermissionIndex,
330
- WErrors.IsValidServiceItemName,
331
- WErrors.IsValidCoinType,
332
- WErrors.IsValidGuardIdentifier,
333
- WErrors.IsValidValue,
334
- WErrors.IsValidValueType,
335
- WErrors.IsValidLocation,
336
- WErrors.WitnessTypeInvalid,
337
- ],
338
- error_code: "invalid_parameter",
339
- retryable: false,
340
- recovery_hint: "Check parameter format against the tool schema; consult wowok-tools Skill for the operation's requirements",
341
- },
342
- {
343
- codes: [WErrors.BcsTypeInvalid, WErrors.ParseObjectContentFailed],
344
- error_code: "bcs_error",
345
- retryable: false,
346
- recovery_hint: "BCS serialization/deserialization error. Verify data types and structure match the expected schema",
347
- },
348
- {
349
- codes: [WErrors.NetworkInvalid],
350
- error_code: "config_error",
351
- retryable: false,
352
- recovery_hint: "Configuration error. Verify that network, RPC endpoints, and required environment variables are properly configured",
353
- },
354
- {
355
- codes: [
356
- WErrors.AccountPersistentStorageNotSet,
357
- WErrors.ConfigPersistentStorageNotSet,
358
- WErrors.AccountPersistentStorageNotFound,
359
- ],
360
- error_code: "config_error",
361
- retryable: false,
362
- recovery_hint: "Persistent storage not configured. Initialize account storage before performing this operation",
363
- },
364
- {
365
- codes: [WErrors.AccountNameExist, WErrors.LocalMarkNameExist],
366
- error_code: "state_conflict",
367
- retryable: false,
368
- recovery_hint: "Object state conflicts with the operation. Query the current state with query_toolkit and adjust parameters",
369
- },
370
- {
371
- codes: [WErrors.MaxObjectsPerQuery, WErrors.ResourceTagCountExceeded, WErrors.AddressCountExceeded, WErrors.NumberCountExceeded],
372
- error_code: "invalid_parameter",
373
- retryable: false,
374
- recovery_hint: "Count limit exceeded. Reduce the number of items per request and retry",
375
- },
376
- ];
377
- function isWException(value) {
378
- return value instanceof WException;
379
- }
380
- function classifyWException(exception) {
381
- const code = exception.getErrorCode();
382
- const mapping = WERROR_MAPPINGS.find((m) => m.codes.includes(code));
383
- if (!mapping)
384
- return undefined;
385
- const result = {
386
- error_code: mapping.error_code,
387
- retryable: mapping.retryable,
388
- recovery_hint: mapping.recovery_hint,
389
- };
390
- return result;
391
- }
392
- const WOWOK_ADDRESSES = new Set([
393
- "0x0000000000000000000000000000000000000000000000000000000000000002",
394
- "0x2",
395
- ]);
396
- function extractMoveAbortInfo(errorMsg) {
397
- if (!errorMsg)
398
- return undefined;
399
- const abortCodeMatch = errorMsg.match(/MoveAbort\([^,]+,\s*(\d+)\)/);
400
- const moduleNameMatch = errorMsg.match(/name:\s*Identifier\("([^"]+)"\)/);
401
- const addressMatch = errorMsg.match(/address:\s*([0-9a-fA-Fx]+)/);
402
- if (abortCodeMatch && moduleNameMatch && addressMatch) {
403
- const code = parseInt(abortCodeMatch[1], 10);
404
- const module = moduleNameMatch[1].toLowerCase();
405
- const address = addressMatch[1].toLowerCase();
406
- if (WOWOK_ADDRESSES.has(address)) {
407
- const description = getMoveErrorDescription(module, code) ?? undefined;
408
- return { module, code, description };
409
- }
410
- }
411
- const formattedAbortCode = errorMsg.match(/abort code:\s*(\d+)/);
412
- const formattedModule = errorMsg.match(/'0x[0-9a-fA-F]+::([^:]+)::[^']+'/);
413
- const formattedAddress = errorMsg.match(/'(0x[0-9a-fA-F]+)::/);
414
- if (formattedAbortCode && formattedModule && formattedAddress) {
415
- const code = parseInt(formattedAbortCode[1], 10);
416
- const module = formattedModule[1].toLowerCase();
417
- const address = formattedAddress[1].toLowerCase();
418
- if (WOWOK_ADDRESSES.has(address)) {
419
- const description = getMoveErrorDescription(module, code) ?? undefined;
420
- return { module, code, description };
421
- }
422
- }
423
- return undefined;
424
- }
425
- export function classifyError(errorMsg, error) {
426
- if (error !== undefined && isWException(error)) {
427
- const fromWException = classifyWException(error);
428
- if (fromWException) {
429
- const abortInfo = extractMoveAbortInfo(errorMsg);
430
- if (abortInfo) {
431
- fromWException.move_abort_info = abortInfo;
432
- if (abortInfo.description && fromWException.recovery_hint && !fromWException.recovery_hint.includes(abortInfo.description)) {
433
- fromWException.recovery_hint = `${fromWException.recovery_hint}. Details: ${abortInfo.description}`;
434
- }
435
- }
436
- return fromWException;
437
- }
438
- }
439
- if (!errorMsg) {
440
- return { error_code: "unknown", retryable: false };
441
- }
442
- for (const rule of ERROR_RULES) {
443
- if (rule.patterns.some((p) => p.test(errorMsg))) {
444
- const result = {
445
- error_code: rule.error_code,
446
- retryable: rule.retryable,
447
- recovery_hint: rule.recovery_hint,
448
- };
449
- const abortInfo = extractMoveAbortInfo(errorMsg);
450
- if (abortInfo) {
451
- result.move_abort_info = abortInfo;
452
- if (abortInfo.description) {
453
- result.recovery_hint = `${result.recovery_hint}. Details: ${abortInfo.description}`;
454
- }
455
- }
456
- return result;
457
- }
458
- }
459
- const abortInfo = extractMoveAbortInfo(errorMsg);
460
- const fallback = {
461
- error_code: "unknown",
462
- retryable: false,
463
- recovery_hint: "Inspect the full error message; consult wowok-tools Skill for the operation's requirements",
464
- };
465
- if (abortInfo) {
466
- fallback.move_abort_info = abortInfo;
467
- if (abortInfo.description) {
468
- fallback.recovery_hint = `${abortInfo.description}. ${fallback.recovery_hint}`;
469
- }
470
- }
471
- return fallback;
472
- }
473
- const INTENT_RULES = [
474
- { operation_type: "service", signals: (d) => d?.publish === true, intent: "publish_service", confidence: 0.95 },
475
- { operation_type: "service", signals: (d) => d?.name && d?.publish === undefined, intent: "create_service", confidence: 0.9 },
476
- { operation_type: "service", intent: "modify_service", confidence: 0.7 },
477
- { operation_type: "machine", intent: "configure_machine", confidence: 0.9 },
478
- { operation_type: "progress", intent: "update_progress", confidence: 0.9 },
479
- { operation_type: "order", signals: (d) => !!d?.arb, intent: "apply_arbitration", confidence: 0.9 },
480
- { operation_type: "order", intent: "manage_order", confidence: 0.85 },
481
- { operation_type: "payment", signals: (d) => d?.receive === true, intent: "claim_escrow_payment", confidence: 0.95 },
482
- { operation_type: "payment", intent: "send_payment", confidence: 0.9 },
483
- { operation_type: "reward", intent: "manage_reward", confidence: 0.9 },
484
- { operation_type: "demand", intent: "post_demand", confidence: 0.9 },
485
- { operation_type: "treasury", intent: "manage_treasury", confidence: 0.9 },
486
- { operation_type: "allocation", intent: "allocate_funds", confidence: 0.9 },
487
- { operation_type: "permission", intent: "manage_permission", confidence: 0.9 },
488
- { operation_type: "guard", intent: "configure_guard", confidence: 0.9 },
489
- { operation_type: "arbitration", intent: "manage_arbitration", confidence: 0.9 },
490
- { operation_type: "contact", intent: "manage_contact", confidence: 0.9 },
491
- { operation_type: "repository", intent: "manage_repository", confidence: 0.9 },
492
- { operation_type: "personal", intent: "manage_personal", confidence: 0.9 },
493
- { operation_type: "gen_passport", intent: "generate_passport", confidence: 0.95 },
494
- { operation_type: "bridge_cross_chain_wow_to_evm", intent: "cross_chain_wow_to_evm_deposit", confidence: 0.95 },
495
- { operation_type: "bridge_cross_chain_evm_to_wow", intent: "cross_chain_evm_to_wow_deposit", confidence: 0.95 },
496
- { operation_type: "bridge_claim_wow_to_evm", intent: "claim_wow_to_evm", confidence: 0.95 },
497
- { operation_type: "bridge_withdraw", intent: "withdraw_from_evm_account", confidence: 0.9 },
498
- { operation_type: "bridge_query_active_evm_account", intent: "query_bridge_status", confidence: 0.85 },
499
- { operation_type: "bridge_query_supported_evm_chains", intent: "query_bridge_status", confidence: 0.85 },
500
- { operation_type: "bridge_query_supported_tokens", intent: "query_bridge_status", confidence: 0.85 },
501
- { operation_type: "bridge_query_transfer_list", intent: "query_bridge_status", confidence: 0.85 },
502
- { operation_type: "bridge_query_transfer_status", intent: "query_bridge_status", confidence: 0.85 },
503
- { operation_type: "bridge_manage_evm_rpc", intent: "manage_evm_rpc", confidence: 0.9 },
504
- { operation_type: "account_new", intent: "create_account", confidence: 0.95 },
505
- { operation_type: "account_faucet", intent: "claim_faucet", confidence: 0.95 },
506
- { operation_type: "account_balance", intent: "query_balance", confidence: 0.9 },
507
- { operation_type: "mark_add", intent: "create_local_mark", confidence: 0.9 },
508
- { operation_type: "mark_remove", intent: "remove_local_mark", confidence: 0.9 },
509
- { operation_type: "mark_query", intent: "query_local_marks", confidence: 0.9 },
510
- { operation_type: "local_info", intent: "query_local_info", confidence: 0.9 },
511
- { operation_type: "query_toolkit", intent: "query_objects", confidence: 0.85 },
512
- { operation_type: "onchain_events", intent: "query_events", confidence: 0.85 },
513
- { operation_type: "onchain_table_data", intent: "query_table_data", confidence: 0.85 },
514
- ];
515
- export function inferIntent(operation_type, data) {
516
- const rules = INTENT_RULES.filter((r) => r.operation_type === operation_type);
517
- const signaled = rules.find((r) => r.signals && r.signals(data));
518
- if (signaled)
519
- return signaled.intent;
520
- const fallback = rules.find((r) => !r.signals);
521
- return fallback?.intent ?? operation_type;
522
- }
523
- function inferStatus(safeResult) {
524
- if (safeResult && typeof safeResult === "object" && "error" in safeResult)
525
- return "failed";
526
- if (safeResult && typeof safeResult === "object" && "digest" in safeResult) {
527
- return safeResult?.effects?.status?.status === "success" ? "success" : "failed";
528
- }
529
- return "success";
530
- }
531
- const OBJECT_TYPE_TO_ROLE = {
532
- service: "Service",
533
- machine: "Machine",
534
- progress: "Progress",
535
- permission: "Permission",
536
- guard: "Guard",
537
- order: "Order",
538
- arb: "Arbitration",
539
- arbcase: "ArbCase",
540
- messenger: "Messenger",
541
- contact: "Contact",
542
- demand: "Demand",
543
- reward: "Reward",
544
- personal: "Personal",
545
- repository: "Repository",
546
- treasury: "Treasury",
547
- discount: "Discount",
548
- allocation: "Allocation",
549
- };
550
- export function objectTypeToRole(objectType) {
551
- if (!objectType)
552
- return "Other";
553
- const base = objectType.replace(/<.*>/, "").trim();
554
- const segments = base.split("::");
555
- const last = (segments[segments.length - 1] || "").toLowerCase();
556
- return OBJECT_TYPE_TO_ROLE[last] ?? "Other";
557
- }
558
- export function tagObjectRoles(objectChanges) {
559
- if (!Array.isArray(objectChanges))
560
- return [];
561
- return objectChanges
562
- .filter((c) => c && (c.objectId || c.object?.objectId))
563
- .map((c) => {
564
- const id = c.objectId || c.object?.objectId;
565
- const type = c.objectType || c.object?.objectType || "";
566
- const changeType = c.type || "";
567
- return {
568
- id,
569
- role: objectTypeToRole(type),
570
- immutable: type.includes("Service") && changeType === "published",
571
- };
572
- });
573
- }
574
- const GAS_COIN_PATTERNS = [/::wow::WOW$/i];
575
- const SMALL_AMOUNT_THRESHOLD = BigInt(1_000_000);
576
- function isNegative(amount) {
577
- return String(amount ?? "0").startsWith("-");
578
- }
579
- function hasEventMatch(events, pattern) {
580
- if (!Array.isArray(events))
581
- return false;
582
- return events.some((e) => pattern.test(String(e?.type ?? e?.event_type ?? "")));
583
- }
584
- function isGasCoin(coinType) {
585
- if (!coinType)
586
- return false;
587
- return GAS_COIN_PATTERNS.some((p) => p.test(coinType));
588
- }
589
- function absAmount(amount) {
590
- try {
591
- return BigInt(String(amount).replace("-", "") || "0");
592
- }
593
- catch {
594
- return BigInt(0);
595
- }
596
- }
597
- const FUND_ROLE_RULES = [
598
- {
599
- when: (ctx) => hasEventMatch(ctx.events, /order::OrderPaidEvent/i),
600
- role: "payment",
601
- confidence: 0.95,
602
- },
603
- {
604
- when: (ctx) => hasEventMatch(ctx.events, /order::OrderRefundedEvent|order::RefundEvent/i),
605
- role: "refund",
606
- confidence: 0.95,
607
- },
608
- {
609
- when: (ctx) => hasEventMatch(ctx.events, /reward::RewardClaimedEvent|reward::ClaimedEvent/i),
610
- role: "reward",
611
- confidence: 0.95,
612
- },
613
- {
614
- when: (ctx) => hasEventMatch(ctx.events, /arbitration::CompensationEvent|arbitration::RefundEvent/i),
615
- role: "compensation",
616
- confidence: 0.9,
617
- },
618
- {
619
- when: (ctx) => hasEventMatch(ctx.events, /treasury::DepositEvent/i),
620
- role: "deposit",
621
- confidence: 0.95,
622
- },
623
- {
624
- when: (ctx) => hasEventMatch(ctx.events, /treasury::WithdrawEvent|treasury::ReleaseEvent/i),
625
- role: "release",
626
- confidence: 0.9,
627
- },
628
- {
629
- when: (ctx) => ctx.operation_type === "payment" && ctx.data?.receive === true,
630
- role: "release",
631
- confidence: 0.95,
632
- },
633
- {
634
- when: (ctx) => ctx.operation_type === "payment" && isNegative(ctx.amount),
635
- role: "payment",
636
- confidence: 0.95,
637
- },
638
- {
639
- when: (ctx) => ctx.operation_type === "payment" && !isNegative(ctx.amount),
640
- role: "refund",
641
- confidence: 0.9,
642
- },
643
- {
644
- when: (ctx) => ctx.operation_type === "reward" && isNegative(ctx.amount),
645
- role: "reward",
646
- confidence: 0.95,
647
- },
648
- {
649
- when: (ctx) => ctx.operation_type === "reward" && !isNegative(ctx.amount),
650
- role: "release",
651
- confidence: 0.9,
652
- },
653
- {
654
- when: (ctx) => ctx.operation_type === "treasury" && isNegative(ctx.amount),
655
- role: "deposit",
656
- confidence: 0.95,
657
- },
658
- {
659
- when: (ctx) => ctx.operation_type === "treasury" && !isNegative(ctx.amount),
660
- role: "release",
661
- confidence: 0.9,
662
- },
663
- {
664
- when: (ctx) => ctx.operation_type === "allocation" && isNegative(ctx.amount),
665
- role: "payment",
666
- confidence: 0.85,
667
- },
668
- {
669
- when: (ctx) => ctx.operation_type === "allocation" && !isNegative(ctx.amount),
670
- role: "release",
671
- confidence: 0.85,
672
- },
673
- {
674
- when: (ctx) => ctx.operation_type === "arbitration" && (ctx.data?.compensation !== undefined || ctx.data?.arb === true),
675
- role: "compensation",
676
- confidence: 0.9,
677
- },
678
- {
679
- when: (ctx) => ctx.operation_type === "order" && isNegative(ctx.amount) && ctx.data?.buy !== undefined,
680
- role: "payment",
681
- confidence: 0.9,
682
- },
683
- {
684
- when: (ctx) => ctx.operation_type === "order" && !isNegative(ctx.amount) && (ctx.data?.refund !== undefined || ctx.data?.arb !== undefined),
685
- role: "refund",
686
- confidence: 0.85,
687
- },
688
- {
689
- when: (ctx) => {
690
- if (isNegative(ctx.amount))
691
- return false;
692
- const amt = absAmount(ctx.amount);
693
- return isGasCoin(ctx.coinType) && amt > BigInt(0) && amt < SMALL_AMOUNT_THRESHOLD;
694
- },
695
- role: "gas",
696
- confidence: 0.7,
697
- },
698
- {
699
- when: (ctx) => {
700
- if (isNegative(ctx.amount))
701
- return false;
702
- return ctx.sender !== undefined && ctx.recipient !== undefined && ctx.sender === ctx.recipient && ctx.sender !== "";
703
- },
704
- role: "change",
705
- confidence: 0.7,
706
- },
707
- {
708
- when: (ctx) => isNegative(ctx.amount),
709
- role: "payment",
710
- confidence: 0.7,
711
- },
712
- {
713
- when: (ctx) => !isNegative(ctx.amount) && absAmount(ctx.amount) === BigInt(0),
714
- role: "other",
715
- confidence: 0.5,
716
- },
717
- {
718
- when: (ctx) => !isNegative(ctx.amount),
719
- role: "release",
720
- confidence: 0.7,
721
- },
722
- {
723
- when: () => true,
724
- role: "other",
725
- confidence: 0.3,
726
- },
727
- ];
728
- export function tagFundRoles(balanceChanges, operation_type, data, events) {
729
- if (!Array.isArray(balanceChanges))
730
- return [];
731
- return balanceChanges
732
- .filter((c) => c && (c.amount !== undefined || c.coinType))
733
- .map((c) => {
734
- const ctx = {
735
- operation_type,
736
- amount: String(c.amount ?? "0"),
737
- coinType: c.coinType,
738
- data: data ?? {},
739
- events,
740
- sender: c.sender,
741
- recipient: c.recipient,
742
- };
743
- const rule = FUND_ROLE_RULES.find((r) => r.when(ctx));
744
- const role = rule?.role ?? "other";
745
- return {
746
- amount: ctx.amount,
747
- coinType: c.coinType || "",
748
- role,
749
- from: c.sender ?? null,
750
- to: c.recipient ?? null,
751
- };
752
- });
753
- }
754
- const EVENT_SEMANTIC_RULES = [
755
- {
756
- pattern: /::service::ServiceCreatedEvent/i,
757
- business_meaning: "A new Service was created (not yet published)",
758
- category: "lifecycle",
759
- side_effect: "Service exists in draft state; configure Machine and publish when ready",
760
- },
761
- {
762
- pattern: /::service::ServicePublishedEvent/i,
763
- business_meaning: "Service has been published and is now immutable",
764
- category: "lifecycle",
765
- side_effect: "Customers can now place orders against this Service",
766
- },
767
- {
768
- pattern: /::service::ServiceModifiedEvent/i,
769
- business_meaning: "Service configuration was modified",
770
- category: "state_change",
771
- },
772
- {
773
- pattern: /::machine::MachineCreatedEvent/i,
774
- business_meaning: "A new Machine (workflow template) was created",
775
- category: "lifecycle",
776
- },
777
- {
778
- pattern: /::machine::MachineBoundEvent/i,
779
- business_meaning: "Machine was bound to a Service",
780
- category: "state_change",
781
- side_effect: "Orders placed on this Service will follow the Machine's state graph",
782
- },
783
- {
784
- pattern: /::machine::MachinePublishedEvent/i,
785
- business_meaning: "Machine was published and is now immutable",
786
- category: "lifecycle",
787
- },
788
- {
789
- pattern: /::order::OrderCreatedEvent/i,
790
- business_meaning: "A new Order was placed by a customer",
791
- category: "lifecycle",
792
- side_effect: "Order is pending payment; merchant should await payment before proceeding",
793
- },
794
- {
795
- pattern: /::order::OrderPaidEvent/i,
796
- business_meaning: "Order has been paid by the customer",
797
- category: "fund_flow",
798
- side_effect: "Funds are escrowed; merchant can advance the order to delivery",
799
- },
800
- {
801
- pattern: /::order::OrderAdvancedEvent/i,
802
- business_meaning: "Order advanced to the next state in the Machine graph",
803
- category: "state_change",
804
- },
805
- {
806
- pattern: /::order::OrderCompletedEvent/i,
807
- business_meaning: "Order has been completed",
808
- category: "lifecycle",
809
- side_effect: "Allocation can be executed to distribute funds to recipients",
810
- },
811
- {
812
- pattern: /::order::OrderRefundedEvent|::order::RefundEvent/i,
813
- business_meaning: "Order was refunded",
814
- category: "fund_flow",
815
- side_effect: "Escrowed funds returned to the customer",
816
- },
817
- {
818
- pattern: /::order::OrderCancelledEvent/i,
819
- business_meaning: "Order was cancelled",
820
- category: "lifecycle",
821
- },
822
- {
823
- pattern: /::reward::RewardCreatedEvent/i,
824
- business_meaning: "A new Reward pool was created",
825
- category: "lifecycle",
826
- },
827
- {
828
- pattern: /::reward::RewardClaimedEvent|::reward::ClaimedEvent/i,
829
- business_meaning: "Reward was claimed by a claimant",
830
- category: "fund_flow",
831
- side_effect: "Funds transferred from the reward pool to the claimant",
832
- },
833
- {
834
- pattern: /::treasury::DepositEvent/i,
835
- business_meaning: "Funds were deposited into the Treasury",
836
- category: "fund_flow",
837
- },
838
- {
839
- pattern: /::treasury::WithdrawEvent|::treasury::ReleaseEvent/i,
840
- business_meaning: "Funds were withdrawn from the Treasury",
841
- category: "fund_flow",
842
- },
843
- {
844
- pattern: /::demand::DemandCreatedEvent/i,
845
- business_meaning: "A new Demand (bounty) was posted",
846
- category: "lifecycle",
847
- },
848
- {
849
- pattern: /::demand::PresenterSubmittedEvent|::demand::PresentedEvent/i,
850
- business_meaning: "A presenter submitted a solution for the Demand",
851
- category: "state_change",
852
- },
853
- {
854
- pattern: /::permission::PermissionGrantedEvent/i,
855
- business_meaning: "Permission was granted to an address",
856
- category: "permission",
857
- },
858
- {
859
- pattern: /::permission::PermissionRevokedEvent/i,
860
- business_meaning: "Permission was revoked from an address",
861
- category: "permission",
862
- },
863
- {
864
- pattern: /::guard::GuardRejectedEvent|::guard::RejectedEvent/i,
865
- business_meaning: "Guard verification rejected the operation",
866
- category: "guard",
867
- side_effect: "Operation was blocked; user must satisfy the Guard's submission requirements",
868
- },
869
- {
870
- pattern: /::guard::GuardPassedEvent|::guard::AcceptedEvent/i,
871
- business_meaning: "Guard verification passed",
872
- category: "guard",
873
- },
874
- {
875
- pattern: /::arbitration::ArbitrationRequestedEvent|::arbitration::RequestedEvent/i,
876
- business_meaning: "Arbitration was requested for an Order",
877
- category: "state_change",
878
- side_effect: "Order is now in dispute; arbiter will rule on the outcome",
879
- },
880
- {
881
- pattern: /::arbitration::ArbitrationResolvedEvent|::arbitration::ResolvedEvent|::arbitration::CompensationEvent/i,
882
- business_meaning: "Arbitration was resolved (compensation or refund awarded)",
883
- category: "fund_flow",
884
- side_effect: "Funds redistributed per arbiter's ruling",
885
- },
886
- {
887
- pattern: /::allocation::AllocatedEvent|::allocation::DistributedEvent/i,
888
- business_meaning: "Funds were distributed to allocation recipients",
889
- category: "fund_flow",
890
- },
891
- {
892
- pattern: /::progress::ProgressUpdatedEvent|::progress::UpdatedEvent/i,
893
- business_meaning: "Order progress was updated",
894
- category: "state_change",
895
- },
896
- ];
897
- function extractRelatedObject(event) {
898
- if (!event || typeof event !== "object")
899
- return undefined;
900
- const fields = event.fields ?? event.payload ?? event;
901
- if (typeof fields !== "object")
902
- return undefined;
903
- for (const key of ["object_id", "objectId", "id", "parent", "service", "order", "machine", "reward", "treasury"]) {
904
- const v = fields[key];
905
- if (typeof v === "string" && v.startsWith("0x") && v.length >= 6)
906
- return v;
907
- }
908
- return undefined;
909
- }
910
- export function eventToSemantic(event) {
911
- const eventType = String(event?.type ?? event?.event_type ?? "");
912
- const rule = EVENT_SEMANTIC_RULES.find((r) => r.pattern.test(eventType));
913
- if (!rule) {
914
- return {
915
- event_type: eventType,
916
- business_meaning: "Unknown event",
917
- category: "other",
918
- };
919
- }
920
- const related = rule.extractRelatedObject ? rule.extractRelatedObject(event) : extractRelatedObject(event);
921
- const result = {
922
- event_type: eventType,
923
- business_meaning: rule.business_meaning,
924
- category: rule.category,
925
- };
926
- if (related)
927
- result.related_object = related;
928
- if (rule.side_effect)
929
- result.side_effect = rule.side_effect;
930
- return result;
931
- }
932
- export function annotateEvents(events) {
933
- if (!Array.isArray(events))
934
- return [];
935
- return events.map(eventToSemantic);
936
- }
937
- const NEXT_ACTION_RULES = [
938
- {
939
- when: (ot) => ot === "service",
940
- action: "publish the Service when configuration is complete",
941
- reason: "Service must be published before customers can order",
942
- tool: "onchain_operations (service with publish:true)",
943
- priority: "recommended",
944
- },
945
- {
946
- when: (ot) => ot === "service",
947
- action: "add Machine nodes to define the service workflow",
948
- reason: "Machine drives order state transitions",
949
- tool: "onchain_operations (machine)",
950
- priority: "recommended",
951
- },
952
- {
953
- when: (ot) => ot === "machine",
954
- action: "bind Progress to track order execution",
955
- reason: "Progress provides customer-visible status updates",
956
- tool: "onchain_operations (progress)",
957
- priority: "recommended",
958
- },
959
- {
960
- when: (ot) => ot === "order",
961
- action: "wait for customer payment or proceed to allocation",
962
- reason: "Order lifecycle: payment → allocation → completion",
963
- priority: "optional",
964
- },
965
- {
966
- when: (ot, data) => ot === "order" && data?.transfer_to !== undefined,
967
- action: "inform the end customer about the supplier/sub-contractor who will fulfill this order",
968
- reason: "O-5 procurement sub-order transparency: customers have the right to know who fulfills their order",
969
- tool: "messenger_operation (notify customer)",
970
- priority: "recommended",
971
- },
972
- {
973
- when: (ot) => ot === "demand",
974
- action: "wait for presenter submissions or evaluate existing ones",
975
- reason: "Demand lifecycle: presenters submit solutions for reward",
976
- priority: "optional",
977
- },
978
- {
979
- when: (ot) => ot === "reward",
980
- action: "deposit funds into the reward pool",
981
- reason: "Reward pool must be funded before claimants can withdraw",
982
- tool: "onchain_operations (treasury)",
983
- priority: "recommended",
984
- },
985
- {
986
- when: (ot) => ot === "bridge_cross_chain_wow_to_evm",
987
- action: "poll query_transfer_status until bridge signs (~1-5 min), then call claim_wow_to_evm to complete",
988
- reason: "Cross-chain WOW→EVM is a 2-step process: deposit first, then claim after bridge confirmation",
989
- tool: "bridge_operation (query_transfer_status, then claim_wow_to_evm)",
990
- priority: "required",
991
- },
992
- {
993
- when: (ot) => ot === "bridge_cross_chain_evm_to_wow",
994
- action: "poll query_transfer_status to monitor auto-claim progress (~10-20 min)",
995
- reason: "EVM→WOW cross-chain auto-claims; monitor progress but no manual action needed",
996
- tool: "bridge_operation (query_transfer_status)",
997
- priority: "recommended",
998
- },
999
- {
1000
- when: (ot) => ot === "bridge_claim_wow_to_evm",
1001
- action: "verify recipient EVM balance updated",
1002
- reason: "Claim completes the cross-chain transfer; verify funds arrived on EVM side",
1003
- tool: "bridge_operation (query_active_evm_account)",
1004
- priority: "recommended",
1005
- },
1006
- {
1007
- when: (ot) => ot === "bridge_withdraw",
1008
- action: "verify WOW balance updated",
1009
- reason: "Withdrawal moves funds from active EVM account to WOW; verify balance",
1010
- tool: "account_operation (balance)",
1011
- priority: "recommended",
1012
- },
1013
- {
1014
- when: (ot) => ot === "account_new",
1015
- action: "claim faucet tokens for gas if on testnet, then proceed to create Service",
1016
- reason: "New account needs gas tokens before on-chain operations",
1017
- tool: "account_operation (faucet)",
1018
- priority: "recommended",
1019
- },
1020
- {
1021
- when: (ot) => ot === "account_faucet",
1022
- action: "proceed to create Permission and Service objects",
1023
- reason: "Account is now funded; start building your service",
1024
- tool: "onchain_operations (permission, service)",
1025
- priority: "recommended",
1026
- },
1027
- {
1028
- when: (ot) => ot === "query_toolkit",
1029
- action: "use the queried object data to plan next operations",
1030
- reason: "Query results reveal current object states for decision-making",
1031
- priority: "optional",
1032
- },
1033
- ];
1034
- function inferNextActions(operation_type, data, status) {
1035
- return NEXT_ACTION_RULES
1036
- .filter((r) => r.when(operation_type, data, status))
1037
- .map((r) => ({
1038
- action: r.action,
1039
- reason: r.reason,
1040
- tool: r.tool,
1041
- priority: r.priority,
1042
- }));
1043
- }
1044
- function inferWarnings(operation_type, data, _safeResult) {
1045
- const warnings = [];
1046
- if (operation_type === "service" && data?.order_allocators === undefined) {
1047
- warnings.push("order_allocators not configured; order funds cannot be distributed automatically");
1048
- }
1049
- if (operation_type === "reward" && (data?.balance === "0" || data?.balance === 0)) {
1050
- warnings.push("Reward pool balance is zero; claimants cannot withdraw");
1051
- }
1052
- if (operation_type === "order" && data?.transfer_to !== undefined) {
1053
- warnings.push("[TRANSPARENCY] Order ownership is being transferred (likely to a supplier/sub-contractor). " +
1054
- "Ensure the end customer is informed about who fulfills their order — this builds trust and is required for procurement sub-orders.");
1055
- }
1056
- return warnings;
1057
- }
1058
- function composeSummary(intent, status, created, modified, released) {
1059
- const intentVerb = intent.replace(/_/g, " ");
1060
- if (status === "failed")
1061
- return `Failed to ${intentVerb}`;
1062
- if (status === "pending_input")
1063
- return `${intentVerb} requires Guard submission to proceed`;
1064
- const parts = [];
1065
- if (created.length)
1066
- parts.push(`created ${created.length} object(s)`);
1067
- if (modified.length)
1068
- parts.push(`modified ${modified.length} object(s)`);
1069
- if (released.length) {
1070
- if (intent === "allocate_funds") {
1071
- const details = released.map(f => {
1072
- const amt = f.amount;
1073
- const coin = shortCoinType(f.coinType);
1074
- const recipient = f.to ? shortAddr(f.to) : null;
1075
- const sender = f.from ? shortAddr(f.from) : null;
1076
- if (recipient)
1077
- return `${amt} ${coin} → ${recipient}`;
1078
- if (sender)
1079
- return `${amt} ${coin} from ${sender}`;
1080
- return `${amt} ${coin}`;
1081
- }).join("; ");
1082
- parts.push(`distributed: ${details}`);
1083
- }
1084
- else {
1085
- parts.push(`${released.length} fund movement(s)`);
1086
- }
1087
- }
1088
- return `Successfully ${intentVerb}${parts.length ? ` (${parts.join(", ")})` : ""}`;
1089
- }
1090
- function shortAddr(addr) {
1091
- if (addr.length > 14) {
1092
- return addr.slice(0, 8) + "..." + addr.slice(-4);
1093
- }
1094
- return addr;
1095
- }
1096
- function shortCoinType(coinType) {
1097
- if (!coinType)
1098
- return "coin";
1099
- const parts = coinType.split("::");
1100
- return parts[parts.length - 1] || coinType;
1101
- }
1102
- function buildCustomerAdvice(operation_type, data, safeResult) {
1103
- if (!isRuntimeEnabled("customer_intelligence"))
1104
- return undefined;
1105
- let stage;
1106
- if (operation_type === "order") {
1107
- stage = "preorder";
1108
- }
1109
- else if (operation_type === "query_toolkit" || operation_type === "onchain_table_data" || operation_type === "onchain_events") {
1110
- stage = "browse";
1111
- }
1112
- else if (operation_type === "service") {
1113
- stage = "evaluate";
1114
- }
1115
- else {
1116
- return undefined;
1117
- }
1118
- const serviceId = data?.service_name ?? data?.service_id ?? data?.service ?? data?.name;
1119
- const orderId = data?.order_name ?? data?.order_id ?? data?.order;
1120
- let servicePrice;
1121
- if (data?.price !== undefined) {
1122
- try {
1123
- servicePrice = BigInt(String(data.price));
1124
- }
1125
- catch { }
1126
- }
1127
- if (servicePrice === undefined && safeResult?.price !== undefined) {
1128
- try {
1129
- servicePrice = BigInt(String(safeResult.price));
1130
- }
1131
- catch { }
1132
- }
1133
- const hasArbitration = booleanFromSignals(data?.arb_name !== undefined || data?.arbitration !== undefined, data?.arb === false);
1134
- const hasCompensation = booleanFromSignals(data?.compensation_fund !== undefined || data?.compensation !== undefined, false);
1135
- const hasRefundPath = booleanFromSignals(data?.refund !== undefined, false);
1136
- const hasMessenger = booleanFromSignals(data?.um !== undefined ||
1137
- data?.um_name !== undefined ||
1138
- data?.messenger !== undefined ||
1139
- safeResult?.um !== undefined, data?.um === null || data?.um_name === null);
1140
- const customerRequired = Array.isArray(data?.customer_required)
1141
- ? data.customer_required.filter((x) => typeof x === "string")
1142
- : Array.isArray(safeResult?.customer_required)
1143
- ? safeResult.customer_required.filter((x) => typeof x === "string")
1144
- : [];
1145
- const noArbitration = hasArbitration === false;
1146
- const noCompensation = hasCompensation === false;
1147
- const riskScore = typeof data?.risk_score === "number" ? data.risk_score
1148
- : typeof safeResult?.risk_score === "number" ? safeResult.risk_score : undefined;
1149
- const riskLevel = data?.risk_level ?? safeResult?.risk_level;
1150
- const profile = getProfile();
1151
- const userMinTrust = profile.risk_appetite === "conservative" ? 70
1152
- : profile.risk_appetite === "aggressive" ? 30 : 50;
1153
- let tokenHint;
1154
- const moneyDisplay = safeResult?._money_display ??
1155
- (Array.isArray(safeResult?.objects) ? safeResult.objects[0]?._money_display : undefined);
1156
- const mdEntry = moneyDisplay ? Object.values(moneyDisplay)[0] : undefined;
1157
- if (mdEntry?.precision_known === true) {
1158
- tokenHint = { decimals: mdEntry.decimals, symbol: mdEntry.symbol };
1159
- }
1160
- else {
1161
- const typeRaw = safeResult?.type_raw ??
1162
- (Array.isArray(safeResult?.objects) ? safeResult.objects[0]?.type_raw : undefined);
1163
- tokenHint =
1164
- registryDisplayHint(extractGenericTokenType(typeRaw)) ??
1165
- registryDisplayHint(typeof data?.type_parameter === "string" ? data.type_parameter : undefined);
1166
- }
1167
- const ctx = {
1168
- stage,
1169
- service_id: serviceId,
1170
- order_id: orderId,
1171
- service_price: servicePrice,
1172
- token: tokenHint,
1173
- has_arbitration: hasArbitration,
1174
- has_compensation: hasCompensation,
1175
- has_refund_path: hasRefundPath,
1176
- has_messenger: hasMessenger,
1177
- customer_required: customerRequired,
1178
- risk_score: riskScore,
1179
- risk_level: riskLevel,
1180
- user_min_trust_score: userMinTrust,
1181
- user_require_arbitration: profile.risk_appetite === "conservative",
1182
- user_require_compensation: profile.risk_appetite === "conservative",
1183
- };
1184
- const reminders = generateReminders(ctx);
1185
- const recommendations = [];
1186
- for (const r of reminders) {
1187
- if (r.action)
1188
- recommendations.push(r.action);
1189
- }
1190
- if (noArbitration && !recommendations.some((r) => r.includes("arbitration"))) {
1191
- recommendations.push("Require the merchant to configure an Arbitration service before placing the order");
1192
- }
1193
- if (noCompensation && !recommendations.some((r) => r.includes("compensation"))) {
1194
- recommendations.push("Require the merchant to set a compensation_fund to guarantee automatic payout when the order fails");
1195
- }
1196
- const advice = {
1197
- recommendations,
1198
- reminders: reminders.map((r) => ({
1199
- id: r.id,
1200
- stage: r.stage,
1201
- priority: r.priority,
1202
- message: r.message,
1203
- action: r.action,
1204
- })),
1205
- };
1206
- if (riskScore !== undefined)
1207
- advice.risk_score = riskScore;
1208
- if (riskLevel !== undefined)
1209
- advice.risk_level = riskLevel;
1210
- return advice;
1211
- }
1212
- function buildGuardAdvice(operation_type, data, safeResult) {
1213
- try {
1214
- if (operation_type === "guard") {
1215
- return buildGuardCreateAdvice(data);
1216
- }
1217
- if (operation_type === "gen_passport") {
1218
- const status = safeResult?.error ? "fail" : "pass";
1219
- return {
1220
- current_round: "R8",
1221
- test_result: {
1222
- status: status,
1223
- passport_id: status === "pass" ? safeResult?.passport : undefined,
1224
- failure_node: status === "fail"
1225
- ? (typeof safeResult?.error === "string" ? safeResult.error.slice(0, 120) : undefined)
1226
- : undefined,
1227
- },
1228
- };
1229
- }
1230
- const errorStr = typeof safeResult?.error === "string" ? safeResult.error : "";
1231
- if (errorStr.includes("GUARD") || errorStr.includes("Guard") || errorStr.includes("guard")) {
1232
- return {
1233
- risk_warnings: [
1234
- `Guard verification failed: ${errorStr.slice(0, 200)}`,
1235
- "Suggestion: check whether the submission data matches the Guard table declaration, or query the Guard definition to learn the required submission",
1236
- ],
1237
- };
1238
- }
1239
- return undefined;
1240
- }
1241
- catch {
1242
- return undefined;
1243
- }
1244
- }
1245
- function buildGuardCreateAdvice(data) {
1246
- if (!data)
1247
- return undefined;
1248
- const puzzleInput = convertCallDataToPuzzleInput(data);
1249
- const puzzle = derivePuzzleFromCallData(puzzleInput);
1250
- const puzzleStatusBooleans = getPuzzleStatusBooleans(puzzle);
1251
- let matchedScene;
1252
- let sceneDescription;
1253
- let sceneConstraints;
1254
- if (data.binding_hint?.action) {
1255
- matchedScene = inferSceneFromAction(data.binding_hint.action);
1256
- if (matchedScene) {
1257
- sceneDescription = matchedScene.name;
1258
- sceneConstraints = matchedScene.special_constraints;
1259
- }
1260
- }
1261
- let suggestedPatterns;
1262
- const intentText = data.binding_hint?.rule_sentence
1263
- || data.binding_hint?.action
1264
- || "";
1265
- if (intentText) {
1266
- const matched = matchSemanticPattern(intentText);
1267
- if (matched.length > 0) {
1268
- suggestedPatterns = matched.map((m) => `${m.id}: ${m.pattern_name}`);
1269
- }
1270
- }
1271
- let confirmationText;
1272
- try {
1273
- const text = generateConfirmationText(puzzle);
1274
- if (!text.startsWith("[Puzzle incomplete]")) {
1275
- confirmationText = text;
1276
- }
1277
- }
1278
- catch {
1279
- }
1280
- let pendingQuestions;
1281
- const pendingQs = getPendingQuestions(puzzle);
1282
- if (pendingQs.length > 0) {
1283
- pendingQuestions = pendingQs;
1284
- }
1285
- let availableQueries;
1286
- if (matchedScene) {
1287
- const sceneObjectType = mapSceneToObjectType(matchedScene);
1288
- if (sceneObjectType) {
1289
- const filtered = GUARDQUERY
1290
- .filter((q) => q.objectType === sceneObjectType)
1291
- .slice(0, 10)
1292
- .map((q) => ({
1293
- id: q.id,
1294
- name: q.name,
1295
- objectType: String(q.objectType),
1296
- returnType: String(q.return),
1297
- description: q.description,
1298
- }));
1299
- if (filtered.length > 0) {
1300
- availableQueries = filtered;
1301
- }
1302
- }
1303
- }
1304
- const assessment = assessGuardRisksForOperation("guard", data);
1305
- let riskAssessment;
1306
- let riskWarnings;
1307
- if (assessment) {
1308
- const summary = getRiskSummary(assessment);
1309
- riskAssessment = {
1310
- overall_risk: summary.risk_count > 0 ? assessment.overall_risk : "info",
1311
- risk_count: summary.risk_count,
1312
- critical_count: summary.critical_count,
1313
- high_count: summary.high_count,
1314
- needs_human_review: summary.needs_human_review,
1315
- top_risks: summary.top_risks,
1316
- stakeholder_advice: assessment.stakeholder_advice,
1317
- };
1318
- const warnings = assessment.risks.map((r) => `[${r.level.toUpperCase()}] ${r.title}: ${r.description}`);
1319
- if (warnings.length > 0) {
1320
- riskWarnings = warnings;
1321
- }
1322
- }
1323
- const advice = {
1324
- current_round: "R7",
1325
- puzzle_status: puzzleStatusBooleans,
1326
- };
1327
- if (matchedScene)
1328
- advice.matched_scene = matchedScene.id;
1329
- if (sceneDescription)
1330
- advice.scene_description = sceneDescription;
1331
- if (sceneConstraints)
1332
- advice.scene_constraints = sceneConstraints;
1333
- if (suggestedPatterns)
1334
- advice.suggested_patterns = suggestedPatterns;
1335
- if (availableQueries)
1336
- advice.available_queries = availableQueries;
1337
- if (riskWarnings)
1338
- advice.risk_warnings = riskWarnings;
1339
- if (pendingQuestions)
1340
- advice.pending_questions = pendingQuestions;
1341
- if (confirmationText)
1342
- advice.confirmation_text = confirmationText;
1343
- if (riskAssessment)
1344
- advice.risk_assessment = riskAssessment;
1345
- return advice;
1346
- }
1347
- function convertCallDataToPuzzleInput(data) {
1348
- const result = {};
1349
- if (Array.isArray(data.table)) {
1350
- result.table = data.table.map((item) => ({
1351
- identifier: item.identifier,
1352
- b_submission: item.b_submission,
1353
- value_type: typeof item.value_type === "string" ? item.value_type : String(item.value_type),
1354
- value: convertValueSnapshot(item.value),
1355
- name: item.name ?? "",
1356
- object_type: item.object_type,
1357
- }));
1358
- }
1359
- if (data.root && typeof data.root === "object") {
1360
- const rootObj = data.root;
1361
- if (rootObj.type !== "file" && rootObj.type !== "node") {
1362
- result.root = convertNodeToSnapshot(data.root);
1363
- }
1364
- else if (rootObj.type === "node" && data.root.node) {
1365
- result.root = convertNodeToSnapshot(data.root.node);
1366
- }
1367
- }
1368
- if (data.rely && Array.isArray(data.rely.guards)) {
1369
- result.rely = {
1370
- guards: data.rely.guards.map((g) => typeof g === "string" ? g : String(g)),
1371
- logic_or: data.rely.logic_or,
1372
- };
1373
- }
1374
- if (data.binding_hint) {
1375
- const bh = data.binding_hint;
1376
- const bindingHint = {
1377
- action: bh.action,
1378
- host_object: bh.host_object,
1379
- binding_field: bh.binding_field,
1380
- };
1381
- if (bh.rule_sentence !== undefined)
1382
- bindingHint.rule_sentence = bh.rule_sentence;
1383
- if (bh.failure_conditions !== undefined)
1384
- bindingHint.failure_conditions = bh.failure_conditions;
1385
- if (bh.circular_reference !== undefined)
1386
- bindingHint.circular_reference = bh.circular_reference;
1387
- result.binding_hint = bindingHint;
1388
- }
1389
- return result;
1390
- }
1391
- function convertNodeToSnapshot(node) {
1392
- if (!node || typeof node !== "object") {
1393
- return { type: "unknown" };
1394
- }
1395
- const snapshot = {
1396
- type: String(node.type ?? "unknown"),
1397
- };
1398
- if (typeof node.identifier === "number") {
1399
- snapshot.identifier = node.identifier;
1400
- }
1401
- if (node.query !== undefined) {
1402
- snapshot.query = typeof node.query === "number" ? node.query : String(node.query);
1403
- }
1404
- if (node.object && typeof node.object === "object") {
1405
- const obj = {
1406
- identifier: Number(node.object.identifier),
1407
- };
1408
- if (typeof node.object.convert_witness === "number") {
1409
- obj.convert_witness = node.object.convert_witness;
1410
- }
1411
- snapshot.object = obj;
1412
- }
1413
- if (Array.isArray(node.parameters)) {
1414
- snapshot.parameters = node.parameters.map((p) => convertNodeToSnapshot(p));
1415
- }
1416
- if (typeof node.context === "string") {
1417
- const ctxValue = node.context;
1418
- if (ctxValue === "Clock" || ctxValue === "Guard" || ctxValue === "Signer") {
1419
- snapshot.context = ctxValue;
1420
- }
1421
- }
1422
- if (Array.isArray(node.nodes)) {
1423
- snapshot.nodes = node.nodes.map((n) => convertNodeToSnapshot(n));
1424
- }
1425
- if (node.node) {
1426
- snapshot.node = convertNodeToSnapshot(node.node);
1427
- }
1428
- if (node.nodeLeft) {
1429
- snapshot.nodeLeft = convertNodeToSnapshot(node.nodeLeft);
1430
- }
1431
- if (node.nodeRight) {
1432
- snapshot.nodeRight = convertNodeToSnapshot(node.nodeRight);
1433
- }
1434
- return snapshot;
1435
- }
1436
- function convertValueSnapshot(value) {
1437
- if (value === undefined || value === null)
1438
- return undefined;
1439
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1440
- return value;
1441
- }
1442
- if (Array.isArray(value)) {
1443
- const allString = value.every((v) => typeof v === "string");
1444
- if (allString)
1445
- return value;
1446
- const allNumber = value.every((v) => typeof v === "number");
1447
- if (allNumber)
1448
- return value;
1449
- const allBool = value.every((v) => typeof v === "boolean");
1450
- if (allBool)
1451
- return value;
1452
- return JSON.stringify(value);
1453
- }
1454
- return JSON.stringify(value);
1455
- }
1456
- function mapSceneToObjectType(scene) {
1457
- const hostObject = scene.host_object;
1458
- if (hostObject === "Standalone")
1459
- return undefined;
1460
- return hostObject;
1461
- }
1462
- export function buildSemantic(safeResult, context) {
1463
- if (!context)
1464
- return undefined;
1465
- const intent = inferIntent(context.operation_type, context.data);
1466
- const status = inferStatus(safeResult);
1467
- const objectChanges = safeResult?.objectChanges || [];
1468
- const balanceChanges = safeResult?.balanceChanges || [];
1469
- const events = safeResult?.events || [];
1470
- const created = tagObjectRoles(objectChanges.filter((c) => c?.type === "created"));
1471
- const modified = tagObjectRoles(objectChanges.filter((c) => c?.type === "mutated" || c?.type === "published"));
1472
- const released = tagFundRoles(balanceChanges, context.operation_type, context.data, events);
1473
- const annotatedEvents = annotateEvents(events);
1474
- const next_actions = inferNextActions(context.operation_type, context.data, status);
1475
- const warnings = inferWarnings(context.operation_type, context.data, safeResult);
1476
- if (context.pre_warnings && context.pre_warnings.length > 0) {
1477
- warnings.push(...context.pre_warnings);
1478
- }
1479
- if (context.operation_type === "service" && context.data?.publish === true) {
1480
- const findings = auditService(context.data);
1481
- for (const f of findings) {
1482
- const prefix = f.severity === "error" ? "[AUDIT ERROR] " : f.severity === "warning" ? "[AUDIT] " : "[INFO] ";
1483
- warnings.push(prefix + f.message);
1484
- }
1485
- }
1486
- let experience;
1487
- const experienceLayerEnabled = isRuntimeEnabled("experience_layer");
1488
- if (experienceLayerEnabled) {
1489
- try {
1490
- const feedback = getExperienceFeedback(context.operation_type, context.data, intent);
1491
- if (feedback) {
1492
- experience = feedback;
1493
- }
1494
- const outcome = status === "success" ? "success" : status === "failed" ? "failed" : "partial";
1495
- const referencedObjects = [...created, ...modified].map((o) => o.id).filter(Boolean);
1496
- const errCode = inferErrorCodeForSignal(safeResult);
1497
- recordOperationOutcome(context.operation_type, context.data, intent, outcome, errCode, referencedObjects);
1498
- }
1499
- catch {
1500
- }
1501
- }
1502
- let evolution_context;
1503
- if (isRuntimeEnabled("industry_evolution")) {
1504
- try {
1505
- const industryHint = (typeof context.data?.industry === "string" && context.data.industry.trim())
1506
- ? context.data.industry.trim()
1507
- : undefined;
1508
- if (industryHint && !experienceLayerEnabled) {
1509
- const outcome = status === "success"
1510
- ? { success: true }
1511
- : { success: false, error_code: inferErrorCodeForSignal(safeResult) };
1512
- recordIndustrySignal(industryHint, { type: context.operation_type, data: context.data }, outcome);
1513
- }
1514
- if (industryHint) {
1515
- const evoCtx = injectEvolutionContext(undefined, industryHint, deriveAdviceRole(context.operation_type, context.data));
1516
- if (evoCtx && (evoCtx.industry_signal || evoCtx.evolution_advice || evoCtx.confidence > 0)) {
1517
- evolution_context = evoCtx;
1518
- }
1519
- }
1520
- }
1521
- catch {
1522
- }
1523
- }
1524
- let service_status;
1525
- if (isRuntimeEnabled("semantic_rich")) {
1526
- try {
1527
- const all = listServices();
1528
- const active = all.filter((s) => s.enabled).map((s) => s.name);
1529
- const inactive = all.filter((s) => !s.enabled).map((s) => s.name);
1530
- service_status = {
1531
- active,
1532
- inactive: inactive.length ? inactive : undefined,
1533
- };
1534
- }
1535
- catch {
1536
- }
1537
- }
1538
- let customer_advice;
1539
- try {
1540
- customer_advice = buildCustomerAdvice(context.operation_type, context.data, safeResult);
1541
- }
1542
- catch {
1543
- }
1544
- let guard_advice;
1545
- try {
1546
- guard_advice = buildGuardAdvice(context.operation_type, context.data, safeResult);
1547
- }
1548
- catch {
1549
- }
1550
- return {
1551
- intent,
1552
- status,
1553
- summary: composeSummary(intent, status, created, modified, released),
1554
- created: created.length ? created : undefined,
1555
- modified: modified.length ? modified : undefined,
1556
- released: released.length ? released : undefined,
1557
- events: annotatedEvents.length ? annotatedEvents : undefined,
1558
- next_actions: next_actions.length ? next_actions : undefined,
1559
- warnings: warnings.length ? warnings : undefined,
1560
- experience,
1561
- service_status,
1562
- customer_advice,
1563
- evolution_context,
1564
- guard_advice,
1565
- };
1566
- }
1567
- function inferErrorCodeForSignal(safeResult) {
1568
- if (!safeResult)
1569
- return undefined;
1570
- if (typeof safeResult.error === "string")
1571
- return safeResult.error.slice(0, 64);
1572
- return undefined;
1573
- }
1574
- export function buildDataSemantic(data, context, isError, errorMsg) {
1575
- if (!context)
1576
- return undefined;
1577
- const intent = inferIntent(context.operation_type, context.data);
1578
- const warnings = [];
1579
- if (context.pre_warnings && context.pre_warnings.length > 0) {
1580
- warnings.push(...context.pre_warnings);
1581
- }
1582
- let status;
1583
- if (isError) {
1584
- status = "failed";
1585
- }
1586
- else {
1587
- status = "success";
1588
- if (Array.isArray(data) && data.length === 0) {
1589
- status = "partial";
1590
- warnings.push("no results found");
1591
- }
1592
- else if (data === null || data === undefined) {
1593
- status = "partial";
1594
- warnings.push("no results found");
1595
- }
1596
- else if (typeof data === "object" && !Array.isArray(data)) {
1597
- const values = Object.values(data);
1598
- if (values.length > 0 && values.every((v) => (Array.isArray(v) ? v.length === 0 : v === null || v === undefined))) {
1599
- status = "partial";
1600
- warnings.push("no results found");
1601
- }
1602
- }
1603
- }
1604
- const next_actions = inferNextActions(context.operation_type, context.data, status);
1605
- let annotatedEvents;
1606
- if (!isError && context.operation_type === "onchain_events") {
1607
- const eventsArray = Array.isArray(data) ? data : (data?.data && Array.isArray(data.data) ? data.data : null);
1608
- if (eventsArray) {
1609
- annotatedEvents = annotateEvents(eventsArray);
1610
- if (annotatedEvents.length === 0)
1611
- annotatedEvents = undefined;
1612
- }
1613
- }
1614
- const intentVerb = intent.replace(/_/g, " ");
1615
- let summary;
1616
- if (status === "failed") {
1617
- summary = errorMsg ? `Failed to ${intentVerb}: ${errorMsg}` : `Failed to ${intentVerb}`;
1618
- }
1619
- else if (status === "partial") {
1620
- summary = `${intentVerb} completed with no results`;
1621
- }
1622
- else {
1623
- summary = `Successfully ${intentVerb}`;
1624
- }
1625
- let service_status;
1626
- if (isRuntimeEnabled("semantic_rich")) {
1627
- try {
1628
- const all = listServices();
1629
- const active = all.filter((s) => s.enabled).map((s) => s.name);
1630
- const inactive = all.filter((s) => !s.enabled).map((s) => s.name);
1631
- service_status = {
1632
- active,
1633
- inactive: inactive.length ? inactive : undefined,
1634
- };
1635
- }
1636
- catch {
1637
- }
1638
- }
1639
- let customer_advice;
1640
- if (!isError) {
1641
- try {
1642
- customer_advice = buildCustomerAdvice(context.operation_type, context.data, data);
1643
- }
1644
- catch {
1645
- }
1646
- }
1647
- return {
1648
- intent,
1649
- status,
1650
- summary,
1651
- events: annotatedEvents,
1652
- next_actions: next_actions.length ? next_actions : undefined,
1653
- warnings: warnings.length ? warnings : undefined,
1654
- service_status,
1655
- customer_advice,
1656
- };
1657
- }
1
+ import{auditService}from'../../knowledge/index.js';import{getExperienceFeedback,recordOperationOutcome}from'../../experience/index.js';import{isEnabled as a268a,listServices}from'../../config/index.js';import{generateReminders}from'../../customer/index.js';import{getProfile}from'../../experience/user-profile.js';import{injectEvolutionContext,recordIndustrySignal}from'../../knowledge/flywheel-loop.js';import{WException,getMoveErrorDescription,WErrors}from'@wowok/wowok';import{GUARDQUERY}from'@wowok/wowok';import{assessGuardRisksForOperation,getRiskSummary}from'../../knowledge/guard-risk.js';import{derivePuzzleFromCallData,getPuzzleStatusBooleans,getPendingQuestions,generateConfirmationText}from'../../knowledge/guard-puzzle.js';import{inferSceneFromAction}from'../../knowledge/guard-ledger.js';import{extractGenericTokenType,registryDisplayHint}from'../../knowledge/fund-layer.js';import{matchSemanticPattern}from'../../knowledge/guard-translation.js';function booleanFromSignals(a,b){if(a)return!![];if(b)return![];return undefined;}function deriveAdviceRole(a,b){switch(a){case'order':case'personal':case'demand':return'customer';case'service':case'machine':case'permission':case'reward':case'repository':case'allocator':case'treasury':return'merchant';case'arbitration':if(b?.['vote']!==undefined)return'arbitrator';if(b?.['dispute']!==undefined)return'customer';return undefined;default:return undefined;}}const ERROR_RULES=[{'patterns':[/too\s*many\s*requests/i,/rate\s*limit/i,/429/i,/throttl/i,/faucet.*rate/i,/request.*limit.*exceeded/i],'error_code':'rate_limit','retryable':!![],'recovery_hint':'Rate\x20limit\x20hit\x20(HTTP\x20429).\x20Wait\x20with\x20exponential\x20backoff\x20and\x20retry.\x20To\x20check\x20existing\x20balance,\x20use\x20account_balance\x20query.'},{'patterns':[/gas.*budget.*exceeded/i,/out\s*of\s*gas/i,/gas\s*exceeded/i,/insufficient\s*gas/i,/not\s*enough\s*gas/i,/could not automatically determine a budget/i,/dry run failed.*budget/i,/Maximum gas/i],'error_code':'gas_exceeded','retryable':!![],'recovery_hint':'Gas\x20budget\x20exceeded.\x20Increase\x20the\x20gas_budget\x20parameter\x20or\x20claim\x20more\x20gas\x20tokens,\x20then\x20retry'},{'patterns':[/insufficient\s*(balance|coin|fund)/i,/ENOTENOUGH/i,/not\s*enough\s*(coin|balance)/i,/coin\s*not\s*enough/i,/balance\s*not\s*enough/i,/stock\s*not\s*enough/i,/fee\s*not\s*enough/i,/Insufficient balance/i],'error_code':'insufficient_balance','retryable':!![],'recovery_hint':'Claim\x20faucet\x20tokens\x20via\x20account_operation\x20(faucet)\x20then\x20retry\x20the\x20call'},{'patterns':[/bcs.*(error|fail|invalid)/i,/BCS serialization/i,/serialization\s*(failure|error)/i,/deserialization\s*(failure|error)/i,/invalid bcs type/i,/Out of range.*bcs/i,/Length out of range/i,/parse object content failed/i],'error_code':'bcs_error','retryable':![],'recovery_hint':'BCS\x20serialization/deserialization\x20error.\x20Verify\x20data\x20types\x20and\x20structure\x20match\x20the\x20expected\x20schema'},{'patterns':[/signature.*(invalid|fail|error|verif)/i,/invalid\s*signature/i,/signature\s*verification\s*failed/i,/bad\s*signature/i,/signing\s*fail/i,/crypto.*signature/i,/ed25519.*(fail|error|invalid)/i,/secp256k1.*(fail|error|invalid)/i],'error_code':'signature_error','retryable':![],'recovery_hint':'Signature\x20verification\x20failed.\x20Check\x20that\x20the\x20correct\x20private\x20key\x20and\x20network\x20configuration\x20are\x20correct'},{'patterns':[/config.*(not set|not found|invalid|missing)/i,/RPC\s*not\s*configured/i,/network.*not\s*specified/i,/protocol network not specified/i,/account persistent storage not set/i,/config persistent storage not set/i,/account persistent storage not found/i,/no\s*rpc\s*url/i],'error_code':'config_error','retryable':![],'recovery_hint':'Configuration\x20error.\x20Verify\x20that\x20network,\x20RPC\x20endpoints,\x20and\x20required\x20environment\x20variables\x20are\x20properly\x20configured'},{'patterns':[/network/i,/timeout/i,/ECONNRESET/i,/ETIMEDOUT/i,/ECONNREFUSED/i,/EAI_AGAIN/i,/RPC\s*(error|failed|unreachable)/i,/socket\s*hang\s*up/i,/fetch\s*failed/i,/connection\s*(refused|reset|lost)/i,/dns\s*(error|fail)/i],'error_code':'network_error','retryable':!![],'recovery_hint':'Retry\x20the\x20call;\x20if\x20it\x20persists,\x20switch\x20RPC\x20endpoint\x20or\x20check\x20connectivity'},{'patterns':[/guard.*(reject|fail|denied|verif)/i,/verification\s*failed/i,/submission.*(invalid|fail|required)/i,/passport.*(invalid|fail|verif)/i,/move[._-]?abort.*guard/i,/Guard count exceeded limit/i,/Submission size exceeded limit/i,/Submission not found/i,/Guard not found/i,/Impact guard not found/i],'error_code':'guard_rejected','retryable':![],'recovery_hint':'Fill\x20the\x20Guard\x20submission\x20data\x20(see\x20the\x20\x27submission\x27\x20field)\x20and\x20resubmit\x20via\x20call_with_submission'},{'patterns':[/WIP file verification failed/i,/Failed to load WIP file/i,/WIP.*hash\s*mismatch/i,/Invalid WIP file structure/i,/wip.*not\s*found/i,/wip.*unreachable/i,/wip_file.*error/i],'error_code':'wip_verification_failed','retryable':![],'recovery_hint':['WIP\x20file\x20must\x20be\x20publicly\x20accessible\x20via\x20HTTP(S)\x20URL\x20—\x20local\x20file\x20paths\x20cannot\x20be\x20stored\x20on-chain.','Deployment\x20options\x20(pick\x20one):','\x20\x201.\x20GitHub\x20Pages\x20(free,\x20stable):\x20upload\x20.wip\x20file\x20to\x20a\x20repo,\x20enable\x20Pages,\x20use\x20raw\x20URL.','\x20\x20\x20\x20\x20Example:\x20https://<user>.github.io/<repo>/<file>.wip','\x20\x20\x20\x20\x20Or\x20raw\x20URL:\x20https://raw.githubusercontent.com/<user>/<repo>/<branch>/<file>.wip','\x20\x202.\x20IPFS\x20(free,\x20decentralized):\x20upload\x20via\x20Pinata\x20(https://pinata.cloud)\x20or\x20nft.storage.','\x20\x20\x20\x20\x20Use\x20the\x20ipfs://<CID>\x20or\x20https://<gateway>/ipfs/<CID>\x20URL\x20form.','\x20\x20\x20\x20\x20Common\x20gateways:\x20https://ipfs.io/ipfs/,\x20https://cloudflare-ipfs.com/ipfs/,\x20https://dweb.link/ipfs/','\x20\x203.\x20User\x27s\x20own\x20website:\x20serve\x20the\x20.wip\x20file\x20from\x20your\x20static\x20site.','\x20\x204.\x20Generate\x20a\x20fresh\x20WIP\x20file\x20locally\x20first\x20via\x20wip_file\x20(type=\x27generate\x27),\x20upload\x20it,\x20then\x20re-submit\x20the\x20URL.','After\x20updating\x20the\x20sale\x27s\x20wip\x20URL,\x20re-run\x20the\x20operation.']['join']('\x0a')},{'patterns':[/already\s*publish/i,/immutable/i,/cannot\s*(modify|change|mutate)/i,/locked/i,/is\s*published/i,/Service already published/i,/Machine already published/i,/setting lock duration not exceeded/i],'error_code':'immutable_violation','retryable':![],'recovery_hint':'Object\x20is\x20in\x20an\x20immutable\x20state\x20(e.g.\x20Service\x20already\x20published).\x20Recreate\x20the\x20object\x20if\x20a\x20different\x20config\x20is\x20needed'},{'patterns':[/permission/i,/unauthorized/i,/forbidden/i,/not\s*(the\s*)?owner/i,/access\s*denied/i,/no permission/i,/Permission denied/i,/Not the builder/i,/Not admin/i,/No operation permission/i,/Not the holder/i],'error_code':'permission_denied','retryable':![],'recovery_hint':'Use\x20an\x20account\x20with\x20the\x20required\x20permission,\x20or\x20pass\x20permission_guard\x20IDs\x20via\x20env.permission_guard'},{'patterns':[/not\s*found/i,/does\s*not\s*exist/i,/ENOTFOUND/i,/no\s*such\s*object/i,/unknown\s*object/i,/account not found/i,/address not found/i,/token not found/i,/Node not found/i,/Policy not found/i,/Reward not found/i],'error_code':'object_not_found','retryable':![],'recovery_hint':'Verify\x20the\x20object\x20ID/name\x20with\x20query_toolkit;\x20local_mark\x20names\x20are\x20case-sensitive'},{'patterns':[/state\s*(conflict|mismatch)/i,/already\s*exist/i,/conflict/i,/duplicate/i,/version\s*mismatch/i,/name exist/i,/Duplicate forward name/i,/Duplicate node previous/i,/already claimed/i,/already specified/i,/already accomplished/i,/already used/i,/Status does not match/i,/does not match/i],'error_code':'state_conflict','retryable':![],'recovery_hint':'Object\x20state\x20conflicts\x20with\x20the\x20operation.\x20Query\x20the\x20current\x20state\x20with\x20query_toolkit\x20and\x20adjust\x20parameters'},{'patterns':[/invalid/i,/missing\s*(field|param|required)/i,/required/i,/expected/i,/malformed/i,/parse\s*error/i,/type\s*mismatch/i,/invalid argument/i,/Invalid value/i,/Invalid data value/i,/Invalid string value/i,/Invalid argument/i,/IsValid/i,/type does not match/i,/value type/i],'error_code':'invalid_parameter','retryable':![],'recovery_hint':'Check\x20parameter\x20format\x20against\x20the\x20tool\x20schema;\x20consult\x20wowok-tools\x20Skill\x20for\x20the\x20operation\x27s\x20requirements'}],WERROR_MAPPINGS=[{'codes':[WErrors['AccountNotFound'],WErrors['AddressNotFound'],WErrors['TokenNotFoundLocally']],'error_code':'object_not_found','retryable':![],'recovery_hint':'Verify\x20the\x20object\x20ID/name\x20with\x20query_toolkit;\x20local_mark\x20names\x20are\x20case-sensitive'},{'codes':[WErrors['NoPermission']],'error_code':'permission_denied','retryable':![],'recovery_hint':'Use\x20an\x20account\x20with\x20the\x20required\x20permission,\x20or\x20pass\x20permission_guard\x20IDs\x20via\x20env.permission_guard'},{'codes':[WErrors['IsValidDescription'],WErrors['IsValidName'],WErrors['IsValidName_AllowEmpty'],WErrors['IsValidEndpoint'],WErrors['IsValidAddress'],WErrors['IsValidArgType'],WErrors['IsValidTokenType'],WErrors['IsValidUint'],WErrors['IsValidInt'],WErrors['IsValidU8'],WErrors['IsValidU16'],WErrors['IsValidU32'],WErrors['IsValidU64'],WErrors['IsValidU128'],WErrors['IsValidU256'],WErrors['IsValidRate'],WErrors['IsValidArray'],WErrors['IsValidObjects'],WErrors['AllInvalid'],WErrors['InvalidParam'],WErrors['IsValidPermissionIndex'],WErrors['IsValidKey'],WErrors['IsValidIdentifier'],WErrors['IsValidHttpUrl'],WErrors['IsValidBizPermissionIndex'],WErrors['IsValidServiceItemName'],WErrors['IsValidCoinType'],WErrors['IsValidGuardIdentifier'],WErrors['IsValidValue'],WErrors['IsValidValueType'],WErrors['IsValidLocation'],WErrors['WitnessTypeInvalid']],'error_code':'invalid_parameter','retryable':![],'recovery_hint':'Check\x20parameter\x20format\x20against\x20the\x20tool\x20schema;\x20consult\x20wowok-tools\x20Skill\x20for\x20the\x20operation\x27s\x20requirements'},{'codes':[WErrors['BcsTypeInvalid'],WErrors['ParseObjectContentFailed']],'error_code':'bcs_error','retryable':![],'recovery_hint':'BCS\x20serialization/deserialization\x20error.\x20Verify\x20data\x20types\x20and\x20structure\x20match\x20the\x20expected\x20schema'},{'codes':[WErrors['NetworkInvalid']],'error_code':'config_error','retryable':![],'recovery_hint':'Configuration\x20error.\x20Verify\x20that\x20network,\x20RPC\x20endpoints,\x20and\x20required\x20environment\x20variables\x20are\x20properly\x20configured'},{'codes':[WErrors['AccountPersistentStorageNotSet'],WErrors['ConfigPersistentStorageNotSet'],WErrors['AccountPersistentStorageNotFound']],'error_code':'config_error','retryable':![],'recovery_hint':'Persistent\x20storage\x20not\x20configured.\x20Initialize\x20account\x20storage\x20before\x20performing\x20this\x20operation'},{'codes':[WErrors['AccountNameExist'],WErrors['LocalMarkNameExist']],'error_code':'state_conflict','retryable':![],'recovery_hint':'Object\x20state\x20conflicts\x20with\x20the\x20operation.\x20Query\x20the\x20current\x20state\x20with\x20query_toolkit\x20and\x20adjust\x20parameters'},{'codes':[WErrors['MaxObjectsPerQuery'],WErrors['ResourceTagCountExceeded'],WErrors['AddressCountExceeded'],WErrors['NumberCountExceeded']],'error_code':'invalid_parameter','retryable':![],'recovery_hint':'Count\x20limit\x20exceeded.\x20Reduce\x20the\x20number\x20of\x20items\x20per\x20request\x20and\x20retry'}];function isWException(a){return a instanceof WException;}function classifyWException(a){const b=a['getErrorCode'](),c=WERROR_MAPPINGS['find'](e=>e['codes']['includes'](b));if(!c)return undefined;const d={'error_code':c['error_code'],'retryable':c['retryable'],'recovery_hint':c['recovery_hint']};return d;}const WOWOK_ADDRESSES=new Set(['0x0000000000000000000000000000000000000000000000000000000000000002','0x2']);function extractMoveAbortInfo(a){if(!a)return undefined;const b=a['match'](/MoveAbort\([^,]+,\s*(\d+)\)/),c=a['match'](/name:\s*Identifier\("([^"]+)"\)/),d=a['match'](/address:\s*([0-9a-fA-Fx]+)/);if(b&&c&&d){const h=parseInt(b[0x1],0xa),i=c[0x1]['toLowerCase'](),j=d[0x1]['toLowerCase']();if(WOWOK_ADDRESSES['has'](j)){const k=getMoveErrorDescription(i,h)??undefined;return{'module':i,'code':h,'description':k};}}const e=a['match'](/abort code:\s*(\d+)/),f=a['match'](/'0x[0-9a-fA-F]+::([^:]+)::[^']+'/),g=a['match'](/'(0x[0-9a-fA-F]+)::/);if(e&&f&&g){const l=parseInt(e[0x1],0xa),m=f[0x1]['toLowerCase'](),n=g[0x1]['toLowerCase']();if(WOWOK_ADDRESSES['has'](n)){const o=getMoveErrorDescription(m,l)??undefined;return{'module':m,'code':l,'description':o};}}return undefined;}export function classifyError(a,b){if(b!==undefined&&isWException(b)){const e=classifyWException(b);if(e){const f=extractMoveAbortInfo(a);return f&&(e['move_abort_info']=f,f['description']&&e['recovery_hint']&&!e['recovery_hint']['includes'](f['description'])&&(e['recovery_hint']=e['recovery_hint']+'.\x20Details:\x20'+f['description'])),e;}}if(!a)return{'error_code':'unknown','retryable':![]};for(const g of ERROR_RULES){if(g['patterns']['some'](h=>h['test'](a))){const h={'error_code':g['error_code'],'retryable':g['retryable'],'recovery_hint':g['recovery_hint']},i=extractMoveAbortInfo(a);return i&&(h['move_abort_info']=i,i['description']&&(h['recovery_hint']=h['recovery_hint']+'.\x20Details:\x20'+i['description'])),h;}}const c=extractMoveAbortInfo(a),d={'error_code':'unknown','retryable':![],'recovery_hint':'Inspect\x20the\x20full\x20error\x20message;\x20consult\x20wowok-tools\x20Skill\x20for\x20the\x20operation\x27s\x20requirements'};return c&&(d['move_abort_info']=c,c['description']&&(d['recovery_hint']=c['description']+'.\x20'+d['recovery_hint'])),d;}const INTENT_RULES=[{'operation_type':'service','signals':a=>a?.['publish']===!![],'intent':'publish_service','confidence':0.95},{'operation_type':'service','signals':a=>a?.['name']&&a?.['publish']===undefined,'intent':'create_service','confidence':0.9},{'operation_type':'service','intent':'modify_service','confidence':0.7},{'operation_type':'machine','intent':'configure_machine','confidence':0.9},{'operation_type':'progress','intent':'update_progress','confidence':0.9},{'operation_type':'order','signals':a=>!!a?.['arb'],'intent':'apply_arbitration','confidence':0.9},{'operation_type':'order','intent':'manage_order','confidence':0.85},{'operation_type':'payment','signals':a=>a?.['receive']===!![],'intent':'claim_escrow_payment','confidence':0.95},{'operation_type':'payment','intent':'send_payment','confidence':0.9},{'operation_type':'reward','intent':'manage_reward','confidence':0.9},{'operation_type':'demand','intent':'post_demand','confidence':0.9},{'operation_type':'treasury','intent':'manage_treasury','confidence':0.9},{'operation_type':'allocation','intent':'allocate_funds','confidence':0.9},{'operation_type':'permission','intent':'manage_permission','confidence':0.9},{'operation_type':'guard','intent':'configure_guard','confidence':0.9},{'operation_type':'arbitration','intent':'manage_arbitration','confidence':0.9},{'operation_type':'contact','intent':'manage_contact','confidence':0.9},{'operation_type':'repository','intent':'manage_repository','confidence':0.9},{'operation_type':'personal','intent':'manage_personal','confidence':0.9},{'operation_type':'gen_passport','intent':'generate_passport','confidence':0.95},{'operation_type':'bridge_cross_chain_wow_to_evm','intent':'cross_chain_wow_to_evm_deposit','confidence':0.95},{'operation_type':'bridge_cross_chain_evm_to_wow','intent':'cross_chain_evm_to_wow_deposit','confidence':0.95},{'operation_type':'bridge_claim_wow_to_evm','intent':'claim_wow_to_evm','confidence':0.95},{'operation_type':'bridge_withdraw','intent':'withdraw_from_evm_account','confidence':0.9},{'operation_type':'bridge_query_active_evm_account','intent':'query_bridge_status','confidence':0.85},{'operation_type':'bridge_query_supported_evm_chains','intent':'query_bridge_status','confidence':0.85},{'operation_type':'bridge_query_supported_tokens','intent':'query_bridge_status','confidence':0.85},{'operation_type':'bridge_query_transfer_list','intent':'query_bridge_status','confidence':0.85},{'operation_type':'bridge_query_transfer_status','intent':'query_bridge_status','confidence':0.85},{'operation_type':'bridge_manage_evm_rpc','intent':'manage_evm_rpc','confidence':0.9},{'operation_type':'account_new','intent':'create_account','confidence':0.95},{'operation_type':'account_faucet','intent':'claim_faucet','confidence':0.95},{'operation_type':'account_balance','intent':'query_balance','confidence':0.9},{'operation_type':'mark_add','intent':'create_local_mark','confidence':0.9},{'operation_type':'mark_remove','intent':'remove_local_mark','confidence':0.9},{'operation_type':'mark_query','intent':'query_local_marks','confidence':0.9},{'operation_type':'local_info','intent':'query_local_info','confidence':0.9},{'operation_type':'query_toolkit','intent':'query_objects','confidence':0.85},{'operation_type':'onchain_events','intent':'query_events','confidence':0.85},{'operation_type':'onchain_table_data','intent':'query_table_data','confidence':0.85}];export function inferIntent(a,b){const c=INTENT_RULES['filter'](f=>f['operation_type']===a),d=c['find'](f=>f['signals']&&f['signals'](b));if(d)return d['intent'];const e=c['find'](f=>!f['signals']);return e?.['intent']??a;}function inferStatus(a){if(a&&typeof a==='object'&&'error'in a)return'failed';if(a&&typeof a==='object'&&'digest'in a)return a?.['effects']?.['status']?.['status']==='success'?'success':'failed';return'success';}const OBJECT_TYPE_TO_ROLE={'service':'Service','machine':'Machine','progress':'Progress','permission':'Permission','guard':'Guard','order':'Order','arb':'Arbitration','arbcase':'ArbCase','messenger':'Messenger','contact':'Contact','demand':'Demand','reward':'Reward','personal':'Personal','repository':'Repository','treasury':'Treasury','discount':'Discount','allocation':'Allocation'};export function objectTypeToRole(a){if(!a)return'Other';const b=a['replace'](/<.*>/,'')['trim'](),c=b['split']('::'),d=(c[c['length']-0x1]||'')['toLowerCase']();return OBJECT_TYPE_TO_ROLE[d]??'Other';}export function tagObjectRoles(a){if(!Array['isArray'](a))return[];return a['filter'](b=>b&&(b['objectId']||b['object']?.['objectId']))['map'](b=>{const d=b['objectId']||b['object']?.['objectId'],e=b['objectType']||b['object']?.['objectType']||'',f=b['type']||'';return{'id':d,'role':objectTypeToRole(e),'immutable':e['includes']('Service')&&f==='published'};});}const GAS_COIN_PATTERNS=[/::wow::WOW$/i],SMALL_AMOUNT_THRESHOLD=BigInt(0xf4240);function isNegative(a){return String(a??'0')['startsWith']('-');}function hasEventMatch(a,b){if(!Array['isArray'](a))return![];return a['some'](c=>b['test'](String(c?.['type']??c?.['event_type']??'')));}function isGasCoin(a){if(!a)return![];return GAS_COIN_PATTERNS['some'](b=>b['test'](a));}function absAmount(a){try{return BigInt(String(a)['replace']('-','')||'0');}catch{return BigInt(0x0);}}const FUND_ROLE_RULES=[{'when':a=>hasEventMatch(a['events'],/order::OrderPaidEvent/i),'role':'payment','confidence':0.95},{'when':a=>hasEventMatch(a['events'],/order::OrderRefundedEvent|order::RefundEvent/i),'role':'refund','confidence':0.95},{'when':a=>hasEventMatch(a['events'],/reward::RewardClaimedEvent|reward::ClaimedEvent/i),'role':'reward','confidence':0.95},{'when':a=>hasEventMatch(a['events'],/arbitration::CompensationEvent|arbitration::RefundEvent/i),'role':'compensation','confidence':0.9},{'when':a=>hasEventMatch(a['events'],/treasury::DepositEvent/i),'role':'deposit','confidence':0.95},{'when':a=>hasEventMatch(a['events'],/treasury::WithdrawEvent|treasury::ReleaseEvent/i),'role':'release','confidence':0.9},{'when':a=>a['operation_type']==='payment'&&a['data']?.['receive']===!![],'role':'release','confidence':0.95},{'when':a=>a['operation_type']==='payment'&&isNegative(a['amount']),'role':'payment','confidence':0.95},{'when':a=>a['operation_type']==='payment'&&!isNegative(a['amount']),'role':'refund','confidence':0.9},{'when':a=>a['operation_type']==='reward'&&isNegative(a['amount']),'role':'reward','confidence':0.95},{'when':a=>a['operation_type']==='reward'&&!isNegative(a['amount']),'role':'release','confidence':0.9},{'when':a=>a['operation_type']==='treasury'&&isNegative(a['amount']),'role':'deposit','confidence':0.95},{'when':a=>a['operation_type']==='treasury'&&!isNegative(a['amount']),'role':'release','confidence':0.9},{'when':a=>a['operation_type']==='allocation'&&isNegative(a['amount']),'role':'payment','confidence':0.85},{'when':a=>a['operation_type']==='allocation'&&!isNegative(a['amount']),'role':'release','confidence':0.85},{'when':a=>a['operation_type']==='arbitration'&&(a['data']?.['compensation']!==undefined||a['data']?.['arb']===!![]),'role':'compensation','confidence':0.9},{'when':a=>a['operation_type']==='order'&&isNegative(a['amount'])&&a['data']?.['buy']!==undefined,'role':'payment','confidence':0.9},{'when':a=>a['operation_type']==='order'&&!isNegative(a['amount'])&&(a['data']?.['refund']!==undefined||a['data']?.['arb']!==undefined),'role':'refund','confidence':0.85},{'when':a=>{if(isNegative(a['amount']))return![];const b=absAmount(a['amount']);return isGasCoin(a['coinType'])&&b>BigInt(0x0)&&b<SMALL_AMOUNT_THRESHOLD;},'role':'gas','confidence':0.7},{'when':a=>{if(isNegative(a['amount']))return![];return a['sender']!==undefined&&a['recipient']!==undefined&&a['sender']===a['recipient']&&a['sender']!=='';},'role':'change','confidence':0.7},{'when':a=>isNegative(a['amount']),'role':'payment','confidence':0.7},{'when':a=>!isNegative(a['amount'])&&absAmount(a['amount'])===BigInt(0x0),'role':'other','confidence':0.5},{'when':a=>!isNegative(a['amount']),'role':'release','confidence':0.7},{'when':()=>!![],'role':'other','confidence':0.3}];export function tagFundRoles(a,b,c,d){if(!Array['isArray'](a))return[];return a['filter'](e=>e&&(e['amount']!==undefined||e['coinType']))['map'](e=>{const f={'operation_type':b,'amount':String(e['amount']??'0'),'coinType':e['coinType'],'data':c??{},'events':d,'sender':e['sender'],'recipient':e['recipient']},g=FUND_ROLE_RULES['find'](i=>i['when'](f)),h=g?.['role']??'other';return{'amount':f['amount'],'coinType':e['coinType']||'','role':h,'from':e['sender']??null,'to':e['recipient']??null};});}const EVENT_SEMANTIC_RULES=[{'pattern':/::service::ServiceCreatedEvent/i,'business_meaning':'A\x20new\x20Service\x20was\x20created\x20(not\x20yet\x20published)','category':'lifecycle','side_effect':'Service\x20exists\x20in\x20draft\x20state;\x20configure\x20Machine\x20and\x20publish\x20when\x20ready'},{'pattern':/::service::ServicePublishedEvent/i,'business_meaning':'Service\x20has\x20been\x20published\x20and\x20is\x20now\x20immutable','category':'lifecycle','side_effect':'Customers\x20can\x20now\x20place\x20orders\x20against\x20this\x20Service'},{'pattern':/::service::ServiceModifiedEvent/i,'business_meaning':'Service\x20configuration\x20was\x20modified','category':'state_change'},{'pattern':/::machine::MachineCreatedEvent/i,'business_meaning':'A\x20new\x20Machine\x20(workflow\x20template)\x20was\x20created','category':'lifecycle'},{'pattern':/::machine::MachineBoundEvent/i,'business_meaning':'Machine\x20was\x20bound\x20to\x20a\x20Service','category':'state_change','side_effect':'Orders\x20placed\x20on\x20this\x20Service\x20will\x20follow\x20the\x20Machine\x27s\x20state\x20graph'},{'pattern':/::machine::MachinePublishedEvent/i,'business_meaning':'Machine\x20was\x20published\x20and\x20is\x20now\x20immutable','category':'lifecycle'},{'pattern':/::order::OrderCreatedEvent/i,'business_meaning':'A\x20new\x20Order\x20was\x20placed\x20by\x20a\x20customer','category':'lifecycle','side_effect':'Order\x20is\x20pending\x20payment;\x20merchant\x20should\x20await\x20payment\x20before\x20proceeding'},{'pattern':/::order::OrderPaidEvent/i,'business_meaning':'Order\x20has\x20been\x20paid\x20by\x20the\x20customer','category':'fund_flow','side_effect':'Funds\x20are\x20escrowed;\x20merchant\x20can\x20advance\x20the\x20order\x20to\x20delivery'},{'pattern':/::order::OrderAdvancedEvent/i,'business_meaning':'Order\x20advanced\x20to\x20the\x20next\x20state\x20in\x20the\x20Machine\x20graph','category':'state_change'},{'pattern':/::order::OrderCompletedEvent/i,'business_meaning':'Order\x20has\x20been\x20completed','category':'lifecycle','side_effect':'Allocation\x20can\x20be\x20executed\x20to\x20distribute\x20funds\x20to\x20recipients'},{'pattern':/::order::OrderRefundedEvent|::order::RefundEvent/i,'business_meaning':'Order\x20was\x20refunded','category':'fund_flow','side_effect':'Escrowed\x20funds\x20returned\x20to\x20the\x20customer'},{'pattern':/::order::OrderCancelledEvent/i,'business_meaning':'Order\x20was\x20cancelled','category':'lifecycle'},{'pattern':/::reward::RewardCreatedEvent/i,'business_meaning':'A\x20new\x20Reward\x20pool\x20was\x20created','category':'lifecycle'},{'pattern':/::reward::RewardClaimedEvent|::reward::ClaimedEvent/i,'business_meaning':'Reward\x20was\x20claimed\x20by\x20a\x20claimant','category':'fund_flow','side_effect':'Funds\x20transferred\x20from\x20the\x20reward\x20pool\x20to\x20the\x20claimant'},{'pattern':/::treasury::DepositEvent/i,'business_meaning':'Funds\x20were\x20deposited\x20into\x20the\x20Treasury','category':'fund_flow'},{'pattern':/::treasury::WithdrawEvent|::treasury::ReleaseEvent/i,'business_meaning':'Funds\x20were\x20withdrawn\x20from\x20the\x20Treasury','category':'fund_flow'},{'pattern':/::demand::DemandCreatedEvent/i,'business_meaning':'A\x20new\x20Demand\x20(bounty)\x20was\x20posted','category':'lifecycle'},{'pattern':/::demand::PresenterSubmittedEvent|::demand::PresentedEvent/i,'business_meaning':'A\x20presenter\x20submitted\x20a\x20solution\x20for\x20the\x20Demand','category':'state_change'},{'pattern':/::permission::PermissionGrantedEvent/i,'business_meaning':'Permission\x20was\x20granted\x20to\x20an\x20address','category':'permission'},{'pattern':/::permission::PermissionRevokedEvent/i,'business_meaning':'Permission\x20was\x20revoked\x20from\x20an\x20address','category':'permission'},{'pattern':/::guard::GuardRejectedEvent|::guard::RejectedEvent/i,'business_meaning':'Guard\x20verification\x20rejected\x20the\x20operation','category':'guard','side_effect':'Operation\x20was\x20blocked;\x20user\x20must\x20satisfy\x20the\x20Guard\x27s\x20submission\x20requirements'},{'pattern':/::guard::GuardPassedEvent|::guard::AcceptedEvent/i,'business_meaning':'Guard\x20verification\x20passed','category':'guard'},{'pattern':/::arbitration::ArbitrationRequestedEvent|::arbitration::RequestedEvent/i,'business_meaning':'Arbitration\x20was\x20requested\x20for\x20an\x20Order','category':'state_change','side_effect':'Order\x20is\x20now\x20in\x20dispute;\x20arbiter\x20will\x20rule\x20on\x20the\x20outcome'},{'pattern':/::arbitration::ArbitrationResolvedEvent|::arbitration::ResolvedEvent|::arbitration::CompensationEvent/i,'business_meaning':'Arbitration\x20was\x20resolved\x20(compensation\x20or\x20refund\x20awarded)','category':'fund_flow','side_effect':'Funds\x20redistributed\x20per\x20arbiter\x27s\x20ruling'},{'pattern':/::allocation::AllocatedEvent|::allocation::DistributedEvent/i,'business_meaning':'Funds\x20were\x20distributed\x20to\x20allocation\x20recipients','category':'fund_flow'},{'pattern':/::progress::ProgressUpdatedEvent|::progress::UpdatedEvent/i,'business_meaning':'Order\x20progress\x20was\x20updated','category':'state_change'},{'pattern':/::demand::DemandFeedbackEvent|::demand::FeedbackEvent/i,'business_meaning':'A\x20demand\x20owner\x20gave\x20feedback\x20(acceptance\x20score)\x20on\x20a\x20presented\x20service','category':'state_change','side_effect':'High\x20acceptance\x20score\x20signals\x20a\x20strong\x20service↔demand\x20fit;\x20low\x20score\x20signals\x20a\x20mismatch'},{'pattern':/::entity::NewEntityEvent|::entity::EntityRegisteredEvent|::registrar::NewEntityEvent/i,'business_meaning':'A\x20new\x20on-chain\x20entity\x20(user/merchant)\x20was\x20registered','category':'lifecycle','side_effect':'A\x20new\x20potential\x20counterparty\x20entered\x20the\x20ecosystem'}];function extractRelatedObject(a){if(!a||typeof a!=='object')return undefined;const b=a['fields']??a['payload']??a;if(typeof b!=='object')return undefined;for(const c of['object_id','objectId','id','parent','service','order','machine','reward','treasury']){const d=b[c];if(typeof d==='string'&&d['startsWith']('0x')&&d['length']>=0x6)return d;}return undefined;}const BUILTIN_EVENT_TYPE_MAP={'NewOrderEvent':'::order::OrderCreatedEvent','ArbEvent':'::arbitration::ArbitrationRequestedEvent','ProgressEvent':'::progress::ProgressUpdatedEvent','DemandPresentEvent':'::demand::PresenterSubmittedEvent','DemandFeedbackEvent':'::demand::DemandFeedbackEvent','NewEntityEvent':'::entity::NewEntityEvent'};export function eventToSemantic(a){const b=String(a?.['type']??a?.['event_type']??''),c=String(a?.['type_raw']??''),d=[c,b,BUILTIN_EVENT_TYPE_MAP[b]??'']['filter'](Boolean),e=EVENT_SEMANTIC_RULES['find'](h=>d['some'](i=>h['pattern']['test'](i)));if(!e)return{'event_type':b,'business_meaning':'Unknown\x20event','category':'other'};const f=e['extractRelatedObject']?e['extractRelatedObject'](a):extractRelatedObject(a),g={'event_type':b,'business_meaning':e['business_meaning'],'category':e['category']};if(f)g['related_object']=f;if(e['side_effect'])g['side_effect']=e['side_effect'];return g;}export function annotateEvents(a){if(!Array['isArray'](a))return[];return a['map'](eventToSemantic);}const NEXT_ACTION_RULES=[{'when':a=>a==='service','action':'publish\x20the\x20Service\x20when\x20configuration\x20is\x20complete','reason':'Service\x20must\x20be\x20published\x20before\x20customers\x20can\x20order','tool':'onchain_operations\x20(service\x20with\x20publish:true)','priority':'recommended'},{'when':a=>a==='service','action':'add\x20Machine\x20nodes\x20to\x20define\x20the\x20service\x20workflow','reason':'Machine\x20drives\x20order\x20state\x20transitions','tool':'onchain_operations\x20(machine)','priority':'recommended'},{'when':a=>a==='machine','action':'bind\x20Progress\x20to\x20track\x20order\x20execution','reason':'Progress\x20provides\x20customer-visible\x20status\x20updates','tool':'onchain_operations\x20(progress)','priority':'recommended'},{'when':a=>a==='order','action':'wait\x20for\x20customer\x20payment\x20or\x20proceed\x20to\x20allocation','reason':'Order\x20lifecycle:\x20payment\x20→\x20allocation\x20→\x20completion','priority':'optional'},{'when':(a,b)=>a==='order'&&b?.['transfer_to']!==undefined,'action':'inform\x20the\x20end\x20customer\x20about\x20the\x20supplier/sub-contractor\x20who\x20will\x20fulfill\x20this\x20order','reason':'O-5\x20procurement\x20sub-order\x20transparency:\x20customers\x20have\x20the\x20right\x20to\x20know\x20who\x20fulfills\x20their\x20order','tool':'messenger_operation\x20(notify\x20customer)','priority':'recommended'},{'when':a=>a==='demand','action':'wait\x20for\x20presenter\x20submissions\x20or\x20evaluate\x20existing\x20ones','reason':'Demand\x20lifecycle:\x20presenters\x20submit\x20solutions\x20for\x20reward','priority':'optional'},{'when':a=>a==='reward','action':'deposit\x20funds\x20into\x20the\x20reward\x20pool','reason':'Reward\x20pool\x20must\x20be\x20funded\x20before\x20claimants\x20can\x20withdraw','tool':'onchain_operations\x20(treasury)','priority':'recommended'},{'when':a=>a==='bridge_cross_chain_wow_to_evm','action':'poll\x20query_transfer_status\x20until\x20bridge\x20signs\x20(~1-5\x20min),\x20then\x20call\x20claim_wow_to_evm\x20to\x20complete','reason':'Cross-chain\x20WOW→EVM\x20is\x20a\x202-step\x20process:\x20deposit\x20first,\x20then\x20claim\x20after\x20bridge\x20confirmation','tool':'bridge_operation\x20(query_transfer_status,\x20then\x20claim_wow_to_evm)','priority':'required'},{'when':a=>a==='bridge_cross_chain_evm_to_wow','action':'poll\x20query_transfer_status\x20to\x20monitor\x20auto-claim\x20progress\x20(~10-20\x20min)','reason':'EVM→WOW\x20cross-chain\x20auto-claims;\x20monitor\x20progress\x20but\x20no\x20manual\x20action\x20needed','tool':'bridge_operation\x20(query_transfer_status)','priority':'recommended'},{'when':a=>a==='bridge_claim_wow_to_evm','action':'verify\x20recipient\x20EVM\x20balance\x20updated','reason':'Claim\x20completes\x20the\x20cross-chain\x20transfer;\x20verify\x20funds\x20arrived\x20on\x20EVM\x20side','tool':'bridge_operation\x20(query_active_evm_account)','priority':'recommended'},{'when':a=>a==='bridge_withdraw','action':'verify\x20WOW\x20balance\x20updated','reason':'Withdrawal\x20moves\x20funds\x20from\x20active\x20EVM\x20account\x20to\x20WOW;\x20verify\x20balance','tool':'account_operation\x20(balance)','priority':'recommended'},{'when':a=>a==='account_new','action':'claim\x20faucet\x20tokens\x20for\x20gas\x20if\x20on\x20testnet,\x20then\x20proceed\x20to\x20create\x20Service','reason':'New\x20account\x20needs\x20gas\x20tokens\x20before\x20on-chain\x20operations','tool':'account_operation\x20(faucet)','priority':'recommended'},{'when':a=>a==='account_faucet','action':'proceed\x20to\x20create\x20Permission\x20and\x20Service\x20objects','reason':'Account\x20is\x20now\x20funded;\x20start\x20building\x20your\x20service','tool':'onchain_operations\x20(permission,\x20service)','priority':'recommended'},{'when':a=>a==='query_toolkit','action':'use\x20the\x20queried\x20object\x20data\x20to\x20plan\x20next\x20operations','reason':'Query\x20results\x20reveal\x20current\x20object\x20states\x20for\x20decision-making','priority':'optional'}];function inferNextActions(a,b,c){return NEXT_ACTION_RULES['filter'](d=>d['when'](a,b,c))['map'](d=>({'action':d['action'],'reason':d['reason'],'tool':d['tool'],'priority':d['priority']}));}function inferWarnings(a,b,c){const d=[];return a==='service'&&b?.['order_allocators']===undefined&&d['push']('order_allocators\x20not\x20configured;\x20order\x20funds\x20cannot\x20be\x20distributed\x20automatically'),a==='reward'&&(b?.['balance']==='0'||b?.['balance']===0x0)&&d['push']('Reward\x20pool\x20balance\x20is\x20zero;\x20claimants\x20cannot\x20withdraw'),a==='order'&&b?.['transfer_to']!==undefined&&d['push']('[TRANSPARENCY]\x20Order\x20ownership\x20is\x20being\x20transferred\x20(likely\x20to\x20a\x20supplier/sub-contractor).\x20'+'Ensure\x20the\x20end\x20customer\x20is\x20informed\x20about\x20who\x20fulfills\x20their\x20order\x20—\x20this\x20builds\x20trust\x20and\x20is\x20required\x20for\x20procurement\x20sub-orders.'),d;}function composeSummary(a,b,c,d,e){const f=a['replace'](/_/g,'\x20');if(b==='failed')return'Failed\x20to\x20'+f;if(b==='pending_input')return f+'\x20requires\x20Guard\x20submission\x20to\x20proceed';const g=[];if(c['length'])g['push']('created\x20'+c['length']+'\x20object(s)');if(d['length'])g['push']('modified\x20'+d['length']+'\x20object(s)');if(e['length']){if(a==='allocate_funds'){const h=e['map'](i=>{const j=i['amount'],k=shortCoinType(i['coinType']),l=i['to']?shortAddr(i['to']):null,m=i['from']?shortAddr(i['from']):null;if(l)return j+'\x20'+k+'\x20→\x20'+l;if(m)return j+'\x20'+k+'\x20from\x20'+m;return j+'\x20'+k;})['join'](';\x20');g['push']('distributed:\x20'+h);}else g['push'](e['length']+'\x20fund\x20movement(s)');}return'Successfully\x20'+f+(g['length']?'\x20('+g['join'](',\x20')+')':'');}function shortAddr(a){if(a['length']>0xe)return a['slice'](0x0,0x8)+'...'+a['slice'](-0x4);return a;}function shortCoinType(a){if(!a)return'coin';const b=a['split']('::');return b[b['length']-0x1]||a;}function buildCustomerAdvice(a,b,c){if(!a268a('customer_intelligence'))return undefined;let d;if(a==='order')d='preorder';else{if(a==='query_toolkit'||a==='onchain_table_data'||a==='onchain_events')d='browse';else{if(a==='service')d='evaluate';else return undefined;}}const e=b?.['service_name']??b?.['service_id']??b?.['service']??b?.['name'],f=b?.['order_name']??b?.['order_id']??b?.['order'];let g;if(b?.['price']!==undefined)try{g=BigInt(String(b['price']));}catch{}if(g===undefined&&c?.['price']!==undefined)try{g=BigInt(String(c['price']));}catch{}const h=booleanFromSignals(b?.['arb_name']!==undefined||b?.['arbitration']!==undefined,b?.['arb']===![]),i=booleanFromSignals(b?.['compensation_fund']!==undefined||b?.['compensation']!==undefined,![]),j=booleanFromSignals(b?.['refund']!==undefined,![]),k=booleanFromSignals(b?.['um']!==undefined||b?.['um_name']!==undefined||b?.['messenger']!==undefined||c?.['um']!==undefined,b?.['um']===null||b?.['um_name']===null),l=Array['isArray'](b?.['customer_required'])?b['customer_required']['filter'](A=>typeof A==='string'):Array['isArray'](c?.['customer_required'])?c['customer_required']['filter'](A=>typeof A==='string'):[],m=h===![],n=i===![],o=typeof b?.['risk_score']==='number'?b['risk_score']:typeof c?.['risk_score']==='number'?c['risk_score']:undefined,p=b?.['risk_level']??c?.['risk_level'],q=getProfile(),s=q['risk_appetite']==='conservative'?0x46:q['risk_appetite']==='aggressive'?0x1e:0x32;let t;const u=c?.['_money_display']??(Array['isArray'](c?.['objects'])?c['objects'][0x0]?.['_money_display']:undefined),v=u?Object['values'](u)[0x0]:undefined;if(v?.['precision_known']===!![])t={'decimals':v['decimals'],'symbol':v['symbol']};else{const A=c?.['type_raw']??(Array['isArray'](c?.['objects'])?c['objects'][0x0]?.['type_raw']:undefined);t=registryDisplayHint(extractGenericTokenType(A))??registryDisplayHint(typeof b?.['type_parameter']==='string'?b['type_parameter']:undefined);}const w={'stage':d,'service_id':e,'order_id':f,'service_price':g,'token':t,'has_arbitration':h,'has_compensation':i,'has_refund_path':j,'has_messenger':k,'customer_required':l,'risk_score':o,'risk_level':p,'user_min_trust_score':s,'user_require_arbitration':q['risk_appetite']==='conservative','user_require_compensation':q['risk_appetite']==='conservative'},x=generateReminders(w),y=[];for(const B of x){if(B['action'])y['push'](B['action']);}m&&!y['some'](C=>C['includes']('arbitration'))&&y['push']('Require\x20the\x20merchant\x20to\x20configure\x20an\x20Arbitration\x20service\x20before\x20placing\x20the\x20order');n&&!y['some'](C=>C['includes']('compensation'))&&y['push']('Require\x20the\x20merchant\x20to\x20set\x20a\x20compensation_fund\x20to\x20guarantee\x20automatic\x20payout\x20when\x20the\x20order\x20fails');const z={'recommendations':y,'reminders':x['map'](C=>({'id':C['id'],'stage':C['stage'],'priority':C['priority'],'message':C['message'],'action':C['action']}))};if(o!==undefined)z['risk_score']=o;if(p!==undefined)z['risk_level']=p;return z;}function buildGuardAdvice(a,b,c){try{if(a==='guard')return buildGuardCreateAdvice(b);if(a==='gen_passport'){const e=c?.['error']?'fail':'pass';return{'current_round':'R8','test_result':{'status':e,'passport_id':e==='pass'?c?.['passport']:undefined,'failure_node':e==='fail'?typeof c?.['error']==='string'?c['error']['slice'](0x0,0x78):undefined:undefined}};}const d=typeof c?.['error']==='string'?c['error']:'';if(d['includes']('GUARD')||d['includes']('Guard')||d['includes']('guard'))return{'risk_warnings':['Guard\x20verification\x20failed:\x20'+d['slice'](0x0,0xc8),'Suggestion:\x20check\x20whether\x20the\x20submission\x20data\x20matches\x20the\x20Guard\x20table\x20declaration,\x20or\x20query\x20the\x20Guard\x20definition\x20to\x20learn\x20the\x20required\x20submission']};return undefined;}catch{return undefined;}}function buildGuardCreateAdvice(a){if(!a)return undefined;const b=convertCallDataToPuzzleInput(a),c=derivePuzzleFromCallData(b),d=getPuzzleStatusBooleans(c);let e,f,g;a['binding_hint']?.['action']&&(e=inferSceneFromAction(a['binding_hint']['action']),e&&(f=e['name'],g=e['special_constraints']));let h;const i=a['binding_hint']?.['rule_sentence']||a['binding_hint']?.['action']||'';if(i){const r=matchSemanticPattern(i);r['length']>0x0&&(h=r['map'](s=>s['id']+':\x20'+s['pattern_name']));}let j;try{const s=generateConfirmationText(c);!s['startsWith']('[Puzzle\x20incomplete]')&&(j=s);}catch{}let k;const l=getPendingQuestions(c);l['length']>0x0&&(k=l);let m;if(e){const t=mapSceneToObjectType(e);if(t){const u=GUARDQUERY['filter'](v=>v['objectType']===t)['slice'](0x0,0xa)['map'](v=>({'id':v['id'],'name':v['name'],'objectType':String(v['objectType']),'returnType':String(v['return']),'description':v['description']}));u['length']>0x0&&(m=u);}}const n=assessGuardRisksForOperation('guard',a);let o,p;if(n){const v=getRiskSummary(n);o={'overall_risk':v['risk_count']>0x0?n['overall_risk']:'info','risk_count':v['risk_count'],'critical_count':v['critical_count'],'high_count':v['high_count'],'needs_human_review':v['needs_human_review'],'top_risks':v['top_risks'],'stakeholder_advice':n['stakeholder_advice']};const w=n['risks']['map'](x=>'['+x['level']['toUpperCase']()+']\x20'+x['title']+':\x20'+x['description']);w['length']>0x0&&(p=w);}const q={'current_round':'R7','puzzle_status':d};if(e)q['matched_scene']=e['id'];if(f)q['scene_description']=f;if(g)q['scene_constraints']=g;if(h)q['suggested_patterns']=h;if(m)q['available_queries']=m;if(p)q['risk_warnings']=p;if(k)q['pending_questions']=k;if(j)q['confirmation_text']=j;if(o)q['risk_assessment']=o;return q;}function convertCallDataToPuzzleInput(a){const b={};Array['isArray'](a['table'])&&(b['table']=a['table']['map'](c=>({'identifier':c['identifier'],'b_submission':c['b_submission'],'value_type':typeof c['value_type']==='string'?c['value_type']:String(c['value_type']),'value':convertValueSnapshot(c['value']),'name':c['name']??'','object_type':c['object_type']})));if(a['root']&&typeof a['root']==='object'){const c=a['root'];if(c['type']!=='file'&&c['type']!=='node')b['root']=convertNodeToSnapshot(a['root']);else c['type']==='node'&&a['root']['node']&&(b['root']=convertNodeToSnapshot(a['root']['node']));}a['rely']&&Array['isArray'](a['rely']['guards'])&&(b['rely']={'guards':a['rely']['guards']['map'](d=>typeof d==='string'?d:String(d)),'logic_or':a['rely']['logic_or']});if(a['binding_hint']){const d=a['binding_hint'],e={'action':d['action'],'host_object':d['host_object'],'binding_field':d['binding_field']};if(d['rule_sentence']!==undefined)e['rule_sentence']=d['rule_sentence'];if(d['failure_conditions']!==undefined)e['failure_conditions']=d['failure_conditions'];if(d['circular_reference']!==undefined)e['circular_reference']=d['circular_reference'];b['binding_hint']=e;}return b;}function convertNodeToSnapshot(a){if(!a||typeof a!=='object')return{'type':'unknown'};const b={'type':String(a['type']??'unknown')};typeof a['identifier']==='number'&&(b['identifier']=a['identifier']);a['query']!==undefined&&(b['query']=typeof a['query']==='number'?a['query']:String(a['query']));if(a['object']&&typeof a['object']==='object'){const c={'identifier':Number(a['object']['identifier'])};typeof a['object']['convert_witness']==='number'&&(c['convert_witness']=a['object']['convert_witness']),b['object']=c;}Array['isArray'](a['parameters'])&&(b['parameters']=a['parameters']['map'](d=>convertNodeToSnapshot(d)));if(typeof a['context']==='string'){const d=a['context'];(d==='Clock'||d==='Guard'||d==='Signer')&&(b['context']=d);}return Array['isArray'](a['nodes'])&&(b['nodes']=a['nodes']['map'](e=>convertNodeToSnapshot(e))),a['node']&&(b['node']=convertNodeToSnapshot(a['node'])),a['nodeLeft']&&(b['nodeLeft']=convertNodeToSnapshot(a['nodeLeft'])),a['nodeRight']&&(b['nodeRight']=convertNodeToSnapshot(a['nodeRight'])),b;}function convertValueSnapshot(a){if(a===undefined||a===null)return undefined;if(typeof a==='string'||typeof a==='number'||typeof a==='boolean')return a;if(Array['isArray'](a)){const b=a['every'](e=>typeof e==='string');if(b)return a;const c=a['every'](e=>typeof e==='number');if(c)return a;const d=a['every'](e=>typeof e==='boolean');if(d)return a;return JSON['stringify'](a);}return JSON['stringify'](a);}function mapSceneToObjectType(a){const b=a['host_object'];if(b==='Standalone')return undefined;return b;}export function buildSemantic(a,b){if(!b)return undefined;const c=inferIntent(b['operation_type'],b['data']),d=inferStatus(a),e=a?.['objectChanges']||[],g=a?.['balanceChanges']||[],h=a?.['events']||[],i=tagObjectRoles(e['filter'](u=>u?.['type']==='created')),j=tagObjectRoles(e['filter'](u=>u?.['type']==='mutated'||u?.['type']==='published')),k=tagFundRoles(g,b['operation_type'],b['data'],h),l=annotateEvents(h),m=inferNextActions(b['operation_type'],b['data'],d),n=inferWarnings(b['operation_type'],b['data'],a);b['pre_warnings']&&b['pre_warnings']['length']>0x0&&n['push'](...b['pre_warnings']);if(b['operation_type']==='service'&&b['data']?.['publish']===!![]){const u=auditService(b['data']);for(const v of u){const w=v['severity']==='error'?'[AUDIT\x20ERROR]\x20':v['severity']==='warning'?'[AUDIT]\x20':'[INFO]\x20';n['push'](w+v['message']);}}let o;const p=a268a('experience_layer');if(p)try{const x=getExperienceFeedback(b['operation_type'],b['data'],c);x&&(o=x);const y=d==='success'?'success':d==='failed'?'failed':'partial',z=[...i,...j]['map'](B=>B['id'])['filter'](Boolean),A=inferErrorCodeForSignal(a);recordOperationOutcome(b['operation_type'],b['data'],c,y,A,z);}catch{}let q;if(a268a('industry_evolution'))try{const B=typeof b['data']?.['industry']==='string'&&b['data']['industry']['trim']()?b['data']['industry']['trim']():undefined;if(B&&!p){const C=d==='success'?{'success':!![]}:{'success':![],'error_code':inferErrorCodeForSignal(a)};recordIndustrySignal(B,{'type':b['operation_type'],'data':b['data']},C);}if(B){const D=injectEvolutionContext(undefined,B,deriveAdviceRole(b['operation_type'],b['data']));D&&(D['industry_signal']||D['evolution_advice']||D['confidence']>0x0)&&(q=D);}}catch{}let r;if(a268a('semantic_rich'))try{const E=listServices(),F=E['filter'](H=>H['enabled'])['map'](H=>H['name']),G=E['filter'](H=>!H['enabled'])['map'](H=>H['name']);r={'active':F,'inactive':G['length']?G:undefined};}catch{}let s;try{s=buildCustomerAdvice(b['operation_type'],b['data'],a);}catch{}let t;try{t=buildGuardAdvice(b['operation_type'],b['data'],a);}catch{}return{'intent':c,'status':d,'summary':composeSummary(c,d,i,j,k),'created':i['length']?i:undefined,'modified':j['length']?j:undefined,'released':k['length']?k:undefined,'events':l['length']?l:undefined,'next_actions':m['length']?m:undefined,'warnings':n['length']?n:undefined,'experience':o,'service_status':r,'customer_advice':s,'evolution_context':q,'guard_advice':t};}function inferErrorCodeForSignal(a){if(!a)return undefined;if(typeof a['error']==='string')return a['error']['slice'](0x0,0x40);return undefined;}export function buildDataSemantic(a,b,c,d){if(!b)return undefined;const e=inferIntent(b['operation_type'],b['data']),f=[];b['pre_warnings']&&b['pre_warnings']['length']>0x0&&f['push'](...b['pre_warnings']);let g;if(c)g='failed';else{g='success';if(Array['isArray'](a)&&a['length']===0x0)g='partial',f['push']('no\x20results\x20found');else{if(a===null||a===undefined)g='partial',f['push']('no\x20results\x20found');else{if(typeof a==='object'&&!Array['isArray'](a)){const n=Object['values'](a);n['length']>0x0&&n['every'](o=>Array['isArray'](o)?o['length']===0x0:o===null||o===undefined)&&(g='partial',f['push']('no\x20results\x20found'));}}}}const h=inferNextActions(b['operation_type'],b['data'],g);let i;if(!c&&b['operation_type']==='onchain_events'){const o=Array['isArray'](a)?a:a?.['data']&&Array['isArray'](a['data'])?a['data']:null;if(o){i=annotateEvents(o);if(i['length']===0x0)i=undefined;}}const j=e['replace'](/_/g,'\x20');let k;if(g==='failed')k=d?'Failed\x20to\x20'+j+':\x20'+d:'Failed\x20to\x20'+j;else g==='partial'?k=j+'\x20completed\x20with\x20no\x20results':k='Successfully\x20'+j;let l;if(a268a('semantic_rich'))try{const p=listServices(),q=p['filter'](t=>t['enabled'])['map'](t=>t['name']),r=p['filter'](t=>!t['enabled'])['map'](t=>t['name']);l={'active':q,'inactive':r['length']?r:undefined};}catch{}let m;if(!c)try{m=buildCustomerAdvice(b['operation_type'],b['data'],a);}catch{}return{'intent':e,'status':g,'summary':k,'events':i,'next_actions':h['length']?h:undefined,'warnings':f['length']?f:undefined,'service_status':l,'customer_advice':m};}