@wowok/agent-mcp 2.7.1 → 2.7.3

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 (597) hide show
  1. package/dist/config/index.js +1 -1
  2. package/dist/config/runtime.js +1 -238
  3. package/dist/customer/account-events.d.ts +32 -0
  4. package/dist/customer/account-events.js +1 -0
  5. package/dist/customer/customer-advice.d.ts +1 -0
  6. package/dist/customer/customer-advice.js +1 -130
  7. package/dist/customer/index.js +1 -11
  8. package/dist/customer/industry-risks.js +1 -438
  9. package/dist/customer/info-puzzle.js +1 -681
  10. package/dist/customer/order-monitor.js +1 -328
  11. package/dist/customer/order-strategy.d.ts +1 -1
  12. package/dist/customer/order-strategy.js +1 -373
  13. package/dist/customer/post-purchase.js +1 -351
  14. package/dist/customer/preorder-compare.js +1 -34
  15. package/dist/customer/reminder-system.d.ts +2 -0
  16. package/dist/customer/reminder-system.js +1 -316
  17. package/dist/customer/risk-assessment.d.ts +1 -0
  18. package/dist/customer/risk-assessment.js +1 -397
  19. package/dist/customer/types.d.ts +2 -0
  20. package/dist/customer/types.js +1 -13
  21. package/dist/customer/user-preferences.js +1 -460
  22. package/dist/evaluation/arbitration-game.d.ts +9 -2
  23. package/dist/evaluation/arbitration-game.js +1 -48
  24. package/dist/evaluation/builtins/arbitration-score.d.ts +41 -0
  25. package/dist/evaluation/builtins/arbitration-score.js +1 -0
  26. package/dist/evaluation/builtins/demand-match.js +1 -153
  27. package/dist/evaluation/builtins/index.d.ts +1 -0
  28. package/dist/evaluation/builtins/index.js +1 -10
  29. package/dist/evaluation/builtins/service-risk.js +1 -55
  30. package/dist/evaluation/capability.js +1 -13
  31. package/dist/evaluation/category-match-rules.d.ts +30 -0
  32. package/dist/evaluation/category-match-rules.js +1 -0
  33. package/dist/evaluation/composer.js +1 -40
  34. package/dist/evaluation/engine.js +1 -175
  35. package/dist/evaluation/extract.js +1 -115
  36. package/dist/evaluation/game-strategy.d.ts +27 -0
  37. package/dist/evaluation/game-strategy.js +1 -0
  38. package/dist/evaluation/gap.js +1 -100
  39. package/dist/evaluation/index.d.ts +2 -0
  40. package/dist/evaluation/index.js +1 -11
  41. package/dist/evaluation/location-match.d.ts +42 -0
  42. package/dist/evaluation/location-match.js +1 -0
  43. package/dist/evaluation/node-game.d.ts +31 -3
  44. package/dist/evaluation/node-game.js +1 -57
  45. package/dist/evaluation/path-reasoning.d.ts +35 -0
  46. package/dist/evaluation/path-reasoning.js +1 -0
  47. package/dist/evaluation/region.d.ts +6 -0
  48. package/dist/evaluation/region.js +1 -36
  49. package/dist/evaluation/types.d.ts +18 -0
  50. package/dist/evaluation/types.js +1 -1
  51. package/dist/evaluation/user-injection.js +1 -27
  52. package/dist/experience/experience-reuse.js +1 -103
  53. package/dist/experience/index.js +1 -5
  54. package/dist/experience/intent-distill.js +1 -83
  55. package/dist/experience/realtime-feedback.js +1 -94
  56. package/dist/experience/types.js +1 -1
  57. package/dist/experience/user-profile.d.ts +1 -1
  58. package/dist/experience/user-profile.js +1 -171
  59. package/dist/extensions/business-modules.js +1 -287
  60. package/dist/extensions/capability-manifest.js +1 -781
  61. package/dist/extensions/constraint-registry.js +1 -198
  62. package/dist/extensions/index.d.ts +6 -0
  63. package/dist/extensions/index.js +1 -6
  64. package/dist/extensions/industry-layers.d.ts +75 -0
  65. package/dist/extensions/industry-layers.js +1 -0
  66. package/dist/extensions/industry-pack.d.ts +105 -0
  67. package/dist/extensions/industry-pack.js +1 -0
  68. package/dist/extensions/metric-registry.js +1 -257
  69. package/dist/extensions/mode-evaluator.d.ts +1 -1
  70. package/dist/extensions/mode-evaluator.js +1 -170
  71. package/dist/extensions/modes.js +1 -499
  72. package/dist/extensions/registry.d.ts +1 -0
  73. package/dist/extensions/registry.js +1 -717
  74. package/dist/extensions/types.js +1 -1
  75. package/dist/graph/base.d.ts +8 -0
  76. package/dist/graph/base.js +1 -0
  77. package/dist/harness/auto-escalation.js +1 -68
  78. package/dist/harness/checkpoint.js +1 -129
  79. package/dist/harness/index.d.ts +1 -0
  80. package/dist/harness/index.js +1 -78
  81. package/dist/harness/plan.d.ts +2 -0
  82. package/dist/harness/plan.js +1 -315
  83. package/dist/harness/recover.d.ts +1 -1
  84. package/dist/harness/recover.js +1 -139
  85. package/dist/harness/types.d.ts +2 -3
  86. package/dist/harness/types.js +1 -1
  87. package/dist/harness/verify.js +1 -237
  88. package/dist/index.js +1 -273
  89. package/dist/intent/enrich.js +1 -67
  90. package/dist/intent/index.js +1 -60
  91. package/dist/intent/matcher.js +1 -81
  92. package/dist/intent/store.js +1 -55
  93. package/dist/intent/types.js +1 -10
  94. package/dist/knowledge/acquisition-flywheel.js +1 -192
  95. package/dist/knowledge/allocation-confirm.js +1 -534
  96. package/dist/knowledge/allocation-context.js +1 -249
  97. package/dist/knowledge/allocation-ledger.js +1 -463
  98. package/dist/knowledge/allocation-puzzle.js +1 -298
  99. package/dist/knowledge/allocation-risk.js +1 -568
  100. package/dist/knowledge/allocation-templates.js +1 -970
  101. package/dist/knowledge/allocation-translation.js +1 -585
  102. package/dist/knowledge/anti-cheat.d.ts +37 -0
  103. package/dist/knowledge/anti-cheat.js +1 -0
  104. package/dist/knowledge/arb-confirm.d.ts +28 -0
  105. package/dist/knowledge/arb-confirm.js +1 -0
  106. package/dist/knowledge/arb-risk.js +1 -210
  107. package/dist/knowledge/arb-translation.d.ts +48 -0
  108. package/dist/knowledge/arb-translation.js +1 -0
  109. package/dist/knowledge/arbitration-confirm.js +1 -559
  110. package/dist/knowledge/arbitration-context.js +1 -505
  111. package/dist/knowledge/arbitration-ledger.js +1 -521
  112. package/dist/knowledge/arbitration-puzzle.js +1 -304
  113. package/dist/knowledge/arbitration-risk.js +1 -423
  114. package/dist/knowledge/arbitration-templates.js +1 -276
  115. package/dist/knowledge/arbitration-translation.js +1 -487
  116. package/dist/knowledge/audit-rules.js +1 -141
  117. package/dist/knowledge/bridge-confirm.d.ts +26 -0
  118. package/dist/knowledge/bridge-confirm.js +1 -0
  119. package/dist/knowledge/bridge-risk.js +1 -263
  120. package/dist/knowledge/bridge-translation.d.ts +37 -0
  121. package/dist/knowledge/bridge-translation.js +1 -0
  122. package/dist/knowledge/contact-confirm.d.ts +27 -0
  123. package/dist/knowledge/contact-confirm.js +1 -0
  124. package/dist/knowledge/contact-risk.js +1 -200
  125. package/dist/knowledge/contact-templates.js +1 -60
  126. package/dist/knowledge/contact-translation.d.ts +39 -0
  127. package/dist/knowledge/contact-translation.js +1 -0
  128. package/dist/knowledge/demand-confirm.js +1 -206
  129. package/dist/knowledge/demand-context.d.ts +17 -0
  130. package/dist/knowledge/demand-context.js +1 -0
  131. package/dist/knowledge/demand-ledger.d.ts +26 -0
  132. package/dist/knowledge/demand-ledger.js +1 -0
  133. package/dist/knowledge/demand-matching.js +1 -132
  134. package/dist/knowledge/demand-puzzle.d.ts +29 -0
  135. package/dist/knowledge/demand-puzzle.js +1 -0
  136. package/dist/knowledge/demand-risk.js +1 -240
  137. package/dist/knowledge/demand-templates.d.ts +12 -0
  138. package/dist/knowledge/demand-templates.js +1 -0
  139. package/dist/knowledge/demand-translation.js +1 -354
  140. package/dist/knowledge/deployment-scanner.js +1 -823
  141. package/dist/knowledge/dynamic-pricing.js +1 -87
  142. package/dist/knowledge/evidence-review.d.ts +12 -0
  143. package/dist/knowledge/evidence-review.js +1 -0
  144. package/dist/knowledge/examples-scanner-cli.js +1 -26
  145. package/dist/knowledge/examples-scanner.js +1 -843
  146. package/dist/knowledge/flywheel-loop.d.ts +0 -1
  147. package/dist/knowledge/flywheel-loop.js +1 -404
  148. package/dist/knowledge/fund-layer.js +1 -973
  149. package/dist/knowledge/glossary.js +1 -211
  150. package/dist/knowledge/guard-confirm.js +1 -406
  151. package/dist/knowledge/guard-context.js +1 -287
  152. package/dist/knowledge/guard-design-patterns.js +1 -360
  153. package/dist/knowledge/guard-ledger.js +1 -260
  154. package/dist/knowledge/guard-lint.js +1 -670
  155. package/dist/knowledge/guard-migration.d.ts +1 -1
  156. package/dist/knowledge/guard-migration.js +1 -228
  157. package/dist/knowledge/guard-puzzle.js +1 -805
  158. package/dist/knowledge/guard-render.js +1 -700
  159. package/dist/knowledge/guard-risk.js +1 -1879
  160. package/dist/knowledge/guard-submission-prompt.js +1 -171
  161. package/dist/knowledge/guard-templates.js +1 -1105
  162. package/dist/knowledge/guard-translation.js +1 -1119
  163. package/dist/knowledge/index.d.ts +71 -3
  164. package/dist/knowledge/index.js +1 -436
  165. package/dist/knowledge/industry-evolution.js +1 -323
  166. package/dist/knowledge/industry-generalizer.js +1 -381
  167. package/dist/knowledge/industry-registry.js +1 -174
  168. package/dist/knowledge/intent-metrics.d.ts +4 -3
  169. package/dist/knowledge/intent-metrics.js +1 -566
  170. package/dist/knowledge/machine-confirm.js +1 -559
  171. package/dist/knowledge/machine-context.js +1 -833
  172. package/dist/knowledge/machine-ledger.js +1 -338
  173. package/dist/knowledge/machine-puzzle.js +1 -494
  174. package/dist/knowledge/machine-render.js +1 -565
  175. package/dist/knowledge/machine-risk.js +1 -669
  176. package/dist/knowledge/machine-templates.js +1 -1597
  177. package/dist/knowledge/machine-topology.js +1 -234
  178. package/dist/knowledge/machine-translation.js +1 -513
  179. package/dist/knowledge/market-metrics.d.ts +12 -0
  180. package/dist/knowledge/market-metrics.js +1 -0
  181. package/dist/knowledge/market-operations.d.ts +46 -0
  182. package/dist/knowledge/market-operations.js +1 -0
  183. package/dist/knowledge/mcp-schema-audit-cli.js +1 -45
  184. package/dist/knowledge/mcp-schema-audit.d.ts +22 -22
  185. package/dist/knowledge/mcp-schema-audit.js +1 -777
  186. package/dist/knowledge/onchain-constants.js +1 -35
  187. package/dist/knowledge/order-confirm.js +1 -573
  188. package/dist/knowledge/order-context.js +1 -390
  189. package/dist/knowledge/order-ledger.js +1 -341
  190. package/dist/knowledge/order-puzzle.js +1 -255
  191. package/dist/knowledge/order-risk.js +1 -653
  192. package/dist/knowledge/order-templates.js +1 -368
  193. package/dist/knowledge/order-translation.js +1 -550
  194. package/dist/knowledge/overrides-loader.js +1 -65
  195. package/dist/knowledge/passport-confirm.js +1 -531
  196. package/dist/knowledge/passport-context.js +1 -306
  197. package/dist/knowledge/passport-ledger.js +1 -282
  198. package/dist/knowledge/passport-puzzle.js +1 -333
  199. package/dist/knowledge/passport-risk.js +1 -450
  200. package/dist/knowledge/passport-templates.js +1 -568
  201. package/dist/knowledge/passport-translation.js +1 -516
  202. package/dist/knowledge/payment-confirm.d.ts +26 -0
  203. package/dist/knowledge/payment-confirm.js +1 -0
  204. package/dist/knowledge/payment-risk.js +1 -249
  205. package/dist/knowledge/payment-translation.d.ts +37 -0
  206. package/dist/knowledge/payment-translation.js +1 -0
  207. package/dist/knowledge/permission-confirm.js +1 -426
  208. package/dist/knowledge/permission-context.js +1 -224
  209. package/dist/knowledge/permission-ledger.d.ts +11 -0
  210. package/dist/knowledge/permission-ledger.js +1 -403
  211. package/dist/knowledge/permission-puzzle.js +1 -173
  212. package/dist/knowledge/permission-risk.js +1 -411
  213. package/dist/knowledge/permission-templates.js +1 -234
  214. package/dist/knowledge/permission-translation.js +1 -350
  215. package/dist/knowledge/personal-confirm.d.ts +29 -0
  216. package/dist/knowledge/personal-confirm.js +1 -0
  217. package/dist/knowledge/personal-risk.js +1 -212
  218. package/dist/knowledge/personal-translation.d.ts +37 -0
  219. package/dist/knowledge/personal-translation.js +1 -0
  220. package/dist/knowledge/process-model.d.ts +1 -11
  221. package/dist/knowledge/process-model.js +1 -160
  222. package/dist/knowledge/progress-confirm.js +1 -456
  223. package/dist/knowledge/progress-context.js +1 -452
  224. package/dist/knowledge/progress-ledger.js +1 -330
  225. package/dist/knowledge/progress-puzzle.js +1 -219
  226. package/dist/knowledge/progress-risk.js +1 -461
  227. package/dist/knowledge/progress-templates.js +1 -228
  228. package/dist/knowledge/progress-translation.js +1 -405
  229. package/dist/knowledge/proof-confirm.js +1 -187
  230. package/dist/knowledge/proof-context.d.ts +17 -0
  231. package/dist/knowledge/proof-context.js +1 -0
  232. package/dist/knowledge/proof-ledger.d.ts +34 -0
  233. package/dist/knowledge/proof-ledger.js +1 -0
  234. package/dist/knowledge/proof-puzzle.d.ts +35 -0
  235. package/dist/knowledge/proof-puzzle.js +1 -0
  236. package/dist/knowledge/proof-risk.js +1 -207
  237. package/dist/knowledge/proof-templates.d.ts +22 -0
  238. package/dist/knowledge/proof-templates.js +1 -0
  239. package/dist/knowledge/proof-translation.js +1 -283
  240. package/dist/knowledge/registrar-confirm.d.ts +26 -0
  241. package/dist/knowledge/registrar-confirm.js +1 -0
  242. package/dist/knowledge/registrar-risk.js +1 -217
  243. package/dist/knowledge/registrar-translation.d.ts +37 -0
  244. package/dist/knowledge/registrar-translation.js +1 -0
  245. package/dist/knowledge/repository-confirm.js +1 -286
  246. package/dist/knowledge/repository-context.d.ts +12 -0
  247. package/dist/knowledge/repository-context.js +1 -0
  248. package/dist/knowledge/repository-ledger.d.ts +25 -0
  249. package/dist/knowledge/repository-ledger.js +1 -0
  250. package/dist/knowledge/repository-puzzle.d.ts +30 -0
  251. package/dist/knowledge/repository-puzzle.js +1 -0
  252. package/dist/knowledge/repository-risk.js +1 -373
  253. package/dist/knowledge/repository-templates.d.ts +14 -0
  254. package/dist/knowledge/repository-templates.js +1 -0
  255. package/dist/knowledge/repository-translation.js +1 -445
  256. package/dist/knowledge/reputation-rules.js +1 -99
  257. package/dist/knowledge/resource-confirm.d.ts +25 -0
  258. package/dist/knowledge/resource-confirm.js +1 -0
  259. package/dist/knowledge/resource-risk.js +1 -157
  260. package/dist/knowledge/resource-translation.d.ts +37 -0
  261. package/dist/knowledge/resource-translation.js +1 -0
  262. package/dist/knowledge/reward-confirm.js +1 -526
  263. package/dist/knowledge/reward-context.d.ts +2 -2
  264. package/dist/knowledge/reward-context.js +1 -504
  265. package/dist/knowledge/reward-ledger.js +1 -502
  266. package/dist/knowledge/reward-puzzle.js +1 -300
  267. package/dist/knowledge/reward-risk.js +1 -627
  268. package/dist/knowledge/reward-templates.js +1 -197
  269. package/dist/knowledge/reward-translation.js +1 -501
  270. package/dist/knowledge/safety-rules.d.ts +1 -0
  271. package/dist/knowledge/safety-rules.js +1 -404
  272. package/dist/knowledge/scenario-modes.js +1 -321
  273. package/dist/knowledge/service-confirm.js +1 -807
  274. package/dist/knowledge/service-context.js +1 -403
  275. package/dist/knowledge/service-ledger.js +1 -609
  276. package/dist/knowledge/service-puzzle.js +1 -236
  277. package/dist/knowledge/service-risk.d.ts +1 -1
  278. package/dist/knowledge/service-risk.js +1 -651
  279. package/dist/knowledge/service-templates.js +1 -456
  280. package/dist/knowledge/service-translation.js +1 -622
  281. package/dist/knowledge/template-registry.js +1 -353
  282. package/dist/knowledge/tool-constraints.js +1 -195
  283. package/dist/knowledge/tools-reference.js +1 -178
  284. package/dist/knowledge/treasury-confirm.js +1 -512
  285. package/dist/knowledge/treasury-context.js +1 -363
  286. package/dist/knowledge/treasury-ledger.js +1 -300
  287. package/dist/knowledge/treasury-puzzle.js +1 -216
  288. package/dist/knowledge/treasury-risk.js +1 -440
  289. package/dist/knowledge/treasury-templates.js +1 -358
  290. package/dist/knowledge/treasury-translation.js +1 -498
  291. package/dist/knowledge/trust-metrics.js +1 -198
  292. package/dist/knowledge/universal-template.d.ts +22 -0
  293. package/dist/knowledge/universal-template.js +1 -0
  294. package/dist/knowledge/util-confirm.d.ts +24 -0
  295. package/dist/knowledge/util-confirm.js +1 -0
  296. package/dist/knowledge/util-risk.js +1 -135
  297. package/dist/knowledge/util-translation.d.ts +38 -0
  298. package/dist/knowledge/util-translation.js +1 -0
  299. package/dist/knowledge/workflow-guidance.d.ts +116 -0
  300. package/dist/knowledge/workflow-guidance.js +1 -0
  301. package/dist/loop-engineering/aggregate.js +1 -132
  302. package/dist/loop-engineering/context-collect.js +1 -83
  303. package/dist/loop-engineering/diagnose.js +1 -273
  304. package/dist/loop-engineering/improve.js +1 -405
  305. package/dist/loop-engineering/index.js +1 -4
  306. package/dist/loop-engineering/pipeline.js +1 -56
  307. package/dist/mode-market/index.js +1 -3
  308. package/dist/mode-market/registry.js +1 -124
  309. package/dist/mode-market/review.js +1 -214
  310. package/dist/mode-market/submission.js +1 -85
  311. package/dist/participation/collaborator-interest.d.ts +23 -0
  312. package/dist/participation/collaborator-interest.js +1 -0
  313. package/dist/participation/customer-interest.d.ts +25 -0
  314. package/dist/participation/customer-interest.js +1 -0
  315. package/dist/participation/employee-kpi.d.ts +25 -0
  316. package/dist/participation/employee-kpi.js +1 -0
  317. package/dist/participation/employee-store.d.ts +16 -0
  318. package/dist/participation/employee-store.js +1 -0
  319. package/dist/participation/index.d.ts +2 -0
  320. package/dist/participation/index.js +1 -0
  321. package/dist/participation/merchant-interest.js +1 -100
  322. package/dist/participation/radar-core.d.ts +13 -3
  323. package/dist/participation/radar-core.js +1 -269
  324. package/dist/participation/supplier-interest.d.ts +25 -0
  325. package/dist/participation/supplier-interest.js +1 -0
  326. package/dist/persona/analyzer.js +1 -66
  327. package/dist/persona/bridge.js +1 -86
  328. package/dist/persona/defaults.js +1 -195
  329. package/dist/persona/experience-bridge.js +1 -23
  330. package/dist/persona/index.d.ts +9 -2
  331. package/dist/persona/index.js +1 -71
  332. package/dist/persona/local-region.d.ts +20 -0
  333. package/dist/persona/local-region.js +1 -0
  334. package/dist/persona/model.js +1 -111
  335. package/dist/persona/overrides.d.ts +10 -0
  336. package/dist/persona/overrides.js +1 -0
  337. package/dist/persona/pack-personae.d.ts +11 -0
  338. package/dist/persona/pack-personae.js +1 -0
  339. package/dist/persona/store.js +1 -62
  340. package/dist/persona/strategy-intent.d.ts +20 -0
  341. package/dist/persona/strategy-intent.js +1 -0
  342. package/dist/persona/types.d.ts +6 -2
  343. package/dist/persona/types.js +1 -5
  344. package/dist/project/business-puzzle.d.ts +1 -1
  345. package/dist/project/business-puzzle.js +1 -383
  346. package/dist/project/context-assembly.js +1 -254
  347. package/dist/project/deployment-bridge.js +1 -120
  348. package/dist/project/deployment-doc.js +1 -1126
  349. package/dist/project/edit-planner.js +1 -1342
  350. package/dist/project/evaluation.d.ts +37 -1
  351. package/dist/project/evaluation.js +1 -2011
  352. package/dist/project/game-theory.js +1 -177
  353. package/dist/project/graph-builder.js +1 -656
  354. package/dist/project/graph.d.ts +3 -6
  355. package/dist/project/graph.js +1 -340
  356. package/dist/project/handlers.d.ts +33 -2
  357. package/dist/project/handlers.js +1 -1784
  358. package/dist/project/index.d.ts +2 -0
  359. package/dist/project/index.js +1 -301
  360. package/dist/project/intent-analyzer.js +1 -149
  361. package/dist/project/machine-nodes.js +1 -36
  362. package/dist/project/merchant-guide.d.ts +19 -0
  363. package/dist/project/merchant-guide.js +1 -264
  364. package/dist/project/migration.js +1 -125
  365. package/dist/project/mode-actions.js +1 -309
  366. package/dist/project/namespace.js +1 -206
  367. package/dist/project/participation-radar.js +1 -428
  368. package/dist/project/pipeline-actions.js +1 -109
  369. package/dist/project/project-store.js +1 -422
  370. package/dist/project/query.js +1 -153
  371. package/dist/project/reverse-mapping.d.ts +34 -0
  372. package/dist/project/reverse-mapping.js +1 -0
  373. package/dist/project/risk-aggregator.js +1 -295
  374. package/dist/project/rollback-policy.js +1 -290
  375. package/dist/project/semantic-assembler.js +1 -345
  376. package/dist/project/semantic-graph.d.ts +3 -5
  377. package/dist/project/semantic-graph.js +1 -292
  378. package/dist/project/stage-gate.js +1 -369
  379. package/dist/project/substep-trace.js +1 -332
  380. package/dist/project/task-tracker.js +1 -78
  381. package/dist/project/workflow-design-assessment.d.ts +24 -0
  382. package/dist/project/workflow-design-assessment.js +1 -0
  383. package/dist/role/derivation.d.ts +18 -0
  384. package/dist/role/derivation.js +1 -0
  385. package/dist/role/index.d.ts +5 -0
  386. package/dist/role/index.js +1 -0
  387. package/dist/role/model.d.ts +8 -0
  388. package/dist/role/model.js +1 -0
  389. package/dist/role/resolution.d.ts +11 -0
  390. package/dist/role/resolution.js +1 -0
  391. package/dist/role/types.d.ts +11 -0
  392. package/dist/role/types.js +1 -0
  393. package/dist/rules.js +1 -52
  394. package/dist/safety/confirm-gate.d.ts +1 -1
  395. package/dist/safety/confirm-gate.js +1 -88
  396. package/dist/safety/index.js +1 -3
  397. package/dist/safety/preview.js +1 -52
  398. package/dist/schema/call/allocation.d.ts +186 -1385
  399. package/dist/schema/call/allocation.js +1 -34
  400. package/dist/schema/call/arbitration.d.ts +272 -1871
  401. package/dist/schema/call/arbitration.js +1 -113
  402. package/dist/schema/call/base.d.ts +1831 -9076
  403. package/dist/schema/call/base.js +1 -370
  404. package/dist/schema/call/bridge.d.ts +911 -3171
  405. package/dist/schema/call/bridge.js +1 -458
  406. package/dist/schema/call/contact.d.ts +135 -931
  407. package/dist/schema/call/contact.js +1 -37
  408. package/dist/schema/call/demand.d.ts +164 -1194
  409. package/dist/schema/call/demand.js +1 -47
  410. package/dist/schema/call/guard.d.ts +298 -1140
  411. package/dist/schema/call/guard.js +1 -161
  412. package/dist/schema/call/handler.js +1 -322
  413. package/dist/schema/call/index.js +1 -20
  414. package/dist/schema/call/machine.d.ts +459 -5403
  415. package/dist/schema/call/machine.js +1 -193
  416. package/dist/schema/call/order.d.ts +137 -844
  417. package/dist/schema/call/order.js +1 -35
  418. package/dist/schema/call/payment.d.ts +74 -561
  419. package/dist/schema/call/payment.js +1 -37
  420. package/dist/schema/call/permission-handler.js +1 -54
  421. package/dist/schema/call/permission.d.ts +335 -2791
  422. package/dist/schema/call/permission.js +1 -105
  423. package/dist/schema/call/personal.d.ts +227 -1814
  424. package/dist/schema/call/personal.js +1 -78
  425. package/dist/schema/call/progress.d.ts +140 -843
  426. package/dist/schema/call/progress.js +1 -47
  427. package/dist/schema/call/proof.d.ts +42 -258
  428. package/dist/schema/call/proof.js +1 -33
  429. package/dist/schema/call/repository.d.ts +324 -2222
  430. package/dist/schema/call/repository.js +1 -77
  431. package/dist/schema/call/reward.d.ts +153 -1183
  432. package/dist/schema/call/reward.js +1 -30
  433. package/dist/schema/call/semantic.js +1 -1679
  434. package/dist/schema/call/service.d.ts +376 -3431
  435. package/dist/schema/call/service.js +1 -184
  436. package/dist/schema/call/treasury.d.ts +252 -2158
  437. package/dist/schema/call/treasury.js +1 -71
  438. package/dist/schema/common/index.d.ts +222 -697
  439. package/dist/schema/common/index.js +1 -407
  440. package/dist/schema/config/index.d.ts +18 -161
  441. package/dist/schema/config/index.js +1 -68
  442. package/dist/schema/employee/index.d.ts +99 -0
  443. package/dist/schema/employee/index.js +1 -0
  444. package/dist/schema/evaluation/index.d.ts +1062 -3748
  445. package/dist/schema/evaluation/index.js +1 -356
  446. package/dist/schema/index.d.ts +3 -0
  447. package/dist/schema/index.js +1 -17
  448. package/dist/schema/industry-pack/index.d.ts +132 -0
  449. package/dist/schema/industry-pack/index.js +1 -0
  450. package/dist/schema/intent-radar/index.d.ts +92 -245
  451. package/dist/schema/intent-radar/index.js +1 -89
  452. package/dist/schema/local/index.d.ts +2045 -18080
  453. package/dist/schema/local/index.js +1 -927
  454. package/dist/schema/local/wip.d.ts +61 -651
  455. package/dist/schema/local/wip.js +1 -187
  456. package/dist/schema/messenger/index.d.ts +949 -5557
  457. package/dist/schema/messenger/index.js +1 -475
  458. package/dist/schema/operations.d.ts +2969 -26518
  459. package/dist/schema/operations.js +1 -520
  460. package/dist/schema/persona/index.d.ts +469 -1820
  461. package/dist/schema/persona/index.js +1 -148
  462. package/dist/schema/project/index.d.ts +1027 -8408
  463. package/dist/schema/project/index.js +1 -2057
  464. package/dist/schema/query/index.d.ts +12041 -75261
  465. package/dist/schema/query/index.js +1 -1646
  466. package/dist/schema/schema-query/index.d.ts +35 -98
  467. package/dist/schema/schema-query/index.js +1 -104
  468. package/dist/schema/schema-version.js +1 -76
  469. package/dist/schema/task-status.d.ts +26 -132
  470. package/dist/schema/task-status.js +1 -36
  471. package/dist/schema/trust/index.d.ts +194 -1290
  472. package/dist/schema/trust/index.js +1 -314
  473. package/dist/schema/utils/guard-parser.js +1 -419
  474. package/dist/schema/utils/guard-query-utils.js +1 -46
  475. package/dist/schema/utils/node-parser.js +1 -369
  476. package/dist/schema/utils/object-type-utils.js +1 -35
  477. package/dist/schema/utils/permission-index-utils.js +1 -7
  478. package/dist/schema/utils/permission-machine-check.js +1 -121
  479. package/dist/schema/utils/skills-recommendation.d.ts +1 -0
  480. package/dist/schema/utils/skills-recommendation.js +1 -77
  481. package/dist/schema/workspace/index.d.ts +69 -0
  482. package/dist/schema/workspace/index.js +1 -0
  483. package/dist/schema-query-impl/index.js +1 -0
  484. package/dist/schemas/account_operation.output.json +3147 -1652
  485. package/dist/schemas/account_operation.schema.json +225 -218
  486. package/dist/schemas/bridge_operation.output.json +1168 -650
  487. package/dist/schemas/bridge_operation.schema.json +736 -504
  488. package/dist/schemas/config_operation.output.json +185 -179
  489. package/dist/schemas/config_operation.schema.json +21 -26
  490. package/dist/schemas/employee_operation.output.json +207 -0
  491. package/dist/schemas/employee_operation.schema.json +176 -0
  492. package/dist/schemas/evaluation_operation.output.json +2329 -557
  493. package/dist/schemas/evaluation_operation.schema.json +2939 -720
  494. package/dist/schemas/guard2file.output.json +58 -64
  495. package/dist/schemas/guard2file.schema.json +79 -81
  496. package/dist/schemas/index.json +29 -11
  497. package/dist/schemas/industry_pack_operation.output.json +594 -0
  498. package/dist/schemas/industry_pack_operation.schema.json +55 -0
  499. package/dist/schemas/intent_radar.output.json +275 -200
  500. package/dist/schemas/intent_radar.schema.json +124 -123
  501. package/dist/schemas/local_info_operation.output.json +1174 -657
  502. package/dist/schemas/local_info_operation.schema.json +119 -125
  503. package/dist/schemas/local_mark_operation.output.json +1239 -689
  504. package/dist/schemas/local_mark_operation.schema.json +91 -96
  505. package/dist/schemas/machineNode2file.output.json +63 -69
  506. package/dist/schemas/machineNode2file.schema.json +79 -81
  507. package/dist/schemas/messenger_operation.output.json +2722 -1528
  508. package/dist/schemas/messenger_operation.schema.json +1482 -1264
  509. package/dist/schemas/onchain_events.output.json +2590 -975
  510. package/dist/schemas/onchain_events.schema.json +117 -99
  511. package/dist/schemas/onchain_operations.output.json +3957 -2309
  512. package/dist/schemas/onchain_operations.schema.json +20799 -9285
  513. package/dist/schemas/onchain_operations_allocation.schema.json +172 -108
  514. package/dist/schemas/onchain_operations_arbitration.schema.json +233 -146
  515. package/dist/schemas/onchain_operations_contact.schema.json +129 -90
  516. package/dist/schemas/onchain_operations_demand.schema.json +170 -112
  517. package/dist/schemas/onchain_operations_gen_passport.schema.json +61 -646
  518. package/dist/schemas/onchain_operations_gen_proof.schema.json +40 -172
  519. package/dist/schemas/onchain_operations_guard.schema.json +3765 -294
  520. package/dist/schemas/onchain_operations_machine.schema.json +537 -164
  521. package/dist/schemas/onchain_operations_order.schema.json +126 -96
  522. package/dist/schemas/onchain_operations_payment.schema.json +82 -67
  523. package/dist/schemas/onchain_operations_permission.schema.json +331 -93
  524. package/dist/schemas/onchain_operations_personal.schema.json +636 -96
  525. package/dist/schemas/onchain_operations_progress.schema.json +125 -92
  526. package/dist/schemas/onchain_operations_proof.schema.json +76 -69
  527. package/dist/schemas/onchain_operations_repository.schema.json +636 -249
  528. package/dist/schemas/onchain_operations_reward.schema.json +218 -108
  529. package/dist/schemas/onchain_operations_service.schema.json +679 -221
  530. package/dist/schemas/onchain_operations_treasury.schema.json +401 -135
  531. package/dist/schemas/onchain_table_data.output.json +6018 -2430
  532. package/dist/schemas/onchain_table_data.schema.json +544 -430
  533. package/dist/schemas/persona_operation.output.json +1568 -265
  534. package/dist/schemas/persona_operation.schema.json +346 -202
  535. package/dist/schemas/project_operation.output.json +6957 -5147
  536. package/dist/schemas/project_operation.schema.json +1050 -1020
  537. package/dist/schemas/query_task_status.output.json +195 -99
  538. package/dist/schemas/query_task_status.schema.json +12 -18
  539. package/dist/schemas/query_toolkit.output.json +18870 -14566
  540. package/dist/schemas/query_toolkit.schema.json +614 -522
  541. package/dist/schemas/schema_query.output.json +127 -129
  542. package/dist/schemas/schema_query.schema.json +64 -69
  543. package/dist/schemas/trust_score.output.json +678 -587
  544. package/dist/schemas/trust_score.schema.json +289 -277
  545. package/dist/schemas/wip_file.output.json +116 -124
  546. package/dist/schemas/wip_file.schema.json +142 -143
  547. package/dist/schemas/workspace_operation.output.json +277 -0
  548. package/dist/schemas/workspace_operation.schema.json +45 -0
  549. package/dist/schemas/wowok_buildin_info.output.json +1693 -723
  550. package/dist/schemas/wowok_buildin_info.schema.json +576 -512
  551. package/dist/telemetry/index.js +1 -112
  552. package/dist/telemetry/redact.js +1 -23
  553. package/dist/telemetry/storage.js +1 -80
  554. package/dist/tools/handlers/bridge.d.ts +8 -1
  555. package/dist/tools/handlers/bridge.js +1 -1
  556. package/dist/tools/handlers/config.js +1 -74
  557. package/dist/tools/handlers/employee.d.ts +2 -0
  558. package/dist/tools/handlers/employee.js +1 -0
  559. package/dist/tools/handlers/evaluation.js +1 -123
  560. package/dist/tools/handlers/file-export.js +1 -90
  561. package/dist/tools/handlers/industry-pack.d.ts +2 -0
  562. package/dist/tools/handlers/industry-pack.js +1 -0
  563. package/dist/tools/handlers/intent-radar.js +1 -76
  564. package/dist/tools/handlers/local.js +1 -53
  565. package/dist/tools/handlers/messenger.js +1 -188
  566. package/dist/tools/handlers/onchain.js +1 -1180
  567. package/dist/tools/handlers/persona.js +1 -89
  568. package/dist/tools/handlers/project.js +1 -211
  569. package/dist/tools/handlers/query.js +1 -434
  570. package/dist/tools/handlers/schema-query.js +1 -176
  571. package/dist/tools/handlers/task-status.js +1 -26
  572. package/dist/tools/handlers/trust.js +1 -380
  573. package/dist/tools/handlers/wip.js +1 -90
  574. package/dist/tools/handlers/workspace.d.ts +2 -0
  575. package/dist/tools/handlers/workspace.js +1 -0
  576. package/dist/tools/index.d.ts +2 -1
  577. package/dist/tools/index.js +1 -1382
  578. package/dist/tools/retry.js +1 -85
  579. package/dist/tools/rules-hook.d.ts +1 -1
  580. package/dist/tools/rules-hook.js +1 -23
  581. package/dist/tools/shared.d.ts +1 -1
  582. package/dist/tools/shared.js +1 -130
  583. package/dist/tools/types.d.ts +2 -1
  584. package/dist/tools/types.js +1 -1
  585. package/dist/tools/upgrade-check.d.ts +19 -0
  586. package/dist/tools/upgrade-check.js +1 -0
  587. package/dist/tools/wip-deploy-assist.js +1 -306
  588. package/dist/tools/wrap.js +1 -500
  589. package/package.json +7 -6
  590. package/dist/knowledge/arbitration-trust.d.ts +0 -24
  591. package/dist/knowledge/arbitration-trust.js +0 -117
  592. package/dist/schema/call/bridge-handler.d.ts +0 -8
  593. package/dist/schema/call/bridge-handler.js +0 -265
  594. package/dist/schema/sync-layer4.d.ts +0 -21
  595. package/dist/schema/sync-layer4.js +0 -286
  596. package/dist/schema-query/index.js +0 -810
  597. /package/dist/{schema-query → schema-query-impl}/index.d.ts +0 -0
@@ -1,1679 +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
- pattern: /::demand::DemandFeedbackEvent|::demand::FeedbackEvent/i,
898
- business_meaning: "A demand owner gave feedback (acceptance score) on a presented service",
899
- category: "state_change",
900
- side_effect: "High acceptance score signals a strong service↔demand fit; low score signals a mismatch",
901
- },
902
- {
903
- pattern: /::entity::NewEntityEvent|::entity::EntityRegisteredEvent|::registrar::NewEntityEvent/i,
904
- business_meaning: "A new on-chain entity (user/merchant) was registered",
905
- category: "lifecycle",
906
- side_effect: "A new potential counterparty entered the ecosystem",
907
- },
908
- ];
909
- function extractRelatedObject(event) {
910
- if (!event || typeof event !== "object")
911
- return undefined;
912
- const fields = event.fields ?? event.payload ?? event;
913
- if (typeof fields !== "object")
914
- return undefined;
915
- for (const key of ["object_id", "objectId", "id", "parent", "service", "order", "machine", "reward", "treasury"]) {
916
- const v = fields[key];
917
- if (typeof v === "string" && v.startsWith("0x") && v.length >= 6)
918
- return v;
919
- }
920
- return undefined;
921
- }
922
- const BUILTIN_EVENT_TYPE_MAP = {
923
- NewOrderEvent: "::order::OrderCreatedEvent",
924
- ArbEvent: "::arbitration::ArbitrationRequestedEvent",
925
- ProgressEvent: "::progress::ProgressUpdatedEvent",
926
- DemandPresentEvent: "::demand::PresenterSubmittedEvent",
927
- DemandFeedbackEvent: "::demand::DemandFeedbackEvent",
928
- NewEntityEvent: "::entity::NewEntityEvent",
929
- };
930
- export function eventToSemantic(event) {
931
- const eventType = String(event?.type ?? event?.event_type ?? "");
932
- const typeRaw = String(event?.type_raw ?? "");
933
- const candidates = [typeRaw, eventType, BUILTIN_EVENT_TYPE_MAP[eventType] ?? ""].filter(Boolean);
934
- const rule = EVENT_SEMANTIC_RULES.find((r) => candidates.some((c) => r.pattern.test(c)));
935
- if (!rule) {
936
- return {
937
- event_type: eventType,
938
- business_meaning: "Unknown event",
939
- category: "other",
940
- };
941
- }
942
- const related = rule.extractRelatedObject ? rule.extractRelatedObject(event) : extractRelatedObject(event);
943
- const result = {
944
- event_type: eventType,
945
- business_meaning: rule.business_meaning,
946
- category: rule.category,
947
- };
948
- if (related)
949
- result.related_object = related;
950
- if (rule.side_effect)
951
- result.side_effect = rule.side_effect;
952
- return result;
953
- }
954
- export function annotateEvents(events) {
955
- if (!Array.isArray(events))
956
- return [];
957
- return events.map(eventToSemantic);
958
- }
959
- const NEXT_ACTION_RULES = [
960
- {
961
- when: (ot) => ot === "service",
962
- action: "publish the Service when configuration is complete",
963
- reason: "Service must be published before customers can order",
964
- tool: "onchain_operations (service with publish:true)",
965
- priority: "recommended",
966
- },
967
- {
968
- when: (ot) => ot === "service",
969
- action: "add Machine nodes to define the service workflow",
970
- reason: "Machine drives order state transitions",
971
- tool: "onchain_operations (machine)",
972
- priority: "recommended",
973
- },
974
- {
975
- when: (ot) => ot === "machine",
976
- action: "bind Progress to track order execution",
977
- reason: "Progress provides customer-visible status updates",
978
- tool: "onchain_operations (progress)",
979
- priority: "recommended",
980
- },
981
- {
982
- when: (ot) => ot === "order",
983
- action: "wait for customer payment or proceed to allocation",
984
- reason: "Order lifecycle: payment → allocation → completion",
985
- priority: "optional",
986
- },
987
- {
988
- when: (ot, data) => ot === "order" && data?.transfer_to !== undefined,
989
- action: "inform the end customer about the supplier/sub-contractor who will fulfill this order",
990
- reason: "O-5 procurement sub-order transparency: customers have the right to know who fulfills their order",
991
- tool: "messenger_operation (notify customer)",
992
- priority: "recommended",
993
- },
994
- {
995
- when: (ot) => ot === "demand",
996
- action: "wait for presenter submissions or evaluate existing ones",
997
- reason: "Demand lifecycle: presenters submit solutions for reward",
998
- priority: "optional",
999
- },
1000
- {
1001
- when: (ot) => ot === "reward",
1002
- action: "deposit funds into the reward pool",
1003
- reason: "Reward pool must be funded before claimants can withdraw",
1004
- tool: "onchain_operations (treasury)",
1005
- priority: "recommended",
1006
- },
1007
- {
1008
- when: (ot) => ot === "bridge_cross_chain_wow_to_evm",
1009
- action: "poll query_transfer_status until bridge signs (~1-5 min), then call claim_wow_to_evm to complete",
1010
- reason: "Cross-chain WOW→EVM is a 2-step process: deposit first, then claim after bridge confirmation",
1011
- tool: "bridge_operation (query_transfer_status, then claim_wow_to_evm)",
1012
- priority: "required",
1013
- },
1014
- {
1015
- when: (ot) => ot === "bridge_cross_chain_evm_to_wow",
1016
- action: "poll query_transfer_status to monitor auto-claim progress (~10-20 min)",
1017
- reason: "EVM→WOW cross-chain auto-claims; monitor progress but no manual action needed",
1018
- tool: "bridge_operation (query_transfer_status)",
1019
- priority: "recommended",
1020
- },
1021
- {
1022
- when: (ot) => ot === "bridge_claim_wow_to_evm",
1023
- action: "verify recipient EVM balance updated",
1024
- reason: "Claim completes the cross-chain transfer; verify funds arrived on EVM side",
1025
- tool: "bridge_operation (query_active_evm_account)",
1026
- priority: "recommended",
1027
- },
1028
- {
1029
- when: (ot) => ot === "bridge_withdraw",
1030
- action: "verify WOW balance updated",
1031
- reason: "Withdrawal moves funds from active EVM account to WOW; verify balance",
1032
- tool: "account_operation (balance)",
1033
- priority: "recommended",
1034
- },
1035
- {
1036
- when: (ot) => ot === "account_new",
1037
- action: "claim faucet tokens for gas if on testnet, then proceed to create Service",
1038
- reason: "New account needs gas tokens before on-chain operations",
1039
- tool: "account_operation (faucet)",
1040
- priority: "recommended",
1041
- },
1042
- {
1043
- when: (ot) => ot === "account_faucet",
1044
- action: "proceed to create Permission and Service objects",
1045
- reason: "Account is now funded; start building your service",
1046
- tool: "onchain_operations (permission, service)",
1047
- priority: "recommended",
1048
- },
1049
- {
1050
- when: (ot) => ot === "query_toolkit",
1051
- action: "use the queried object data to plan next operations",
1052
- reason: "Query results reveal current object states for decision-making",
1053
- priority: "optional",
1054
- },
1055
- ];
1056
- function inferNextActions(operation_type, data, status) {
1057
- return NEXT_ACTION_RULES
1058
- .filter((r) => r.when(operation_type, data, status))
1059
- .map((r) => ({
1060
- action: r.action,
1061
- reason: r.reason,
1062
- tool: r.tool,
1063
- priority: r.priority,
1064
- }));
1065
- }
1066
- function inferWarnings(operation_type, data, _safeResult) {
1067
- const warnings = [];
1068
- if (operation_type === "service" && data?.order_allocators === undefined) {
1069
- warnings.push("order_allocators not configured; order funds cannot be distributed automatically");
1070
- }
1071
- if (operation_type === "reward" && (data?.balance === "0" || data?.balance === 0)) {
1072
- warnings.push("Reward pool balance is zero; claimants cannot withdraw");
1073
- }
1074
- if (operation_type === "order" && data?.transfer_to !== undefined) {
1075
- warnings.push("[TRANSPARENCY] Order ownership is being transferred (likely to a supplier/sub-contractor). " +
1076
- "Ensure the end customer is informed about who fulfills their order — this builds trust and is required for procurement sub-orders.");
1077
- }
1078
- return warnings;
1079
- }
1080
- function composeSummary(intent, status, created, modified, released) {
1081
- const intentVerb = intent.replace(/_/g, " ");
1082
- if (status === "failed")
1083
- return `Failed to ${intentVerb}`;
1084
- if (status === "pending_input")
1085
- return `${intentVerb} requires Guard submission to proceed`;
1086
- const parts = [];
1087
- if (created.length)
1088
- parts.push(`created ${created.length} object(s)`);
1089
- if (modified.length)
1090
- parts.push(`modified ${modified.length} object(s)`);
1091
- if (released.length) {
1092
- if (intent === "allocate_funds") {
1093
- const details = released.map(f => {
1094
- const amt = f.amount;
1095
- const coin = shortCoinType(f.coinType);
1096
- const recipient = f.to ? shortAddr(f.to) : null;
1097
- const sender = f.from ? shortAddr(f.from) : null;
1098
- if (recipient)
1099
- return `${amt} ${coin} → ${recipient}`;
1100
- if (sender)
1101
- return `${amt} ${coin} from ${sender}`;
1102
- return `${amt} ${coin}`;
1103
- }).join("; ");
1104
- parts.push(`distributed: ${details}`);
1105
- }
1106
- else {
1107
- parts.push(`${released.length} fund movement(s)`);
1108
- }
1109
- }
1110
- return `Successfully ${intentVerb}${parts.length ? ` (${parts.join(", ")})` : ""}`;
1111
- }
1112
- function shortAddr(addr) {
1113
- if (addr.length > 14) {
1114
- return addr.slice(0, 8) + "..." + addr.slice(-4);
1115
- }
1116
- return addr;
1117
- }
1118
- function shortCoinType(coinType) {
1119
- if (!coinType)
1120
- return "coin";
1121
- const parts = coinType.split("::");
1122
- return parts[parts.length - 1] || coinType;
1123
- }
1124
- function buildCustomerAdvice(operation_type, data, safeResult) {
1125
- if (!isRuntimeEnabled("customer_intelligence"))
1126
- return undefined;
1127
- let stage;
1128
- if (operation_type === "order") {
1129
- stage = "preorder";
1130
- }
1131
- else if (operation_type === "query_toolkit" || operation_type === "onchain_table_data" || operation_type === "onchain_events") {
1132
- stage = "browse";
1133
- }
1134
- else if (operation_type === "service") {
1135
- stage = "evaluate";
1136
- }
1137
- else {
1138
- return undefined;
1139
- }
1140
- const serviceId = data?.service_name ?? data?.service_id ?? data?.service ?? data?.name;
1141
- const orderId = data?.order_name ?? data?.order_id ?? data?.order;
1142
- let servicePrice;
1143
- if (data?.price !== undefined) {
1144
- try {
1145
- servicePrice = BigInt(String(data.price));
1146
- }
1147
- catch { }
1148
- }
1149
- if (servicePrice === undefined && safeResult?.price !== undefined) {
1150
- try {
1151
- servicePrice = BigInt(String(safeResult.price));
1152
- }
1153
- catch { }
1154
- }
1155
- const hasArbitration = booleanFromSignals(data?.arb_name !== undefined || data?.arbitration !== undefined, data?.arb === false);
1156
- const hasCompensation = booleanFromSignals(data?.compensation_fund !== undefined || data?.compensation !== undefined, false);
1157
- const hasRefundPath = booleanFromSignals(data?.refund !== undefined, false);
1158
- const hasMessenger = booleanFromSignals(data?.um !== undefined ||
1159
- data?.um_name !== undefined ||
1160
- data?.messenger !== undefined ||
1161
- safeResult?.um !== undefined, data?.um === null || data?.um_name === null);
1162
- const customerRequired = Array.isArray(data?.customer_required)
1163
- ? data.customer_required.filter((x) => typeof x === "string")
1164
- : Array.isArray(safeResult?.customer_required)
1165
- ? safeResult.customer_required.filter((x) => typeof x === "string")
1166
- : [];
1167
- const noArbitration = hasArbitration === false;
1168
- const noCompensation = hasCompensation === false;
1169
- const riskScore = typeof data?.risk_score === "number" ? data.risk_score
1170
- : typeof safeResult?.risk_score === "number" ? safeResult.risk_score : undefined;
1171
- const riskLevel = data?.risk_level ?? safeResult?.risk_level;
1172
- const profile = getProfile();
1173
- const userMinTrust = profile.risk_appetite === "conservative" ? 70
1174
- : profile.risk_appetite === "aggressive" ? 30 : 50;
1175
- let tokenHint;
1176
- const moneyDisplay = safeResult?._money_display ??
1177
- (Array.isArray(safeResult?.objects) ? safeResult.objects[0]?._money_display : undefined);
1178
- const mdEntry = moneyDisplay ? Object.values(moneyDisplay)[0] : undefined;
1179
- if (mdEntry?.precision_known === true) {
1180
- tokenHint = { decimals: mdEntry.decimals, symbol: mdEntry.symbol };
1181
- }
1182
- else {
1183
- const typeRaw = safeResult?.type_raw ??
1184
- (Array.isArray(safeResult?.objects) ? safeResult.objects[0]?.type_raw : undefined);
1185
- tokenHint =
1186
- registryDisplayHint(extractGenericTokenType(typeRaw)) ??
1187
- registryDisplayHint(typeof data?.type_parameter === "string" ? data.type_parameter : undefined);
1188
- }
1189
- const ctx = {
1190
- stage,
1191
- service_id: serviceId,
1192
- order_id: orderId,
1193
- service_price: servicePrice,
1194
- token: tokenHint,
1195
- has_arbitration: hasArbitration,
1196
- has_compensation: hasCompensation,
1197
- has_refund_path: hasRefundPath,
1198
- has_messenger: hasMessenger,
1199
- customer_required: customerRequired,
1200
- risk_score: riskScore,
1201
- risk_level: riskLevel,
1202
- user_min_trust_score: userMinTrust,
1203
- user_require_arbitration: profile.risk_appetite === "conservative",
1204
- user_require_compensation: profile.risk_appetite === "conservative",
1205
- };
1206
- const reminders = generateReminders(ctx);
1207
- const recommendations = [];
1208
- for (const r of reminders) {
1209
- if (r.action)
1210
- recommendations.push(r.action);
1211
- }
1212
- if (noArbitration && !recommendations.some((r) => r.includes("arbitration"))) {
1213
- recommendations.push("Require the merchant to configure an Arbitration service before placing the order");
1214
- }
1215
- if (noCompensation && !recommendations.some((r) => r.includes("compensation"))) {
1216
- recommendations.push("Require the merchant to set a compensation_fund to guarantee automatic payout when the order fails");
1217
- }
1218
- const advice = {
1219
- recommendations,
1220
- reminders: reminders.map((r) => ({
1221
- id: r.id,
1222
- stage: r.stage,
1223
- priority: r.priority,
1224
- message: r.message,
1225
- action: r.action,
1226
- })),
1227
- };
1228
- if (riskScore !== undefined)
1229
- advice.risk_score = riskScore;
1230
- if (riskLevel !== undefined)
1231
- advice.risk_level = riskLevel;
1232
- return advice;
1233
- }
1234
- function buildGuardAdvice(operation_type, data, safeResult) {
1235
- try {
1236
- if (operation_type === "guard") {
1237
- return buildGuardCreateAdvice(data);
1238
- }
1239
- if (operation_type === "gen_passport") {
1240
- const status = safeResult?.error ? "fail" : "pass";
1241
- return {
1242
- current_round: "R8",
1243
- test_result: {
1244
- status: status,
1245
- passport_id: status === "pass" ? safeResult?.passport : undefined,
1246
- failure_node: status === "fail"
1247
- ? (typeof safeResult?.error === "string" ? safeResult.error.slice(0, 120) : undefined)
1248
- : undefined,
1249
- },
1250
- };
1251
- }
1252
- const errorStr = typeof safeResult?.error === "string" ? safeResult.error : "";
1253
- if (errorStr.includes("GUARD") || errorStr.includes("Guard") || errorStr.includes("guard")) {
1254
- return {
1255
- risk_warnings: [
1256
- `Guard verification failed: ${errorStr.slice(0, 200)}`,
1257
- "Suggestion: check whether the submission data matches the Guard table declaration, or query the Guard definition to learn the required submission",
1258
- ],
1259
- };
1260
- }
1261
- return undefined;
1262
- }
1263
- catch {
1264
- return undefined;
1265
- }
1266
- }
1267
- function buildGuardCreateAdvice(data) {
1268
- if (!data)
1269
- return undefined;
1270
- const puzzleInput = convertCallDataToPuzzleInput(data);
1271
- const puzzle = derivePuzzleFromCallData(puzzleInput);
1272
- const puzzleStatusBooleans = getPuzzleStatusBooleans(puzzle);
1273
- let matchedScene;
1274
- let sceneDescription;
1275
- let sceneConstraints;
1276
- if (data.binding_hint?.action) {
1277
- matchedScene = inferSceneFromAction(data.binding_hint.action);
1278
- if (matchedScene) {
1279
- sceneDescription = matchedScene.name;
1280
- sceneConstraints = matchedScene.special_constraints;
1281
- }
1282
- }
1283
- let suggestedPatterns;
1284
- const intentText = data.binding_hint?.rule_sentence
1285
- || data.binding_hint?.action
1286
- || "";
1287
- if (intentText) {
1288
- const matched = matchSemanticPattern(intentText);
1289
- if (matched.length > 0) {
1290
- suggestedPatterns = matched.map((m) => `${m.id}: ${m.pattern_name}`);
1291
- }
1292
- }
1293
- let confirmationText;
1294
- try {
1295
- const text = generateConfirmationText(puzzle);
1296
- if (!text.startsWith("[Puzzle incomplete]")) {
1297
- confirmationText = text;
1298
- }
1299
- }
1300
- catch {
1301
- }
1302
- let pendingQuestions;
1303
- const pendingQs = getPendingQuestions(puzzle);
1304
- if (pendingQs.length > 0) {
1305
- pendingQuestions = pendingQs;
1306
- }
1307
- let availableQueries;
1308
- if (matchedScene) {
1309
- const sceneObjectType = mapSceneToObjectType(matchedScene);
1310
- if (sceneObjectType) {
1311
- const filtered = GUARDQUERY
1312
- .filter((q) => q.objectType === sceneObjectType)
1313
- .slice(0, 10)
1314
- .map((q) => ({
1315
- id: q.id,
1316
- name: q.name,
1317
- objectType: String(q.objectType),
1318
- returnType: String(q.return),
1319
- description: q.description,
1320
- }));
1321
- if (filtered.length > 0) {
1322
- availableQueries = filtered;
1323
- }
1324
- }
1325
- }
1326
- const assessment = assessGuardRisksForOperation("guard", data);
1327
- let riskAssessment;
1328
- let riskWarnings;
1329
- if (assessment) {
1330
- const summary = getRiskSummary(assessment);
1331
- riskAssessment = {
1332
- overall_risk: summary.risk_count > 0 ? assessment.overall_risk : "info",
1333
- risk_count: summary.risk_count,
1334
- critical_count: summary.critical_count,
1335
- high_count: summary.high_count,
1336
- needs_human_review: summary.needs_human_review,
1337
- top_risks: summary.top_risks,
1338
- stakeholder_advice: assessment.stakeholder_advice,
1339
- };
1340
- const warnings = assessment.risks.map((r) => `[${r.level.toUpperCase()}] ${r.title}: ${r.description}`);
1341
- if (warnings.length > 0) {
1342
- riskWarnings = warnings;
1343
- }
1344
- }
1345
- const advice = {
1346
- current_round: "R7",
1347
- puzzle_status: puzzleStatusBooleans,
1348
- };
1349
- if (matchedScene)
1350
- advice.matched_scene = matchedScene.id;
1351
- if (sceneDescription)
1352
- advice.scene_description = sceneDescription;
1353
- if (sceneConstraints)
1354
- advice.scene_constraints = sceneConstraints;
1355
- if (suggestedPatterns)
1356
- advice.suggested_patterns = suggestedPatterns;
1357
- if (availableQueries)
1358
- advice.available_queries = availableQueries;
1359
- if (riskWarnings)
1360
- advice.risk_warnings = riskWarnings;
1361
- if (pendingQuestions)
1362
- advice.pending_questions = pendingQuestions;
1363
- if (confirmationText)
1364
- advice.confirmation_text = confirmationText;
1365
- if (riskAssessment)
1366
- advice.risk_assessment = riskAssessment;
1367
- return advice;
1368
- }
1369
- function convertCallDataToPuzzleInput(data) {
1370
- const result = {};
1371
- if (Array.isArray(data.table)) {
1372
- result.table = data.table.map((item) => ({
1373
- identifier: item.identifier,
1374
- b_submission: item.b_submission,
1375
- value_type: typeof item.value_type === "string" ? item.value_type : String(item.value_type),
1376
- value: convertValueSnapshot(item.value),
1377
- name: item.name ?? "",
1378
- object_type: item.object_type,
1379
- }));
1380
- }
1381
- if (data.root && typeof data.root === "object") {
1382
- const rootObj = data.root;
1383
- if (rootObj.type !== "file" && rootObj.type !== "node") {
1384
- result.root = convertNodeToSnapshot(data.root);
1385
- }
1386
- else if (rootObj.type === "node" && data.root.node) {
1387
- result.root = convertNodeToSnapshot(data.root.node);
1388
- }
1389
- }
1390
- if (data.rely && Array.isArray(data.rely.guards)) {
1391
- result.rely = {
1392
- guards: data.rely.guards.map((g) => typeof g === "string" ? g : String(g)),
1393
- logic_or: data.rely.logic_or,
1394
- };
1395
- }
1396
- if (data.binding_hint) {
1397
- const bh = data.binding_hint;
1398
- const bindingHint = {
1399
- action: bh.action,
1400
- host_object: bh.host_object,
1401
- binding_field: bh.binding_field,
1402
- };
1403
- if (bh.rule_sentence !== undefined)
1404
- bindingHint.rule_sentence = bh.rule_sentence;
1405
- if (bh.failure_conditions !== undefined)
1406
- bindingHint.failure_conditions = bh.failure_conditions;
1407
- if (bh.circular_reference !== undefined)
1408
- bindingHint.circular_reference = bh.circular_reference;
1409
- result.binding_hint = bindingHint;
1410
- }
1411
- return result;
1412
- }
1413
- function convertNodeToSnapshot(node) {
1414
- if (!node || typeof node !== "object") {
1415
- return { type: "unknown" };
1416
- }
1417
- const snapshot = {
1418
- type: String(node.type ?? "unknown"),
1419
- };
1420
- if (typeof node.identifier === "number") {
1421
- snapshot.identifier = node.identifier;
1422
- }
1423
- if (node.query !== undefined) {
1424
- snapshot.query = typeof node.query === "number" ? node.query : String(node.query);
1425
- }
1426
- if (node.object && typeof node.object === "object") {
1427
- const obj = {
1428
- identifier: Number(node.object.identifier),
1429
- };
1430
- if (typeof node.object.convert_witness === "number") {
1431
- obj.convert_witness = node.object.convert_witness;
1432
- }
1433
- snapshot.object = obj;
1434
- }
1435
- if (Array.isArray(node.parameters)) {
1436
- snapshot.parameters = node.parameters.map((p) => convertNodeToSnapshot(p));
1437
- }
1438
- if (typeof node.context === "string") {
1439
- const ctxValue = node.context;
1440
- if (ctxValue === "Clock" || ctxValue === "Guard" || ctxValue === "Signer") {
1441
- snapshot.context = ctxValue;
1442
- }
1443
- }
1444
- if (Array.isArray(node.nodes)) {
1445
- snapshot.nodes = node.nodes.map((n) => convertNodeToSnapshot(n));
1446
- }
1447
- if (node.node) {
1448
- snapshot.node = convertNodeToSnapshot(node.node);
1449
- }
1450
- if (node.nodeLeft) {
1451
- snapshot.nodeLeft = convertNodeToSnapshot(node.nodeLeft);
1452
- }
1453
- if (node.nodeRight) {
1454
- snapshot.nodeRight = convertNodeToSnapshot(node.nodeRight);
1455
- }
1456
- return snapshot;
1457
- }
1458
- function convertValueSnapshot(value) {
1459
- if (value === undefined || value === null)
1460
- return undefined;
1461
- if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
1462
- return value;
1463
- }
1464
- if (Array.isArray(value)) {
1465
- const allString = value.every((v) => typeof v === "string");
1466
- if (allString)
1467
- return value;
1468
- const allNumber = value.every((v) => typeof v === "number");
1469
- if (allNumber)
1470
- return value;
1471
- const allBool = value.every((v) => typeof v === "boolean");
1472
- if (allBool)
1473
- return value;
1474
- return JSON.stringify(value);
1475
- }
1476
- return JSON.stringify(value);
1477
- }
1478
- function mapSceneToObjectType(scene) {
1479
- const hostObject = scene.host_object;
1480
- if (hostObject === "Standalone")
1481
- return undefined;
1482
- return hostObject;
1483
- }
1484
- export function buildSemantic(safeResult, context) {
1485
- if (!context)
1486
- return undefined;
1487
- const intent = inferIntent(context.operation_type, context.data);
1488
- const status = inferStatus(safeResult);
1489
- const objectChanges = safeResult?.objectChanges || [];
1490
- const balanceChanges = safeResult?.balanceChanges || [];
1491
- const events = safeResult?.events || [];
1492
- const created = tagObjectRoles(objectChanges.filter((c) => c?.type === "created"));
1493
- const modified = tagObjectRoles(objectChanges.filter((c) => c?.type === "mutated" || c?.type === "published"));
1494
- const released = tagFundRoles(balanceChanges, context.operation_type, context.data, events);
1495
- const annotatedEvents = annotateEvents(events);
1496
- const next_actions = inferNextActions(context.operation_type, context.data, status);
1497
- const warnings = inferWarnings(context.operation_type, context.data, safeResult);
1498
- if (context.pre_warnings && context.pre_warnings.length > 0) {
1499
- warnings.push(...context.pre_warnings);
1500
- }
1501
- if (context.operation_type === "service" && context.data?.publish === true) {
1502
- const findings = auditService(context.data);
1503
- for (const f of findings) {
1504
- const prefix = f.severity === "error" ? "[AUDIT ERROR] " : f.severity === "warning" ? "[AUDIT] " : "[INFO] ";
1505
- warnings.push(prefix + f.message);
1506
- }
1507
- }
1508
- let experience;
1509
- const experienceLayerEnabled = isRuntimeEnabled("experience_layer");
1510
- if (experienceLayerEnabled) {
1511
- try {
1512
- const feedback = getExperienceFeedback(context.operation_type, context.data, intent);
1513
- if (feedback) {
1514
- experience = feedback;
1515
- }
1516
- const outcome = status === "success" ? "success" : status === "failed" ? "failed" : "partial";
1517
- const referencedObjects = [...created, ...modified].map((o) => o.id).filter(Boolean);
1518
- const errCode = inferErrorCodeForSignal(safeResult);
1519
- recordOperationOutcome(context.operation_type, context.data, intent, outcome, errCode, referencedObjects);
1520
- }
1521
- catch {
1522
- }
1523
- }
1524
- let evolution_context;
1525
- if (isRuntimeEnabled("industry_evolution")) {
1526
- try {
1527
- const industryHint = (typeof context.data?.industry === "string" && context.data.industry.trim())
1528
- ? context.data.industry.trim()
1529
- : undefined;
1530
- if (industryHint && !experienceLayerEnabled) {
1531
- const outcome = status === "success"
1532
- ? { success: true }
1533
- : { success: false, error_code: inferErrorCodeForSignal(safeResult) };
1534
- recordIndustrySignal(industryHint, { type: context.operation_type, data: context.data }, outcome);
1535
- }
1536
- if (industryHint) {
1537
- const evoCtx = injectEvolutionContext(undefined, industryHint, deriveAdviceRole(context.operation_type, context.data));
1538
- if (evoCtx && (evoCtx.industry_signal || evoCtx.evolution_advice || evoCtx.confidence > 0)) {
1539
- evolution_context = evoCtx;
1540
- }
1541
- }
1542
- }
1543
- catch {
1544
- }
1545
- }
1546
- let service_status;
1547
- if (isRuntimeEnabled("semantic_rich")) {
1548
- try {
1549
- const all = listServices();
1550
- const active = all.filter((s) => s.enabled).map((s) => s.name);
1551
- const inactive = all.filter((s) => !s.enabled).map((s) => s.name);
1552
- service_status = {
1553
- active,
1554
- inactive: inactive.length ? inactive : undefined,
1555
- };
1556
- }
1557
- catch {
1558
- }
1559
- }
1560
- let customer_advice;
1561
- try {
1562
- customer_advice = buildCustomerAdvice(context.operation_type, context.data, safeResult);
1563
- }
1564
- catch {
1565
- }
1566
- let guard_advice;
1567
- try {
1568
- guard_advice = buildGuardAdvice(context.operation_type, context.data, safeResult);
1569
- }
1570
- catch {
1571
- }
1572
- return {
1573
- intent,
1574
- status,
1575
- summary: composeSummary(intent, status, created, modified, released),
1576
- created: created.length ? created : undefined,
1577
- modified: modified.length ? modified : undefined,
1578
- released: released.length ? released : undefined,
1579
- events: annotatedEvents.length ? annotatedEvents : undefined,
1580
- next_actions: next_actions.length ? next_actions : undefined,
1581
- warnings: warnings.length ? warnings : undefined,
1582
- experience,
1583
- service_status,
1584
- customer_advice,
1585
- evolution_context,
1586
- guard_advice,
1587
- };
1588
- }
1589
- function inferErrorCodeForSignal(safeResult) {
1590
- if (!safeResult)
1591
- return undefined;
1592
- if (typeof safeResult.error === "string")
1593
- return safeResult.error.slice(0, 64);
1594
- return undefined;
1595
- }
1596
- export function buildDataSemantic(data, context, isError, errorMsg) {
1597
- if (!context)
1598
- return undefined;
1599
- const intent = inferIntent(context.operation_type, context.data);
1600
- const warnings = [];
1601
- if (context.pre_warnings && context.pre_warnings.length > 0) {
1602
- warnings.push(...context.pre_warnings);
1603
- }
1604
- let status;
1605
- if (isError) {
1606
- status = "failed";
1607
- }
1608
- else {
1609
- status = "success";
1610
- if (Array.isArray(data) && data.length === 0) {
1611
- status = "partial";
1612
- warnings.push("no results found");
1613
- }
1614
- else if (data === null || data === undefined) {
1615
- status = "partial";
1616
- warnings.push("no results found");
1617
- }
1618
- else if (typeof data === "object" && !Array.isArray(data)) {
1619
- const values = Object.values(data);
1620
- if (values.length > 0 && values.every((v) => (Array.isArray(v) ? v.length === 0 : v === null || v === undefined))) {
1621
- status = "partial";
1622
- warnings.push("no results found");
1623
- }
1624
- }
1625
- }
1626
- const next_actions = inferNextActions(context.operation_type, context.data, status);
1627
- let annotatedEvents;
1628
- if (!isError && context.operation_type === "onchain_events") {
1629
- const eventsArray = Array.isArray(data) ? data : (data?.data && Array.isArray(data.data) ? data.data : null);
1630
- if (eventsArray) {
1631
- annotatedEvents = annotateEvents(eventsArray);
1632
- if (annotatedEvents.length === 0)
1633
- annotatedEvents = undefined;
1634
- }
1635
- }
1636
- const intentVerb = intent.replace(/_/g, " ");
1637
- let summary;
1638
- if (status === "failed") {
1639
- summary = errorMsg ? `Failed to ${intentVerb}: ${errorMsg}` : `Failed to ${intentVerb}`;
1640
- }
1641
- else if (status === "partial") {
1642
- summary = `${intentVerb} completed with no results`;
1643
- }
1644
- else {
1645
- summary = `Successfully ${intentVerb}`;
1646
- }
1647
- let service_status;
1648
- if (isRuntimeEnabled("semantic_rich")) {
1649
- try {
1650
- const all = listServices();
1651
- const active = all.filter((s) => s.enabled).map((s) => s.name);
1652
- const inactive = all.filter((s) => !s.enabled).map((s) => s.name);
1653
- service_status = {
1654
- active,
1655
- inactive: inactive.length ? inactive : undefined,
1656
- };
1657
- }
1658
- catch {
1659
- }
1660
- }
1661
- let customer_advice;
1662
- if (!isError) {
1663
- try {
1664
- customer_advice = buildCustomerAdvice(context.operation_type, context.data, data);
1665
- }
1666
- catch {
1667
- }
1668
- }
1669
- return {
1670
- intent,
1671
- status,
1672
- summary,
1673
- events: annotatedEvents,
1674
- next_actions: next_actions.length ? next_actions : undefined,
1675
- warnings: warnings.length ? warnings : undefined,
1676
- service_status,
1677
- customer_advice,
1678
- };
1679
- }
1
+ import{auditService}from'../../knowledge/index.js';import{getExperienceFeedback,recordOperationOutcome}from'../../experience/index.js';import{isEnabled as a316a,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':'proof','intent':'create_proof','confidence':0.9},{'operation_type':'gen_proof','intent':'generate_proof','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':'ArbCase','arbitration':'Arbitration','messenger':'Messenger','contact':'Contact','demand':'Demand','reward':'Reward','personal':'Personal','repository':'Repository','treasury':'Treasury','discount':'Discount','allocation':'Allocation','payment':'Payment','passport':'Passport','proof':'Proof'};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.\x20SPECIAL\x20CASE:\x20publish\x20automatically\x20sets\x20bPaused=false\x20—\x20NO\x20separate\x20unpause\x20call\x20is\x20needed\x20after\x20publish.'},{'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(!a316a('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=a316a('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(a316a('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(a316a('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(a316a('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};}