@wowok/agent-mcp 3.2.0 → 3.2.1

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 (164) hide show
  1. package/dist/config/exposure.d.ts +8 -8
  2. package/dist/config/judgment.d.ts +20 -20
  3. package/dist/config/rule-engine.d.ts +20 -20
  4. package/dist/extensions/industry-pack.js +1 -1
  5. package/dist/graph/onchain/facts.js +1 -1
  6. package/dist/graph/onchain/sdk-batch.d.ts +1 -0
  7. package/dist/graph/onchain/sdk-batch.js +1 -1
  8. package/dist/graph/onchain/sdk-dataplane.d.ts +1 -0
  9. package/dist/graph/onchain/sdk-dataplane.js +1 -1
  10. package/dist/knowledge/allocation-templates.d.ts +1 -1
  11. package/dist/knowledge/allocation-templates.js +1 -1
  12. package/dist/knowledge/arbitration-ledger.js +1 -1
  13. package/dist/knowledge/audit-rules.d.ts +1 -1
  14. package/dist/knowledge/audit-rules.js +1 -1
  15. package/dist/knowledge/builtin-templates.d.ts +1 -1
  16. package/dist/knowledge/builtin-templates.js +1 -1
  17. package/dist/knowledge/discount-threshold.d.ts +15 -0
  18. package/dist/knowledge/discount-threshold.js +1 -0
  19. package/dist/knowledge/getting-started.js +1 -1
  20. package/dist/knowledge/guard-design-patterns.js +1 -1
  21. package/dist/knowledge/guard-lint.js +1 -1
  22. package/dist/knowledge/guard-translation.js +1 -1
  23. package/dist/knowledge/index.d.ts +2 -2
  24. package/dist/knowledge/index.js +1 -1
  25. package/dist/knowledge/industry-generalizer.d.ts +38 -1
  26. package/dist/knowledge/industry-generalizer.js +1 -1
  27. package/dist/knowledge/industry-registry.js +1 -1
  28. package/dist/knowledge/industry-strategy.js +1 -1
  29. package/dist/knowledge/jsonrpc-enum.js +1 -1
  30. package/dist/knowledge/onchain-constants.d.ts +2 -2
  31. package/dist/knowledge/onchain-constants.js +1 -1
  32. package/dist/knowledge/scenario-modes.d.ts +10 -0
  33. package/dist/knowledge/strategy-manuals.d.ts +1 -1
  34. package/dist/knowledge/strategy-manuals.js +1 -1
  35. package/dist/knowledge/template-loader.d.ts +20 -0
  36. package/dist/knowledge/template-loader.js +1 -1
  37. package/dist/knowledge/template-registry.js +1 -1
  38. package/dist/knowledge/template-scanner.js +1 -1
  39. package/dist/knowledge/tools-reference.js +1 -1
  40. package/dist/monitor/MonitorLoop.js +1 -1
  41. package/dist/participation/arbitrator-interest.js +1 -1
  42. package/dist/participation/customer-interest.js +1 -1
  43. package/dist/participation/merchant-interest.js +1 -1
  44. package/dist/playbooks/service-build/business-puzzle.js +1 -1
  45. package/dist/playbooks/service-build/machine-panorama.js +1 -1
  46. package/dist/playbooks/service-build/merchant-guide.js +1 -1
  47. package/dist/playbooks/service-build/mode-actions.d.ts +12 -1
  48. package/dist/playbooks/service-build/mode-actions.js +1 -1
  49. package/dist/playbooks/service-build/object-panorama.js +1 -1
  50. package/dist/playbooks/service-build/participation-radar.js +1 -1
  51. package/dist/playbooks/service-build/relationship-profile.js +1 -1
  52. package/dist/playbooks/service-build/reverse-mapping-refund-p0-5.spec.d.ts +1 -0
  53. package/dist/playbooks/service-build/reverse-mapping-refund-p0-5.spec.js +1 -0
  54. package/dist/playbooks/service-build/reverse-mapping.js +1 -1
  55. package/dist/playbooks/service-build/semantic-graph.js +1 -1
  56. package/dist/playbooks/service-build/service-panorama.js +1 -1
  57. package/dist/playbooks/service-build/service-quote.js +1 -1
  58. package/dist/review/index.js +1 -1
  59. package/dist/role/profiles.js +1 -1
  60. package/dist/role/types.d.ts +2 -0
  61. package/dist/role/types.js +1 -1
  62. package/dist/safety/confirm-gate.js +1 -1
  63. package/dist/schema/call/allocation.d.ts +7 -7
  64. package/dist/schema/call/arbitration.d.ts +1 -1
  65. package/dist/schema/call/arbitration.js +1 -1
  66. package/dist/schema/call/base.d.ts +5 -5
  67. package/dist/schema/call/base.js +1 -1
  68. package/dist/schema/call/bridge.d.ts +5 -9
  69. package/dist/schema/call/bridge.js +1 -1
  70. package/dist/schema/call/contact.d.ts +1 -1
  71. package/dist/schema/call/demand.d.ts +1 -1
  72. package/dist/schema/call/guard.d.ts +11 -11
  73. package/dist/schema/call/handler.js +1 -1
  74. package/dist/schema/call/machine.d.ts +2 -2
  75. package/dist/schema/call/order.d.ts +1 -1
  76. package/dist/schema/call/payment.d.ts +1 -1
  77. package/dist/schema/call/permission.d.ts +1 -1
  78. package/dist/schema/call/personal.d.ts +1 -1
  79. package/dist/schema/call/progress.d.ts +1 -1
  80. package/dist/schema/call/proof.d.ts +2 -2
  81. package/dist/schema/call/repository.d.ts +1 -1
  82. package/dist/schema/call/reward.d.ts +1 -1
  83. package/dist/schema/call/semantic.js +1 -1
  84. package/dist/schema/call/service.d.ts +5 -5
  85. package/dist/schema/call/service.js +1 -1
  86. package/dist/schema/call/treasury.d.ts +1 -1
  87. package/dist/schema/common/index.js +1 -1
  88. package/dist/schema/evaluation/index.d.ts +6 -2
  89. package/dist/schema/evaluation/index.js +1 -1
  90. package/dist/schema/goal/index.d.ts +8 -8
  91. package/dist/schema/goal/planning.d.ts +15 -15
  92. package/dist/schema/industry-pack/index.d.ts +15 -0
  93. package/dist/schema/industry-pack/modes.d.ts +15 -0
  94. package/dist/schema/industry-pack/modes.js +1 -1
  95. package/dist/schema/intent-radar/index.d.ts +3 -0
  96. package/dist/schema/intent-radar/index.js +1 -1
  97. package/dist/schema/local/index.d.ts +577 -18
  98. package/dist/schema/local/index.js +1 -1
  99. package/dist/schema/messenger/index.d.ts +140 -20
  100. package/dist/schema/messenger/index.js +1 -1
  101. package/dist/schema/operations.d.ts +30 -28
  102. package/dist/schema/operations.js +1 -1
  103. package/dist/schema/persona/index.d.ts +708 -708
  104. package/dist/schema/persona/index.js +1 -1
  105. package/dist/schema/query/bi.d.ts +20 -6
  106. package/dist/schema/query/bi.js +1 -1
  107. package/dist/schema/query/index.d.ts +32 -32
  108. package/dist/schema/query/index.js +1 -1
  109. package/dist/schema/schema-query/index.d.ts +3 -3
  110. package/dist/schema/schema-version.js +1 -1
  111. package/dist/schema/watch/index.d.ts +2 -2
  112. package/dist/schema/workflow/index.d.ts +2 -2
  113. package/dist/schema-query-impl/index.js +1 -1
  114. package/dist/schemas/account_operation.output.json +6 -2
  115. package/dist/schemas/account_operation.schema.json +1 -1
  116. package/dist/schemas/bridge_operation.schema.json +2 -10
  117. package/dist/schemas/evaluation_operation.output.json +2 -0
  118. package/dist/schemas/evaluation_operation.schema.json +2 -0
  119. package/dist/schemas/index.json +7 -1
  120. package/dist/schemas/industry_pack_operation.output.json +87 -4
  121. package/dist/schemas/intent_radar.output.json +2 -0
  122. package/dist/schemas/intent_radar.schema.json +1 -0
  123. package/dist/schemas/local_cache_operation.output.json +1536 -0
  124. package/dist/schemas/local_cache_operation.schema.json +101 -0
  125. package/dist/schemas/local_mark_operation.output.json +51 -36
  126. package/dist/schemas/local_mark_operation.schema.json +1 -0
  127. package/dist/schemas/messenger_operation.schema.json +358 -35
  128. package/dist/schemas/onchain_operations.schema.json +10 -10
  129. package/dist/schemas/onchain_operations_allocation.schema.json +1 -1
  130. package/dist/schemas/onchain_operations_arbitration.schema.json +3 -3
  131. package/dist/schemas/onchain_operations_payment.schema.json +1 -1
  132. package/dist/schemas/onchain_operations_reward.schema.json +1 -1
  133. package/dist/schemas/onchain_operations_service.schema.json +3 -3
  134. package/dist/schemas/onchain_operations_treasury.schema.json +1 -1
  135. package/dist/schemas/onchain_table_data.output.json +11 -0
  136. package/dist/schemas/query_toolkit.output.json +11 -4
  137. package/dist/schemas/query_toolkit.schema.json +13 -2
  138. package/dist/tools/handlers/benchmark-migration.js +1 -1
  139. package/dist/tools/handlers/bridge.js +1 -1
  140. package/dist/tools/handlers/config.js +1 -1
  141. package/dist/tools/handlers/local.d.ts +1 -0
  142. package/dist/tools/handlers/local.js +1 -1
  143. package/dist/tools/handlers/messenger.d.ts +9 -2
  144. package/dist/tools/handlers/messenger.js +1 -1
  145. package/dist/tools/handlers/name-resolution.d.ts +4 -0
  146. package/dist/tools/handlers/name-resolution.js +1 -0
  147. package/dist/tools/handlers/name-resolution.spec.d.ts +1 -0
  148. package/dist/tools/handlers/name-resolution.spec.js +1 -0
  149. package/dist/tools/handlers/onchain-name-registration.d.ts +37 -0
  150. package/dist/tools/handlers/onchain-name-registration.js +1 -0
  151. package/dist/tools/handlers/onchain-name-registration.spec.d.ts +1 -0
  152. package/dist/tools/handlers/onchain-name-registration.spec.js +1 -0
  153. package/dist/tools/handlers/onchain.d.ts +1 -0
  154. package/dist/tools/handlers/onchain.js +1 -1
  155. package/dist/tools/handlers/query.d.ts +1 -0
  156. package/dist/tools/handlers/query.js +1 -1
  157. package/dist/tools/index.js +1 -1
  158. package/dist/tools/registry/local.js +1 -1
  159. package/dist/tools/sanitize-description-roundtrip.spec.d.ts +1 -0
  160. package/dist/tools/sanitize-description-roundtrip.spec.js +1 -0
  161. package/dist/tools/sanitize-output.d.ts +1 -0
  162. package/dist/tools/sanitize-output.js +1 -1
  163. package/dist/tools/wrap.js +1 -1
  164. package/package.json +2 -2
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "type_parameter": {
40
40
  "default": "0x2::wow::WOW",
41
- "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. '0x2::wow::WOW' (WOW, the default), '0x...::usdt::USDT' (USDT), '0x...::eth::ETH' (ETH). Defines which token this object accepts for payments. To discover all available tokens and their type tags, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here.",
41
+ "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. ALWAYS the FULL type string `{address}::{module}::{struct}` e.g. '0x2::wow::WOW'. ⚠️ The bare names 'WOW' / 'USDT' / 'ETH' are REJECTED (the validator requires all three parts) — write '0x2::wow::WOW', not 'WOW'. The field may be OMITTED entirely: it then defaults to WOW ('0x2::wow::WOW'). This token is what the object accepts for payments and is fixed at creation. To discover other available tokens, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here. NOTE: testnet/localnet carry WOW only — USDT/ETH are a mainnet capability.",
42
42
  "type": "string"
43
43
  }
44
44
  },
@@ -81,7 +81,7 @@
81
81
  },
82
82
  "type_parameter": {
83
83
  "default": "0x2::wow::WOW",
84
- "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. '0x2::wow::WOW' (WOW, the default), '0x...::usdt::USDT' (USDT), '0x...::eth::ETH' (ETH). Defines which token this object accepts for payments. To discover all available tokens and their type tags, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here.",
84
+ "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. ALWAYS the FULL type string `{address}::{module}::{struct}` e.g. '0x2::wow::WOW'. ⚠️ The bare names 'WOW' / 'USDT' / 'ETH' are REJECTED (the validator requires all three parts) — write '0x2::wow::WOW', not 'WOW'. The field may be OMITTED entirely: it then defaults to WOW ('0x2::wow::WOW'). This token is what the object accepts for payments and is fixed at creation. To discover other available tokens, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here. NOTE: testnet/localnet carry WOW only — USDT/ETH are a mainnet capability.",
85
85
  "type": "string"
86
86
  }
87
87
  },
@@ -218,8 +218,8 @@
218
218
  "description": "Arb CASE object — the single dispute case created by `dispute` (the object you may have named via `namedArb`). NOT the arbitrator registration object: that one goes in the ROOT `object` field, while every case-scoped operation (confirm / voting_deadline_change / vote / feedback / arbitration / reset / arb_withdraw) addresses the case through THIS field. Accepts the Arb's 0x address or its LocalMark name."
219
219
  },
220
220
  "voting_deadline": {
221
- "default": 0,
222
- "description": "Voting deadline as Unix timestamp in MILLISECONDS (ms). SEMANTICS OF SPECIAL VALUES: 0 (DEFAULT when omitted) = deadline already passed → voting is IMPOSSIBLE and the arbitrator may deliver the verdict immediately (direct-verdict flow); null = open-ended voting with no deadline (verdict allowed anytime); a future timestamp = normal voting window (recommended: now + at least 86400000 ms = 24 hours). COMMON MISTAKE: using seconds instead of milliseconds (multiply by 1000). Example: Date.now() + 259200000 for 3 days from now.",
221
+ "default": null,
222
+ "description": "Voting deadline as Unix timestamp in MILLISECONDS (ms). SEMANTICS OF SPECIAL VALUES: null (DEFAULT when omitted) = open-ended voting, no deadline; parties may vote at any time and the arbitrator may deliver the verdict immediately (arb.move skips the deadline assert when the Option is none) — this is the SAFE default; a future timestamp = normal bounded voting window (recommended: now + at least 86400000 ms = 24 hours); 0 = deadline already passed → voting is IMPOSSIBLE (every vote aborts E_VOTING_DEADLINE_PASSED) and only a direct verdict is possible. Only pass 0 deliberately when you truly want a no-vote verdict. COMMON MISTAKE: using seconds instead of milliseconds (multiply by 1000). Example: Date.now() + 259200000 for 3 days from now.",
223
223
  "anyOf": [
224
224
  {
225
225
  "type": "integer",
@@ -38,7 +38,7 @@
38
38
  },
39
39
  "type_parameter": {
40
40
  "default": "0x2::wow::WOW",
41
- "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. '0x2::wow::WOW' (WOW, the default), '0x...::usdt::USDT' (USDT), '0x...::eth::ETH' (ETH). Defines which token this object accepts for payments. To discover all available tokens and their type tags, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here.",
41
+ "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. ALWAYS the FULL type string `{address}::{module}::{struct}` e.g. '0x2::wow::WOW'. ⚠️ The bare names 'WOW' / 'USDT' / 'ETH' are REJECTED (the validator requires all three parts) — write '0x2::wow::WOW', not 'WOW'. The field may be OMITTED entirely: it then defaults to WOW ('0x2::wow::WOW'). This token is what the object accepts for payments and is fixed at creation. To discover other available tokens, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here. NOTE: testnet/localnet carry WOW only — USDT/ETH are a mainnet capability.",
42
42
  "type": "string"
43
43
  }
44
44
  },
@@ -81,7 +81,7 @@
81
81
  },
82
82
  "type_parameter": {
83
83
  "default": "0x2::wow::WOW",
84
- "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. '0x2::wow::WOW' (WOW, the default), '0x...::usdt::USDT' (USDT), '0x...::eth::ETH' (ETH). Defines which token this object accepts for payments. To discover all available tokens and their type tags, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here.",
84
+ "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. ALWAYS the FULL type string `{address}::{module}::{struct}` e.g. '0x2::wow::WOW'. ⚠️ The bare names 'WOW' / 'USDT' / 'ETH' are REJECTED (the validator requires all three parts) — write '0x2::wow::WOW', not 'WOW'. The field may be OMITTED entirely: it then defaults to WOW ('0x2::wow::WOW'). This token is what the object accepts for payments and is fixed at creation. To discover other available tokens, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here. NOTE: testnet/localnet carry WOW only — USDT/ETH are a mainnet capability.",
85
85
  "type": "string"
86
86
  }
87
87
  },
@@ -81,7 +81,7 @@
81
81
  },
82
82
  "type_parameter": {
83
83
  "default": "0x2::wow::WOW",
84
- "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. '0x2::wow::WOW' (WOW, the default), '0x...::usdt::USDT' (USDT), '0x...::eth::ETH' (ETH). Defines which token this object accepts for payments. To discover all available tokens and their type tags, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here.",
84
+ "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. ALWAYS the FULL type string `{address}::{module}::{struct}` e.g. '0x2::wow::WOW'. ⚠️ The bare names 'WOW' / 'USDT' / 'ETH' are REJECTED (the validator requires all three parts) — write '0x2::wow::WOW', not 'WOW'. The field may be OMITTED entirely: it then defaults to WOW ('0x2::wow::WOW'). This token is what the object accepts for payments and is fixed at creation. To discover other available tokens, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here. NOTE: testnet/localnet carry WOW only — USDT/ETH are a mainnet capability.",
85
85
  "type": "string"
86
86
  }
87
87
  },
@@ -923,7 +923,7 @@
923
923
  "description": "Discount magnitude, meaning depends on discount_type. RATES (0): per-10000 off rate — 10 = 0.1% off, 1000 = 10% off, 10000 = 100% off; values above 10000 are rejected. FIXED (1): fixed deduction from the order total in the Service token's smallest units (e.g. 1000000000 = 1 WOW at 9 decimals)."
924
924
  },
925
925
  "benchmark": {
926
- "description": "Minimum order total (in the Service token's smallest units) for the discount to apply — the discount is applied only when the order total is GREATER THAN OR EQUAL TO this value. ⚠️ OMITTING this field means the discount NEVER applies: the coupon object is still consumed (destroyed) when used, but the order total is unchanged. To make a discount that always applies, pass 0. If the order total is below the discounted price the payment aborts — pay the list price; the excess is returned as a new Coin.",
926
+ "description": "Minimum order total (in the Service token's smallest units) for the discount to apply — when set, the discount is applied only if the PRE-discount order total is GREATER THAN OR EQUAL TO this value. ✅ OMITTING this field (or passing null, or 0) means NO threshold — the discount applies UNCONDITIONALLY, and that is the common, correct case. This is the on-chain behaviour: benchmark_met = if (option::is_some(&discount.benchmark)) { total >= benchmark } else { true } (wow-framework sources/w/service.move:274-278, inside the discount-application step). ⚠️ SHARP EDGE when you DO set a threshold: a below-threshold order is NOT rejected — it completes at FULL price and the one-time coupon is still consumed and destroyed, so the buyer pays full price AND loses the coupon. Keep thresholds low enough that your typical basket clears them. If the order total is below the discounted price the payment aborts — pay the list price; the excess is returned as a new Coin.",
927
927
  "anyOf": [
928
928
  {
929
929
  "type": "number"
@@ -1012,7 +1012,7 @@
1012
1012
  }
1013
1013
  },
1014
1014
  "order_allocators": {
1015
- "description": "Order fund allocator. Max 100 allocators (MAX_ALLOCATOR_COUNT). Each allocator has a guard (first matching guard wins) and a sharing list. Set to null to clear. ⚠️ PERMANENTLY IMMUTABLE after publish: order_allocators can ONLY be set BEFORE publish=true (on-chain check rejects after publish — E_ALREADY_PUBLISHED). After publish, the ONLY way to change allocation rules is to create a NEW Service object. There is NO pause+lock exception for order_allocators (unlike arbitrations/rewards which have time-lock removal). PRE-PUBLISH CHECKLIST: verify all guard names resolve, all sharing amounts are correct, threshold is set, and recipient types (Entity/Signer/GuardIdentifier) are intended before calling publish=true. GuardIdentifier sharing mode: {who: {GuardIdentifier: <u8>}, sharing: <rate>, mode: 'Rate'} — resolves recipient from the Guard table submission at allocation time. BINDING SEMANTICS (contract-enforced, abort code 15): in a Service-created Allocation EVERY GuardIdentifier submission must equal the PAYING order — it is always 'the order', never a third party whose address is supplied at trigger time; use {who:{Entity:...}} for named parties. Canonical order pattern: the recipient slot is the single submitted Order (constrained by the Guard — service binding, qualifying node, signer==order.owner); funds land at that order object and are receivable only by its owner (object receipt = owner receipt). Safety is determined by constraint sufficiency — run the recipient constraint audit before publish. Fixed recipients should use {who:{Entity:...}}; unbound Signer recipients are a CRITICAL theft risk. MULTI-CALL ALLOCATION: an allocation can be executed MULTIPLE times (no consumed flag in contract). Use Amount mode (not Surplus) for recurring allocations — Surplus calls balance::withdraw_all which drains the balance. For monthly payment scenarios, create multiple Allocators with time-based Guards + Amount mode sharing items.",
1015
+ "description": "Order fund allocator. Max 100 allocators (MAX_ALLOCATOR_COUNT). ✅ EACH allocator has a guard, and EVERY allocator whose guard address matches the supplied guard RUNS — they are NOT mutually exclusive and NOT first-match-wins. One guard may legitimately authorize several distribution rules (different fix / rate / cap); each contributes its own Payment and consumes its own once-slot (keyed by the allocator index). Allocators are evaluated in vector order against the SHRINKING pool, so a later allocator only sees the balance left by the earlier ones — which is exactly how a waterfall (e.g. Amount fee + net Rate split) is built. On-chain truth: wow::allocation (allocation.move:291-296, `while` loop over all allocators, `if (guard address == alloc.guard)`). ⚠️ If you WANT mutual exclusion you must express it inside the Guard itself (make the conditions logically exclusive). Set to null to clear. ⚠️ PERMANENTLY IMMUTABLE after publish: order_allocators can ONLY be set BEFORE publish=true (on-chain check rejects after publish — E_ALREADY_PUBLISHED). After publish, the ONLY way to change allocation rules is to create a NEW Service object. There is NO pause+lock exception for order_allocators (unlike arbitrations/rewards which have time-lock removal). PRE-PUBLISH CHECKLIST: verify all guard names resolve, all sharing amounts are correct, threshold is set, and recipient types (Entity/Signer/GuardIdentifier) are intended before calling publish=true. GuardIdentifier sharing mode: {who: {GuardIdentifier: <u8>}, sharing: <rate>, mode: 'Rate'} — resolves recipient from the Guard table submission at allocation time. BINDING SEMANTICS (contract-enforced, abort code 15): in a Service-created Allocation EVERY GuardIdentifier submission must equal the PAYING order — it is always 'the order', never a third party whose address is supplied at trigger time; use {who:{Entity:...}} for named parties. Canonical order pattern: the recipient slot is the single submitted Order (constrained by the Guard — service binding, qualifying node, signer==order.owner); funds land at that order object and are receivable only by its owner (object receipt = owner receipt). Safety is determined by constraint sufficiency — run the recipient constraint audit before publish. Fixed recipients should use {who:{Entity:...}}; unbound Signer recipients are a CRITICAL theft risk. MULTI-CALL ALLOCATION: an allocation can be executed MULTIPLE times (no consumed flag in contract). Use Amount mode (not Surplus) for recurring allocations — Surplus calls balance::withdraw_all which drains the balance. For monthly payment scenarios, create multiple Allocators with time-based Guards + Amount mode sharing items.",
1016
1016
  "anyOf": [
1017
1017
  {
1018
1018
  "type": "object",
@@ -81,7 +81,7 @@
81
81
  },
82
82
  "type_parameter": {
83
83
  "default": "0x2::wow::WOW",
84
- "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. '0x2::wow::WOW' (WOW, the default), '0x...::usdt::USDT' (USDT), '0x...::eth::ETH' (ETH). Defines which token this object accepts for payments. To discover all available tokens and their type tags, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here.",
84
+ "description": "Payment token type for this object (format: {address}::{module}::{struct}). e.g. ALWAYS the FULL type string `{address}::{module}::{struct}` e.g. '0x2::wow::WOW'. ⚠️ The bare names 'WOW' / 'USDT' / 'ETH' are REJECTED (the validator requires all three parts) — write '0x2::wow::WOW', not 'WOW'. The field may be OMITTED entirely: it then defaults to WOW ('0x2::wow::WOW'). This token is what the object accepts for payments and is fixed at creation. To discover other available tokens, call wowok_buildin_info with info 'mainnet bridge tokens' and use the returned `wowTypeTag` value here. NOTE: testnet/localnet carry WOW only — USDT/ETH are a mainnet capability.",
85
85
  "type": "string"
86
86
  }
87
87
  },
@@ -9098,6 +9098,17 @@
9098
9098
  "additionalProperties": false
9099
9099
  }
9100
9100
  },
9101
+ "discount": {
9102
+ "description": "C-10: Discount (coupon) object address or LocalMark name to price the basket WITH. Without it the quote is always the UNDISCOUNTED total, so a discounted buyer cannot compute the exact total_pay that order_new requires (it must equal the order total precisely — any drift aborts with E_COIN_NOT_ENOUGH). RATES subtracts total*off/10000; MINUS/FIXED subtracts min(total, off), mirroring the on-chain rule with integer floor division. Read-only: quoting does NOT consume the coupon.",
9103
+ "anyOf": [
9104
+ {
9105
+ "type": "string"
9106
+ },
9107
+ {
9108
+ "type": "null"
9109
+ }
9110
+ ]
9111
+ },
9101
9112
  "context_network": {
9102
9113
  "type": "string",
9103
9114
  "enum": [
@@ -9275,7 +9275,7 @@
9275
9275
  "type": "null"
9276
9276
  }
9277
9277
  ],
9278
- "description": "Minimum order total for the discount to apply (smallest units) — the discount applies only when the order total is greater than or equal to this value. null means the discount never applies (a used coupon object is still consumed, with no effect on the total)."
9278
+ "description": "Minimum order total for the discount to apply (smallest units) — when set, the discount applies only if the PRE-discount order total is greater than or equal to this value. null (or 0) means NO threshold, so the discount applies UNCONDITIONALLY. Sharp edge: an order below a set threshold is NOT rejected — it completes at FULL price and the one-time coupon object is still consumed and destroyed."
9279
9279
  },
9280
9280
  "off": {
9281
9281
  "anyOf": [
@@ -16775,10 +16775,13 @@
16775
16775
  "enum": [
16776
16776
  "merchant",
16777
16777
  "customer",
16778
+ "demander",
16778
16779
  "prospect",
16779
16780
  "supplier",
16780
16781
  "collaborator",
16781
- "arbitrator"
16782
+ "arbitrator",
16783
+ "neutral",
16784
+ "system"
16782
16785
  ],
16783
16786
  "description": "Derived commercial role from on-chain data (Order.builder + PermissionPerm grants + named operators), never caller-asserted."
16784
16787
  },
@@ -17218,10 +17221,13 @@
17218
17221
  "enum": [
17219
17222
  "merchant",
17220
17223
  "customer",
17224
+ "demander",
17221
17225
  "prospect",
17222
17226
  "supplier",
17223
17227
  "collaborator",
17224
- "arbitrator"
17228
+ "arbitrator",
17229
+ "neutral",
17230
+ "system"
17225
17231
  ],
17226
17232
  "description": "Derived commercial role from on-chain data (Order.builder + PermissionPerm grants + named operators), never caller-asserted."
17227
17233
  },
@@ -21005,7 +21011,8 @@
21005
21011
  ],
21006
21012
  "additionalProperties": false
21007
21013
  }
21008
- ]
21014
+ ],
21015
+ "description": "Envelope: { query_type, result }. READ PATH = structuredContent.result.result.<payload> — the 'result' key appears TWICE by design (outer = tool envelope, inner = per-query_type answer), so the payload for e.g. onchain_objects is at `result.result.objects`, for account_balance `result.result.balance`, for onchain_received `result.result.received`. Do NOT read `result.objects` — it is undefined there and an empty read is indistinguishable from 'object absent on chain'."
21009
21016
  },
21010
21017
  "network": {
21011
21018
  "description": "Network the data was READ from for single-network on-chain query types (e.g. account_balance, onchain_objects, onchain_transaction, panoramas). Omitted for purely-local queries (local_*), static cross-chain data (scenario_topology), and two-network results (migration_preflight). When network_source='default' the input omitted the network and the SDK's current default network was used.",
@@ -373,7 +373,7 @@
373
373
  "description": "List of object IDs (names or addresses) to query in batch"
374
374
  },
375
375
  "no_cache": {
376
- "description": "Set to true to bypass cache and fetch fresh on-chain data",
376
+ "description": "Set to FALSE to allow the session cache; OMIT (or pass true) for a forced-fresh read. ⚠️ DEFAULT IS FRESH ON PURPOSE: a cached snapshot here reports a PRE-TRANSACTION value for exactly the fields an agent uses to decide whether money moved — on testnet this reported a stale `compensation_fund`, a stale `order.claimed_by`, and a stale `allocation.balance`. Only pass no_cache:false when you deliberately want a cheap repeat read of data you already know is current. The response carries `_read_freshness` (source live|session_cache, fetched_at) so a snapshot can never be mistaken for state.",
377
377
  "type": "boolean"
378
378
  },
379
379
  "network": {
@@ -391,7 +391,7 @@
391
391
  "objects"
392
392
  ],
393
393
  "additionalProperties": false,
394
- "description": "Batch query on-chain WOWOK objects by ID or name — supports Service, Machine, Order, Treasury, Reward, Arb, Personal, Contact, and more. Use to inspect one or more objects in a single call. Returns: { objects: ObjectBase[] }"
394
+ "description": "Batch query on-chain WOWOK objects by ID or name — supports Service, Machine, Order, Treasury, Reward, Arb, Personal, Contact, and more. Use to inspect one or more objects in a single call. FORCED-FRESH by default (see no_cache) and the response includes `_read_freshness` provenance. Returns: { objects: ObjectBase[], _read_freshness: { source, no_cache, fetched_at, note } }"
395
395
  },
396
396
  {
397
397
  "type": "object",
@@ -1010,6 +1010,17 @@
1010
1010
  "additionalProperties": false
1011
1011
  }
1012
1012
  },
1013
+ "discount": {
1014
+ "description": "C-10: Discount (coupon) object address or LocalMark name to price the basket WITH. Without it the quote is always the UNDISCOUNTED total, so a discounted buyer cannot compute the exact total_pay that order_new requires (it must equal the order total precisely — any drift aborts with E_COIN_NOT_ENOUGH). RATES subtracts total*off/10000; MINUS/FIXED subtracts min(total, off), mirroring the on-chain rule with integer floor division. Read-only: quoting does NOT consume the coupon.",
1015
+ "anyOf": [
1016
+ {
1017
+ "type": "string"
1018
+ },
1019
+ {
1020
+ "type": "null"
1021
+ }
1022
+ ]
1023
+ },
1013
1024
  "context_network": {
1014
1025
  "type": "string",
1015
1026
  "enum": [
@@ -1 +1 @@
1
- import{strictParse}from'../../schema/index.js';import{BenchmarkMigrationSchema}from'../../schema/benchmark-migration/index.js';import{getTemplate,listTemplates}from'../../knowledge/template-loader.js';import{scanTemplate}from'../../knowledge/template-scanner.js';import{planMigration}from'../../playbooks/service-build/migration-planner.js';import{handleMerchantGuide}from'../../playbooks/service-build/merchant-guide.js';import{getIndustryModeRegistry}from'../../extensions/index.js';import{resolveIndustryName}from'../../knowledge/industry-registry.js';function templateSummary(a){return{'id':a['id'],'industry':a['industry'],'variant':a['variant'],'product_ref':a['product_ref'],'archetype':a['archetype'],'key_risk':a['key_risk'],'node_count':a['machine_shape']['length'],'guard_count':a['guards']['length'],'recommended_role':a['recommended_role']};}function requireTemplate(a,b){if(!a)throw new Error('\x27template_id\x27\x20is\x20required\x20for\x20action=\x27'+b+'\x27');const c=getTemplate(a);if(!c)throw new Error('Unknown\x20template\x20id:\x20'+a+'\x20(use\x20action=\x27template_list\x27\x20to\x20see\x20valid\x20ids)');return c;}function scanSummary(a){const b={};for(const c of a['findings'])b[c['severity']]=(b[c['severity']]??0x0)+0x1;return{'risk_level':a['risk_level'],'passed':a['passed'],'finding_count':a['findings']['length'],'findings_by_severity':b,'red_flags':a['red_flags'],'findings':a['findings']};}function assertScanPassed(a,b){if(a['passed'])return;throw new Error('action=\x27'+b+'\x27\x20blocked:\x20pre-deploy\x20scan\x20of\x20template\x20\x27'+a['template_id']+'\x27\x20found\x20CRITICAL\x20risk\x20—\x20'+a['red_flags']['join'](';\x20')+'.\x20Fix\x20the\x20template\x20(frontmatter\x20or\x20body)\x20and\x20re-run\x20action=\x27template_scan\x27.');}function templateIntent(a,b){if(b&&b['trim']())return b['trim']();return'Adopt\x20the\x20'+a['id']+'\x20industry\x20archetype\x20template\x20('+a['archetype']+')\x20for\x20the\x20'+a['industry']+'\x20industry.\x20'+('Primary\x20risk\x20to\x20mitigate:\x20'+a['key_risk']+'.');}function effectiveFeeParams(a,b){return{...a['fee_params'],...b??{}};}function validateFeeParams(a,b){const c=[];let d=0x0;for(const [e,f]of Object['entries'](a)){if(typeof f!=='number'||!Number['isFinite'](f))continue;if(e['endsWith']('_bps')){(!Number['isInteger'](f)||f<0x0||f>0x2710)&&c['push'](e+'='+f+'\x20is\x20not\x20an\x20integer\x20rate\x20in\x20[0,\x2010000]\x20bps');if(e['endsWith']('_share_bps'))d+=Math['max'](0x0,f);}else{if(e['endsWith']('_days')){if(f<=0x0||f>0xe42)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x203650]\x20days');}else{if(e['endsWith']('_hours')){if(f<=0x0||f>0x2238)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x208760]\x20hours');}}}}if(d>0x2710)c['push']('*_share_bps\x20sum\x20'+d+'\x20exceeds\x2010000\x20(a\x20pool\x20splits\x20into\x20at\x20most\x20100%)');if(c['length']>0x0)throw new Error('invalid\x20fee\x20parameters\x20for\x20template\x20\x27'+b+'\x27:\x20'+c['join'](';\x20')+'.\x20'+'Correct\x20the\x20template\x27s\x20fee_params\x20or\x20pass\x20valid\x20\x27fee_overrides\x27.');}function planDivergences(a,b){const c=[],d=b?.['length']??0x0;d!==a['allocator']['count']&&c['push']({'severity':'critical','item':'allocator_row_count','detail':'Template\x20declares\x20'+a['allocator']['count']+'\x20sharing\x20row(s);\x20the\x20generated\x20plan\x20carries\x20'+d+'\x20percentage\x20row(s).','action':'Build\x20the\x20Allocation\x20with\x20the\x20template\x27s\x20own\x20row\x20set\x20(order_allocators\x20is\x20L1\x20—\x20frozen\x20at\x20Service\x20publish).'});a['allocator']['mode']!=='rate'&&c['push']({'severity':'critical','item':'allocation_mode','detail':'Template\x20allocator\x20mode\x20is\x20\x27'+a['allocator']['mode']+'\x27,\x20which\x20a\x20percentage\x20pair\x20cannot\x20represent.','action':'Declare\x20the\x20mode\x20per\x20row\x20explicitly\x20(amount\x20/\x20rate\x20/\x20surplus)\x20instead\x20of\x20publishing\x20the\x20percentage\x20hint.'});const e=a['allocator']['refund_track']!==undefined||/refund/i['test'](a['allocator']['description']);a['allocator']['refund_track']&&c['push']({'severity':'critical','item':'refund_track_not_in_plan','detail':'Template\x20declares\x20a\x20\x27'+a['allocator']['refund_track']+'\x27\x20refund\x20track;\x20the\x20generated\x20plan\x20carries\x20only\x20the\x20settlement\x20split.','action':'Build\x20the\x20second\x20Allocator\x20(Rate\x2010000\x20to\x20the\x20buyer,\x20order-anchored\x20GuardIdentifier\x20recipients)\x20bound\x20to\x20the\x20refund\x20Guard\x20before\x20publish.'});if(!e)c['push']({'severity':'critical','item':'refund_track','detail':'The\x20template\x27s\x20allocator\x20declares\x20no\x20refund\x20track\x20—\x20returns/refunds\x20have\x20no\x20funded\x20path\x20in\x20the\x20money\x20plan.','action':'Add\x20the\x20second\x20Allocator\x20(Rate\x2010000\x20to\x20the\x20buyer)\x20bound\x20to\x20the\x20refund\x20Guard,\x20or\x20confirm\x20with\x20the\x20merchant\x20that\x20refunds\x20are\x20out\x20of\x20scope.'});else!a['allocator']['refund_track']&&c['push']({'severity':'warning','item':'refund_track','detail':'A\x20refund\x20track\x20is\x20declared\x20but\x20not\x20order-anchored,\x20so\x20the\x20refund\x20recipient\x20is\x20resolved\x20from\x20the\x20signer/Entity\x20rather\x20than\x20the\x20paying\x20Order.','action':'Gate\x20the\x20refund\x20track\x20with\x20AND[signer\x20==\x20order.owner,\x20progress.node\x20==\x20X]\x20or\x20move\x20it\x20to\x20an\x20order-anchored\x20GuardIdentifier(0)\x20recipient.'});const f=Object['keys'](a['fee_params'])['filter'](g=>/_(?:days|hours)$/['test'](g));return f['length']>0x0&&!a['time_anchors']&&c['push']({'severity':'warning','item':'window_anchors','detail':'fee_params\x20declares\x20business\x20windows\x20('+f['join'](',\x20')+')\x20but\x20the\x20template\x20declares\x20no\x20time_anchors.','action':'Add\x20time_anchors\x20(or\x20name\x20the\x20window\x20in\x20the\x20Guard\x20set)\x20so\x20the\x20plan\x20emits\x20the\x20release/timeout\x20build\x20steps.'}),c;}function platformShareBps(a){const b=Object['keys'](a)['find'](c=>/(?:platform|commission|service_fee)[a-z_]*_bps$/['test'](c)&&!/^attributed_/['test'](c)&&typeof a[c]==='number');return b!==undefined?a[b]:undefined;}function variantPaymentModel(a){const b=a['machine_shape']['map'](c=>c['name']+'\x20'+c['role'])['join']('\x20')['toLowerCase']();if(/\b(milestone|revision|revis|draft|deliverable)\b/['test'](b))return'milestone';if(/\b(charge|renew|subscription|cycle|billing|monthly)\b/['test'](b))return'subscription';return'escrow';}function variantRefundPolicy(a){const b=a['allocator']['description']['toLowerCase']();if(/full[ -]?refund|100% refund|refund .*100/['test'](b))return'full';if(/pro-?rata|prorated/['test'](b))return'milestone_prorated';if(/partial/['test'](b))return'partial';return undefined;}function variantDeliverables(a,b){const c=[...a['machine_shape']]['reverse']()['find'](e=>!/refund|cancel|dispute|terminat/i['test'](e['name']+'\x20'+e['role']))??a['machine_shape'][a['machine_shape']['length']-0x1],d=b?.['has_logistics']?'physical':b?.['pure_digital']?'digital':'service_session';return[{'name':a['variant']+'\x20fulfillment','type':d,'acceptanceCriteria':'Order\x20reaches\x20the\x20terminal\x20workflow\x20node\x20\x27'+c['name']+'\x27\x20('+c['role']+')','proofOfDelivery':'manual_confirm'}];}function variantModePrior(a,b){if(!b)return undefined;return{...b,'name':a['industry']+'_'+a['variant'],'display_name':a['variant']+'\x20archetype\x20('+a['industry']+')','source':'custom','machine_shape':a['machine_shape']['map'](c=>({...c})),'guards':a['guards']['map'](c=>({...c})),'allocator':{...a['allocator']},'key_risk':a['key_risk'],'build_notes':[...a['build_notes']],...a['time_anchors']?{'time_anchors':{...a['time_anchors']}}:{}};}async function runGuide(a,b,c){const d=effectiveFeeParams(a,c);validateFeeParams(d,a['id']);const e=getIndustryModeRegistry()['getMode'](a['industry']),f=platformShareBps(d),g={'model':variantPaymentModel(a)},h=[];if(f!==undefined){const m=Math['round'](f)/0x64;h['push']({'recipient':'merchant','percentage':Math['round']((0x64-m)*0x64)/0x64}),h['push']({'recipient':'platform','percentage':m}),g['allocation']=h;}const i=variantRefundPolicy(a),j={'escrow':!![]};if(i)j['refundPolicy']=i;const k=await handleMerchantGuide({'intent':templateIntent(a,b),'guide_confirm':{'industry':a['industry'],'payment':g,'trust':j,'deliverables':variantDeliverables(a,e?.['traits'])},'mode_prior_override':variantModePrior(a,e),'name_base':a['id']}),l=planDivergences(a,h);l['length']>0x0&&(k['plan_divergence']={'template_allocator':{...a['allocator']},'template_guard_refs':a['guards']['length'],'plan_allocation':h,'divergences':l,'publish_ready':![]});k['template']={'id':a['id'],'archetype':a['archetype'],'recommended_role':a['recommended_role'],'fee_params':d};if(c&&Object['keys'](c)['length']>0x0)k['template_fee_overrides']=c;return k;}export async function handleBenchmarkMigrationOperation(a){const b=strictParse(BenchmarkMigrationSchema,a,'benchmark_migration_operation\x20input'),c=b['industry']?resolveIndustryName(b['industry'])??b['industry']['toLowerCase']():undefined;let d;switch(b['action']){case'template_list':{const {templates:e,errors:f}=listTemplates(),g=c?e['filter'](h=>h['industry']===c):e;d={'action':'template_list','count':g['length'],'templates':g['map'](templateSummary),'load_errors':f};break;}case'template_get':{const h=requireTemplate(b['template_id'],'template_get');d={'action':'template_get','template':{...h}};break;}case'template_generate':{const i=requireTemplate(b['template_id'],'template_generate'),j=scanTemplate(i);assertScanPassed(j,'template_generate');const k=await runGuide(i,b['description'],b['fee_overrides']);d={'action':'template_generate','template_id':i['id'],'scan':scanSummary(j),'plan':k};break;}case'template_scan':{const l=requireTemplate(b['template_id'],'template_scan');d={'action':'template_scan','scan':scanTemplate(l)};break;}case'migration_import':{if(!b['description']||!b['description']['trim']())throw new Error('\x27description\x27\x20is\x20required\x20for\x20action=\x27migration_import\x27');const m=planMigration({'url':b['url'],'description':b['description'],'industry':c,'network':b['network']});if(!m)throw new Error('No\x20industry\x20template\x20matched\x20the\x20description.\x20Refine\x20the\x20description\x20or\x20pass\x20an\x20explicit\x20\x27industry\x27\x20hint.');d={'action':'migration_import','log':m};break;}case'migration_review':{if(!b['log'])throw new Error('\x27log\x27\x20is\x20required\x20for\x20action=\x27migration_review\x27');const n=b['log'],o=Array['isArray'](n['mapped'])?n['mapped']:[],p=Array['isArray'](n['unmapped'])?n['unmapped']:[],q=Array['isArray'](n['manual_review'])?n['manual_review']:[],r=n['risk_check']??{};d={'action':'migration_review','log':n,'review_summary':{'mapped_count':o['length'],'unmapped_count':p['length'],'manual_review_count':q['length'],'risk_passed':r['passed']===!![]}};break;}case'migration_apply':{const s=requireTemplate(b['template_id'],'migration_apply'),t=scanTemplate(s);assertScanPassed(t,'migration_apply');const u=b['network']??'testnet',v=await runGuide(s,b['description'],b['fee_overrides']);d={'action':'migration_apply','template_id':s['id'],'network':u,'scan':scanSummary(t),'plan':v};break;}default:throw new Error('Unknown\x20benchmark_migration_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':d})}],'structuredContent':{'result':d}};}
1
+ import{strictParse}from'../../schema/index.js';import{BenchmarkMigrationSchema}from'../../schema/benchmark-migration/index.js';import{getTemplate,listTemplates}from'../../knowledge/template-loader.js';import{scanTemplate}from'../../knowledge/template-scanner.js';import{planMigration}from'../../playbooks/service-build/migration-planner.js';import{handleMerchantGuide}from'../../playbooks/service-build/merchant-guide.js';import{getIndustryModeRegistry}from'../../extensions/index.js';import{resolveIndustryName}from'../../knowledge/industry-registry.js';function templateSummary(a){return{'id':a['id'],'industry':a['industry'],'variant':a['variant'],'product_ref':a['product_ref'],'archetype':a['archetype'],'key_risk':a['key_risk'],'node_count':a['machine_shape']['length'],'guard_count':a['guards']['length'],'recommended_role':a['recommended_role']};}function requireTemplate(a,b){if(!a)throw new Error('\x27template_id\x27\x20is\x20required\x20for\x20action=\x27'+b+'\x27');const c=getTemplate(a);if(!c)throw new Error('Unknown\x20template\x20id:\x20'+a+'\x20(use\x20action=\x27template_list\x27\x20to\x20see\x20valid\x20ids)');return c;}function scanSummary(a){const b={};for(const c of a['findings'])b[c['severity']]=(b[c['severity']]??0x0)+0x1;return{'risk_level':a['risk_level'],'passed':a['passed'],'finding_count':a['findings']['length'],'findings_by_severity':b,'red_flags':a['red_flags'],'findings':a['findings']};}function assertScanPassed(a,b){if(a['passed'])return;throw new Error('action=\x27'+b+'\x27\x20blocked:\x20pre-deploy\x20scan\x20of\x20template\x20\x27'+a['template_id']+'\x27\x20found\x20CRITICAL\x20risk\x20—\x20'+a['red_flags']['join'](';\x20')+'.\x20Fix\x20the\x20template\x20(frontmatter\x20or\x20body)\x20and\x20re-run\x20action=\x27template_scan\x27.');}function templateIntent(a,b){if(b&&b['trim']())return b['trim']();return'Adopt\x20the\x20'+a['id']+'\x20industry\x20archetype\x20template\x20('+a['archetype']+')\x20for\x20the\x20'+a['industry']+'\x20industry.\x20'+('Primary\x20risk\x20to\x20mitigate:\x20'+a['key_risk']+'.');}function effectiveFeeParams(a,b){return{...a['fee_params'],...b??{}};}function validateFeeParams(a,b){const c=[];let d=0x0;for(const [e,f]of Object['entries'](a)){if(typeof f!=='number'||!Number['isFinite'](f))continue;if(e['endsWith']('_bps')){(!Number['isInteger'](f)||f<0x0||f>0x2710)&&c['push'](e+'='+f+'\x20is\x20not\x20an\x20integer\x20rate\x20in\x20[0,\x2010000]\x20bps');if(e['endsWith']('_share_bps'))d+=Math['max'](0x0,f);}else{if(e['endsWith']('_days')){if(f<=0x0||f>0xe42)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x203650]\x20days');}else{if(e['endsWith']('_hours')){if(f<=0x0||f>0x2238)c['push'](e+'='+f+'\x20is\x20outside\x20the\x20sane\x20window\x20range\x20(0,\x208760]\x20hours');}}}}if(d>0x2710)c['push']('*_share_bps\x20sum\x20'+d+'\x20exceeds\x2010000\x20(a\x20pool\x20splits\x20into\x20at\x20most\x20100%)');if(c['length']>0x0)throw new Error('invalid\x20fee\x20parameters\x20for\x20template\x20\x27'+b+'\x27:\x20'+c['join'](';\x20')+'.\x20'+'Correct\x20the\x20template\x27s\x20fee_params\x20or\x20pass\x20valid\x20\x27fee_overrides\x27.');}function validateAllocatorRows(a){const b=a['allocator']['rows'];if(b===undefined||b['length']===0x0)return[];const c=[],d=b['filter'](f=>f['track']==='settlement'),e=b['filter'](f=>f['track']==='refund');d['length']!==a['allocator']['count']&&c['push']('settlement\x20rows\x20'+d['length']+'\x20!=\x20allocator.count\x20'+a['allocator']['count']);e['length']>0x0&&!a['allocator']['refund_track']&&c['push']('refund\x20rows\x20declared\x20but\x20allocator.refund_track\x20is\x20missing');a['allocator']['refund_track']&&e['length']===0x0&&c['push']('refund_track\x20\x27'+a['allocator']['refund_track']+'\x27\x20declared\x20but\x20no\x20refund\x20row\x20carries\x20it');for(const [f,g]of[['settlement',d],['refund',e]]){const h=g['filter'](j=>j['mode']==='surplus')['length'];if(h>0x1)c['push'](f+'\x20track\x20has\x20'+h+'\x20Surplus\x20rows\x20(allocation.move\x20allows\x20at\x20most\x20one)');const i=g['filter'](j=>j['mode']==='rate');if(i['length']===g['length']&&i['length']>0x0&&h===0x0){const j=i['reduce']((k,l)=>k+(typeof l['value']==='number'?l['value']:Number(l['value']??NaN)),0x0);(!Number['isFinite'](j)||j!==0x2710)&&c['push'](f+'\x20track\x20is\x20all-Rate\x20but\x20sums\x20to\x20'+j+',\x20not\x2010000\x20bps');}for(const k of g){if(k['mode']==='surplus'&&k['value']!==undefined)c['push'](f+'/'+(k['recipient_key']??'?')+':\x20surplus\x20row\x20must\x20not\x20carry\x20a\x20value');k['mode']==='amount'&&k['value']===undefined&&k['value_from']===undefined&&c['push'](f+'/'+(k['recipient_key']??'?')+':\x20amount\x20row\x20needs\x20value\x20or\x20value_from'),k['value_from']!==undefined&&!(k['value_from']in a['fee_params'])&&c['push'](f+'/'+(k['recipient_key']??'?')+':\x20value_from\x20\x27'+k['value_from']+'\x27\x20is\x20not\x20a\x20fee_params\x20key'),k['recipient']==='guard_identifier'&&k['track']==='settlement'&&c['push']('settlement\x20row\x20uses\x20GuardIdentifier\x20—\x20order-anchored\x20recipients\x20belong\x20to\x20the\x20refund\x20track\x20(see\x20refund_track)');}}return c;}function planDivergences(a,b){const c=[],d=b?.['length']??0x0,e=(a['allocator']['rows']?.['length']??0x0)>0x0;if(e){const h=validateAllocatorRows(a);h['length']>0x0&&c['push']({'severity':'critical','item':'allocator_rows_invalid','detail':'Template\x20allocator\x20rows\x20are\x20internally\x20inconsistent:\x20'+h['join'](';\x20')+'.','action':'Fix\x20the\x20template\x27s\x20allocator.rows\x20(they\x20are\x20the\x20authoritative\x20money\x20plan;\x20order_allocators\x20is\x20L1-frozen\x20at\x20publish).'});}else d!==a['allocator']['count']&&c['push']({'severity':'critical','item':'allocator_row_count','detail':'Template\x20declares\x20'+a['allocator']['count']+'\x20sharing\x20row(s);\x20the\x20generated\x20plan\x20carries\x20'+d+'\x20percentage\x20row(s).','action':'Build\x20the\x20Allocation\x20with\x20the\x20template\x27s\x20own\x20row\x20set\x20(order_allocators\x20is\x20L1\x20—\x20frozen\x20at\x20Service\x20publish),\x20or\x20declare\x20allocator.rows\x20in\x20the\x20template.'}),a['allocator']['mode']!=='rate'&&c['push']({'severity':'critical','item':'allocation_mode','detail':'Template\x20allocator\x20mode\x20is\x20\x27'+a['allocator']['mode']+'\x27,\x20which\x20a\x20percentage\x20pair\x20cannot\x20represent\x20—\x20no\x20percentage\x20hint\x20was\x20emitted.','action':'Declare\x20allocator.rows\x20in\x20the\x20template\x20(per-row\x20amount\x20/\x20rate\x20/\x20surplus);\x20the\x20pipeline\x20will\x20then\x20carry\x20the\x20real\x20split\x20instead\x20of\x20a\x20hint.'});const f=a['allocator']['refund_track']!==undefined||/refund/i['test'](a['allocator']['description']);a['allocator']['refund_track']&&c['push']({'severity':'critical','item':'refund_track_not_in_plan','detail':'Template\x20declares\x20a\x20\x27'+a['allocator']['refund_track']+'\x27\x20refund\x20track;\x20the\x20generated\x20plan\x20carries\x20only\x20the\x20settlement\x20split.','action':'Build\x20the\x20second\x20Allocator\x20(Rate\x2010000\x20to\x20the\x20buyer,\x20order-anchored\x20GuardIdentifier\x20recipients)\x20bound\x20to\x20the\x20refund\x20Guard\x20before\x20publish.'});if(!f)c['push']({'severity':'critical','item':'refund_track','detail':'The\x20template\x27s\x20allocator\x20declares\x20no\x20refund\x20track\x20—\x20returns/refunds\x20have\x20no\x20funded\x20path\x20in\x20the\x20money\x20plan.','action':'Add\x20the\x20second\x20Allocator\x20(Rate\x2010000\x20to\x20the\x20buyer)\x20bound\x20to\x20the\x20refund\x20Guard,\x20or\x20confirm\x20with\x20the\x20merchant\x20that\x20refunds\x20are\x20out\x20of\x20scope.'});else!a['allocator']['refund_track']&&c['push']({'severity':'warning','item':'refund_track','detail':'A\x20refund\x20track\x20is\x20declared\x20but\x20not\x20order-anchored,\x20so\x20the\x20refund\x20recipient\x20is\x20resolved\x20from\x20the\x20signer/Entity\x20rather\x20than\x20the\x20paying\x20Order.','action':'Gate\x20the\x20refund\x20track\x20with\x20AND[signer\x20==\x20order.owner,\x20progress.node\x20==\x20X]\x20or\x20move\x20it\x20to\x20an\x20order-anchored\x20GuardIdentifier(0)\x20recipient.'});const g=Object['keys'](a['fee_params'])['filter'](i=>/_(?:days|hours)$/['test'](i));return g['length']>0x0&&!a['time_anchors']&&c['push']({'severity':'warning','item':'window_anchors','detail':'fee_params\x20declares\x20business\x20windows\x20('+g['join'](',\x20')+')\x20but\x20the\x20template\x20declares\x20no\x20time_anchors.','action':'Add\x20time_anchors\x20(or\x20name\x20the\x20window\x20in\x20the\x20Guard\x20set)\x20so\x20the\x20plan\x20emits\x20the\x20release/timeout\x20build\x20steps.'}),c;}function platformShareBps(a){const b=Object['keys'](a)['find'](c=>/(?:platform|commission|service_fee)[a-z_]*_bps$/['test'](c)&&!/^attributed_/['test'](c)&&typeof a[c]==='number');return b!==undefined?a[b]:undefined;}function variantPaymentModel(a){const b=a['machine_shape']['map'](c=>c['name']+'\x20'+c['role'])['join']('\x20')['toLowerCase']();if(/\b(milestone|revision|revis|draft|deliverable)\b/['test'](b))return'milestone';if(/\b(charge|renew|subscription|cycle|billing|monthly)\b/['test'](b))return'subscription';return'escrow';}function variantRefundPolicy(a){const b=a['allocator']['description']['toLowerCase']();if(/full[ -]?refund|100% refund|refund .*100/['test'](b))return'full';if(/pro-?rata|prorated/['test'](b))return'milestone_prorated';if(/partial/['test'](b))return'partial';return undefined;}function variantDeliverables(a,b){const c=[...a['machine_shape']]['reverse']()['find'](e=>!/refund|cancel|dispute|terminat/i['test'](e['name']+'\x20'+e['role']))??a['machine_shape'][a['machine_shape']['length']-0x1],d=b?.['has_logistics']?'physical':b?.['pure_digital']?'digital':'service_session';return[{'name':a['variant']+'\x20fulfillment','type':d,'acceptanceCriteria':'Order\x20reaches\x20the\x20terminal\x20workflow\x20node\x20\x27'+c['name']+'\x27\x20('+c['role']+')','proofOfDelivery':'manual_confirm'}];}function variantModePrior(a,b){if(!b)return undefined;return{...b,'name':a['industry']+'_'+a['variant'],'display_name':a['variant']+'\x20archetype\x20('+a['industry']+')','source':'custom','machine_shape':a['machine_shape']['map'](c=>({...c})),'guards':a['guards']['map'](c=>({...c})),'allocator':{...a['allocator']},'key_risk':a['key_risk'],'build_notes':[...a['build_notes']],...a['time_anchors']?{'time_anchors':{...a['time_anchors']}}:{}};}async function runGuide(a,b,c){const d=effectiveFeeParams(a,c);validateFeeParams(d,a['id']);const e=getIndustryModeRegistry()['getMode'](a['industry']),f=platformShareBps(d),g={'model':variantPaymentModel(a)},h=[],i=(a['allocator']['rows']?.['length']??0x0)>0x0;if(f!==undefined&&f>0x0&&!i&&a['allocator']['mode']==='rate'){const n=Math['round'](f)/0x64;h['push']({'recipient':'merchant','percentage':Math['round']((0x64-n)*0x64)/0x64}),h['push']({'recipient':'platform','percentage':n}),g['allocation']=h;}const j=variantRefundPolicy(a),k={'escrow':!![]};if(j)k['refundPolicy']=j;const l=await handleMerchantGuide({'intent':templateIntent(a,b),'guide_confirm':{'industry':a['industry'],'payment':g,'trust':k,'deliverables':variantDeliverables(a,e?.['traits'])},'mode_prior_override':variantModePrior(a,e),'name_base':a['id']}),m=planDivergences(a,h);if(a['allocator']['rows']?.['length'])l['template_allocator_rows']=a['allocator']['rows']['map'](o=>({...o}));m['length']>0x0&&(l['plan_divergence']={'template_allocator':{...a['allocator']},'template_guard_refs':a['guards']['length'],'plan_allocation':h,'divergences':m,'publish_ready':![]});l['template']={'id':a['id'],'archetype':a['archetype'],'recommended_role':a['recommended_role'],'fee_params':d};if(c&&Object['keys'](c)['length']>0x0)l['template_fee_overrides']=c;return l;}export async function handleBenchmarkMigrationOperation(a){const b=strictParse(BenchmarkMigrationSchema,a,'benchmark_migration_operation\x20input'),c=b['industry']?resolveIndustryName(b['industry'])??b['industry']['toLowerCase']():undefined;let d;switch(b['action']){case'template_list':{const {templates:e,errors:f}=listTemplates(),g=c?e['filter'](h=>h['industry']===c):e;d={'action':'template_list','count':g['length'],'templates':g['map'](templateSummary),'load_errors':f};break;}case'template_get':{const h=requireTemplate(b['template_id'],'template_get');d={'action':'template_get','template':{...h}};break;}case'template_generate':{const i=requireTemplate(b['template_id'],'template_generate'),j=scanTemplate(i);assertScanPassed(j,'template_generate');const k=await runGuide(i,b['description'],b['fee_overrides']);d={'action':'template_generate','template_id':i['id'],'scan':scanSummary(j),'plan':k};break;}case'template_scan':{const l=requireTemplate(b['template_id'],'template_scan');d={'action':'template_scan','scan':scanTemplate(l)};break;}case'migration_import':{if(!b['description']||!b['description']['trim']())throw new Error('\x27description\x27\x20is\x20required\x20for\x20action=\x27migration_import\x27');const m=planMigration({'url':b['url'],'description':b['description'],'industry':c,'network':b['network']});if(!m)throw new Error('No\x20industry\x20template\x20matched\x20the\x20description.\x20Refine\x20the\x20description\x20or\x20pass\x20an\x20explicit\x20\x27industry\x27\x20hint.');d={'action':'migration_import','log':m};break;}case'migration_review':{if(!b['log'])throw new Error('\x27log\x27\x20is\x20required\x20for\x20action=\x27migration_review\x27');const n=b['log'],o=Array['isArray'](n['mapped'])?n['mapped']:[],p=Array['isArray'](n['unmapped'])?n['unmapped']:[],q=Array['isArray'](n['manual_review'])?n['manual_review']:[],r=n['risk_check']??{};d={'action':'migration_review','log':n,'review_summary':{'mapped_count':o['length'],'unmapped_count':p['length'],'manual_review_count':q['length'],'risk_passed':r['passed']===!![]}};break;}case'migration_apply':{const s=requireTemplate(b['template_id'],'migration_apply'),t=scanTemplate(s);assertScanPassed(t,'migration_apply');const u=b['network']??'testnet',v=await runGuide(s,b['description'],b['fee_overrides']);d={'action':'migration_apply','template_id':s['id'],'network':u,'scan':scanSummary(t),'plan':v};break;}default:throw new Error('Unknown\x20benchmark_migration_operation\x20action:\x20'+String(b['action']));}return{'content':[{'type':'text','text':JSON['stringify']({'result':d})}],'structuredContent':{'result':d}};}
@@ -1 +1 @@
1
- import{BridgeClient,LocalMark}from'@wowok/wowok';import{classifyError,buildSemantic,buildDataSemantic}from'../../schema/call/semantic.js';import{buildReceipt}from'../../schema/call/receipt.js';import{recover}from'../../harness/recover.js';let _bridgeClient=null,_bridgeClientEnv=null;function getBridgeClient(a){const b=a||{},c=b?.['account'],d=b?.['network'];return(_bridgeClient===null||_bridgeClientEnv===null||c!==_bridgeClientEnv?.['account']||d!==_bridgeClientEnv?.['network'])&&(_bridgeClient=new BridgeClient({'wowEnv':b}),_bridgeClientEnv=b),_bridgeClient;}function getBridgeClientForQuery(){if(_bridgeClient!==null)return _bridgeClient;return _bridgeClient=new BridgeClient({}),_bridgeClientEnv={},_bridgeClient;}function validateMainnet(a){const b=a?.['network'];if(b&&b!=='mainnet')throw new Error('Bridge\x20only\x20supports\x20WOW\x20mainnet\x20(current\x20network:\x20\x27'+b+'\x27).\x20Only\x20mainnet\x20provides\x20cross-chain\x20functionality.');}async function resolveWowAddress(a,b){if(!a){const c=b?.['account'];return c;}if(/^0x[0-9a-fA-F]{64}$/['test'](a))return a;try{const d=await LocalMark['Instance']()['get_address'](a);if(d)return d;return a;}catch{return a;}}function safeJson(a){return JSON['stringify'](a,(b,c)=>typeof c==='bigint'?c['toString']():c,0x2);}function convertBigInts(a){if(typeof a==='bigint')return a['toString']();if(Array['isArray'](a))return a['map'](convertBigInts);if(a&&typeof a==='object'){const b={};for(const c of Object['keys'](a))b[c]=convertBigInts(a[c]);return b;}return a;}function ok(a,b,c){const d=convertBigInts(b),e=buildSemantic(buildReceipt(d),c),f={'outcome':'executed','message':a,'result':{'type':'data','data':d},'semantic':e};return{'content':[{'type':'text','text':a},{'type':'text','text':safeJson(d)}],'structuredContent':f};}function err(a,b){const c=classifyError(a),d=buildDataSemantic(undefined,b,!![],a),e={'outcome':'failed','message':a,'result':{'type':'error','error':a,'error_code':c['error_code'],'retryable':c['retryable'],'recovery_hint':c['recovery_hint']},'recovery':recover(c['error_code']??'unknown',b?.['operation_id']??'bridge'),'semantic':d};return{'content':[{'type':'text','text':a}],'structuredContent':e};}export async function handleBridgeOperations(a){if(!a||typeof a!=='object')return err('Invalid\x20args:\x20expected\x20an\x20object\x20with\x20operation_type');let b;try{const {strictParse:f}=await import('../../schema/call/base.js');b=f((await import('../../schema/call/bridge.js'))['BridgeOperationsSchema'],a,'bridge_operations\x20input');}catch(g){return err('Parameter\x20validation\x20failed:\x20'+(g?.['message']??String(g)));}const c=b['env'],d={'operation_type':'bridge_'+b['operation_type'],'data':b['data']};try{switch(b['operation_type']){case'cross_chain_wow_to_evm':{validateMainnet(c);const h=b['data'],i=getBridgeClient(c),j=await i['bridgeWowToEvmSimple']({'token':h['token'],'amount':BigInt(h['amount']),'withdrawTo':h['withdrawTo'],'waitForFinalization':![],'idempotencyKey':h['idempotencyKey'],'idempotentByParams':h['idempotentByParams']}),k=j['idempotentHit']?'\x20[IDEMPOTENT\x20HIT\x20—\x20no\x20new\x20deposit]':'';return ok('WOW→EVM\x20cross-chain\x20step\x201\x20(deposit)\x20submitted.\x20transferId='+j['transferId']+',\x20activeEvmAccount='+j['activeEvmAccount']+'.'+k+'\x20'+'Next:\x20poll\x20query_transfer_status\x20until\x20bridge\x20signs\x20(~1-5\x20min),\x20then\x20call\x20claim_wow_to_evm\x20to\x20complete.',j,d);}case'cross_chain_evm_to_wow':{validateMainnet(c);const l=b['data'],m=await resolveWowAddress(l['recipientWowAddress'],c),n=getBridgeClient(c),o=await n['bridgeEvmToWowSimple']({'token':l['token'],'amount':BigInt(l['amount']),'recipientWowAddress':m,'waitForFinalization':![],'idempotencyKey':l['idempotencyKey'],'idempotentByParams':l['idempotentByParams']}),p=o['idempotentHit']?'\x20[IDEMPOTENT\x20HIT\x20—\x20no\x20new\x20deposit]':'';return ok('EVM→WOW\x20cross-chain\x20submitted.\x20transferId='+o['transferId']+',\x20activeEvmAccount='+o['activeEvmAccount']+'.'+p+'\x20'+'Bridge\x20will\x20auto-claim\x20on\x20WOW\x20(~10-20\x20min).\x20Poll\x20query_transfer_status\x20to\x20monitor\x20progress.',o,d);}case'claim_wow_to_evm':{validateMainnet(c);const q=b['data'],r=getBridgeClient(c),s=await r['claimWowToEvm'](q['transferId']);return ok('WOW→EVM\x20claim\x20(step\x202)\x20completed.\x20transferId='+s['transferId']+',\x20claimTxHash='+s['claimTxHash'],s,d);}case'resume_transfer':{validateMainnet(c);const t=b['data'],u=getBridgeClient(c),v=await u['resumeTransfer'](t['transferId']);return ok('Transfer\x20'+t['transferId']+'\x20resumed.\x20Current\x20step:\x20'+v['step']+',\x20status:\x20'+v['status']+'.',v,d);}case'withdraw':{const w=b['data'],x=getBridgeClientForQuery();let y=w['tokenAddress'];if(!y&&w['token']&&w['token']!=='ETH'){const A=x['config'],B=A?.['evmChains']?.['find'](D=>D['name']===(w['network']??'mainnet')),C=B?.['tokens']?.['find'](D=>D['symbol']===w['token']);y=C?.['evmAddress'];if(!y)return err('Cannot\x20resolve\x20ERC20\x20token\x20address\x20for\x20symbol\x20\x27'+w['token']+'\x27\x20on\x20chain\x20\x27'+(w['network']??'mainnet')+'\x27.\x20Please\x20pass\x20tokenAddress\x20explicitly.',d);}const z=await x['withdrawFromActiveEvmAccount']({'to':w['to'],'amount':BigInt(w['amount']),'tokenAddress':y,'token':w['token']?w['token']:undefined,'network':w['network']});return ok('Withdrawal\x20submitted.\x20transferId='+z['transferId']+',\x20txHash='+z['txHash'],z,d);}case'query_active_evm_account':{const D=b['data']??{},E=getBridgeClientForQuery(),F=await E['queryActiveEvmAccount']({'network':D['network'],'tokens':D['tokens']});return ok('activeEvmAccount:\x20'+F['address']+'\x20('+F['chains']['length']+'\x20chain(s))',F,d);}case'query_supported_evm_chains':{const G=getBridgeClientForQuery(),H=await G['querySupportedEvmChains']();return ok(H['length']+'\x20EVM\x20chain(s)\x20supported:\x20'+H['map'](I=>I['name']+'(chainId='+I['chainId']+')')['join'](',\x20'),H,d);}case'query_supported_tokens':{const I=b['data']??{},J=getBridgeClientForQuery(),K=await J['querySupportedTokens']({'network':I['network']}),L=K['reduce']((M,N)=>M+N['tokens']['length'],0x0);return ok(K['length']+'\x20chain(s),\x20'+L+'\x20token\x20entries:\x20'+K['map'](M=>M['chainName']+'('+M['tokens']['length']+'\x20tokens)')['join'](',\x20'),K,d);}case'query_transfer_list':{const M=b['data']??{},N=getBridgeClientForQuery();let O=await N['queryTransferList']({'onlyActive':M['onlyActive']});M['status']&&(O=O['filter'](Q=>Q['status']===M['status']));M['direction']&&(O=O['filter'](Q=>Q['direction']===M['direction']));M['token']&&(O=O['filter'](Q=>Q['token']===M['token']));M['limit']&&M['limit']>0x0&&(O=O['slice'](0x0,M['limit']));const P=O['filter'](Q=>Q['status']!=='success'&&Q['status']!=='failed')['length'];return ok(O['length']+'\x20transfer\x20record(s)\x20('+P+'\x20in\x20progress)'+(M['status']||M['direction']||M['token']?'\x20(filtered)':''),O,d);}case'query_transfer_status':{const Q=b['data'],R=getBridgeClientForQuery(),S=Q['refresh']!==![];if(S)try{await Promise['race']([R['refreshTransferStatus'](Q['transferId']),new Promise((U,V)=>setTimeout(()=>V(new Error('refresh\x20timeout')),0x3a98))]);}catch{}const T=await R['queryTransferStatus'](Q['transferId']);if(!T)return err('transferId\x20\x27'+Q['transferId']+'\x27\x20not\x20found.\x20'+'Use\x20query_transfer_list\x20to\x20see\x20all\x20valid\x20transferIds.\x20'+'Note:\x20transfer\x20history\x20is\x20persisted\x20in\x20cache.db\x20and\x20restored\x20on\x20MCP\x20restart,\x20'+'so\x20this\x20transferId\x20may\x20never\x20have\x20been\x20created\x20in\x20this\x20environment.',d);return ok('Transfer\x20'+Q['transferId']+':\x20'+T['direction']+'\x20/\x20'+T['step']+'\x20/\x20'+T['status'],T,d);}case'manage_evm_rpc':{const U=b['data'],V=getBridgeClientForQuery(),W=await V['manageEvmRpc']({'op':U['op'],'network':U['network'],'rpcUrls':U['rpcUrls']});return ok('RPC\x20\x27'+U['op']+'\x27\x20operation\x20'+(W['success']?'succeeded':'failed'),W,d);}default:{return err('Unsupported\x20operation_type:\x20'+b['operation_type'],d);}}}catch(X){const Y=X?.['message']??String(X);return err('Bridge\x20operation\x20failed:\x20'+Y,d);}}
1
+ import{BridgeClient,LocalMark}from'@wowok/wowok';import{classifyError,buildSemantic,buildDataSemantic}from'../../schema/call/semantic.js';import{buildReceipt}from'../../schema/call/receipt.js';import{recover}from'../../harness/recover.js';let _bridgeClient=null,_bridgeClientEnv=null;function getBridgeClient(a){const b=a||{},c=b?.['account'],d=b?.['network'];return(_bridgeClient===null||_bridgeClientEnv===null||c!==_bridgeClientEnv?.['account']||d!==_bridgeClientEnv?.['network'])&&(_bridgeClient=new BridgeClient({'wowEnv':b}),_bridgeClientEnv=b),_bridgeClient;}function getBridgeClientForQuery(){if(_bridgeClient!==null)return _bridgeClient;return _bridgeClient=new BridgeClient({}),_bridgeClientEnv={},_bridgeClient;}function validateMainnet(a){const b=a?.['network'];if(b==='mainnet')return;throw new Error(b?'Bridge\x20is\x20only\x20available\x20on\x20WOW\x20mainnet\x20(current\x20network:\x20\x27'+b+'\x27).\x20Cross-chain\x20is\x20mainnet-only\x20-\x20switch\x20to\x20mainnet\x20or\x20pass\x20env.network=\x27mainnet\x27\x20and\x20retry.':'Bridge\x20is\x20only\x20available\x20on\x20WOW\x20mainnet.\x20No\x20network\x20was\x20specified\x20-\x20pass\x20env.network=\x27mainnet\x27\x20explicitly\x20(or\x20switch\x20your\x20network\x20to\x20mainnet)\x20and\x20retry.');}async function resolveWowAddress(a,b){if(!a){const c=b?.['account'];return c;}if(/^0x[0-9a-fA-F]{64}$/['test'](a))return a;try{const d=await LocalMark['Instance']()['get_address'](a);if(d)return d;return a;}catch{return a;}}function safeJson(a){return JSON['stringify'](a,(b,c)=>typeof c==='bigint'?c['toString']():c,0x2);}function convertBigInts(a){if(typeof a==='bigint')return a['toString']();if(Array['isArray'](a))return a['map'](convertBigInts);if(a&&typeof a==='object'){const b={};for(const c of Object['keys'](a))b[c]=convertBigInts(a[c]);return b;}return a;}function ok(a,b,c){const d=convertBigInts(b),e=buildSemantic(buildReceipt(d),c),f={'outcome':'executed','message':a,'result':{'type':'data','data':d},'semantic':e};return{'content':[{'type':'text','text':a},{'type':'text','text':safeJson(d)}],'structuredContent':f};}function err(a,b){const c=classifyError(a),d=buildDataSemantic(undefined,b,!![],a),e={'outcome':'failed','message':a,'result':{'type':'error','error':a,'error_code':c['error_code'],'retryable':c['retryable'],'recovery_hint':c['recovery_hint']},'recovery':recover(c['error_code']??'unknown',b?.['operation_id']??'bridge'),'semantic':d};return{'content':[{'type':'text','text':a}],'structuredContent':e};}export async function handleBridgeOperations(a){if(!a||typeof a!=='object')return err('Invalid\x20args:\x20expected\x20an\x20object\x20with\x20operation_type');let b;try{const {strictParse:f}=await import('../../schema/call/base.js');b=f((await import('../../schema/call/bridge.js'))['BridgeOperationsSchema'],a,'bridge_operations\x20input');}catch(g){return err('Parameter\x20validation\x20failed:\x20'+(g?.['message']??String(g)));}const c=b['env'],d={'operation_type':'bridge_'+b['operation_type'],'data':b['data']};try{switch(b['operation_type']){case'cross_chain_wow_to_evm':{validateMainnet(c);const h=b['data'],i=getBridgeClient(c),j=await i['bridgeWowToEvmSimple']({'token':h['token'],'amount':BigInt(h['amount']),'withdrawTo':h['withdrawTo'],'waitForFinalization':![],'idempotencyKey':h['idempotencyKey']}),k=j['idempotentHit']?'\x20[IDEMPOTENT\x20HIT\x20—\x20no\x20new\x20deposit]':'';return ok('WOW→EVM\x20cross-chain\x20step\x201\x20(deposit)\x20submitted.\x20transferId='+j['transferId']+',\x20activeEvmAccount='+j['activeEvmAccount']+'.'+k+'\x20'+'Next:\x20poll\x20query_transfer_status\x20until\x20bridge\x20signs\x20(~1-5\x20min),\x20then\x20call\x20claim_wow_to_evm\x20to\x20complete.',j,d);}case'cross_chain_evm_to_wow':{validateMainnet(c);const l=b['data'],m=await resolveWowAddress(l['recipientWowAddress'],c),n=getBridgeClient(c),o=await n['bridgeEvmToWowSimple']({'token':l['token'],'amount':BigInt(l['amount']),'recipientWowAddress':m,'waitForFinalization':![],'idempotencyKey':l['idempotencyKey']}),p=o['idempotentHit']?'\x20[IDEMPOTENT\x20HIT\x20—\x20no\x20new\x20deposit]':'';return ok('EVM→WOW\x20cross-chain\x20submitted.\x20transferId='+o['transferId']+',\x20activeEvmAccount='+o['activeEvmAccount']+'.'+p+'\x20'+'Bridge\x20will\x20auto-claim\x20on\x20WOW\x20(~10-20\x20min).\x20Poll\x20query_transfer_status\x20to\x20monitor\x20progress.',o,d);}case'claim_wow_to_evm':{validateMainnet(c);const q=b['data'],r=getBridgeClient(c),s=await r['claimWowToEvm'](q['transferId']);return ok('WOW→EVM\x20claim\x20(step\x202)\x20completed.\x20transferId='+s['transferId']+',\x20claimTxHash='+s['claimTxHash'],s,d);}case'resume_transfer':{validateMainnet(c);const t=b['data'],u=getBridgeClient(c),v=await u['resumeTransfer'](t['transferId']);return ok('Transfer\x20'+t['transferId']+'\x20resumed.\x20Current\x20step:\x20'+v['step']+',\x20status:\x20'+v['status']+'.',v,d);}case'withdraw':{const w=b['data'],x=getBridgeClientForQuery();let y=w['tokenAddress'];if(!y&&w['token']&&w['token']!=='ETH'){const A=x['config'],B=A?.['evmChains']?.['find'](D=>D['name']===(w['network']??'mainnet')),C=B?.['tokens']?.['find'](D=>D['symbol']===w['token']);y=C?.['evmAddress'];if(!y)return err('Cannot\x20resolve\x20ERC20\x20token\x20address\x20for\x20symbol\x20\x27'+w['token']+'\x27\x20on\x20chain\x20\x27'+(w['network']??'mainnet')+'\x27.\x20Please\x20pass\x20tokenAddress\x20explicitly.',d);}const z=await x['withdrawFromActiveEvmAccount']({'to':w['to'],'amount':BigInt(w['amount']),'tokenAddress':y,'token':w['token']?w['token']:undefined,'network':w['network']});return ok('Withdrawal\x20submitted.\x20transferId='+z['transferId']+',\x20txHash='+z['txHash'],z,d);}case'query_active_evm_account':{const D=b['data']??{},E=getBridgeClientForQuery(),F=await E['queryActiveEvmAccount']({'network':D['network'],'tokens':D['tokens']});return ok('activeEvmAccount:\x20'+F['address']+'\x20('+F['chains']['length']+'\x20chain(s))',F,d);}case'query_supported_evm_chains':{const G=getBridgeClientForQuery(),H=await G['querySupportedEvmChains']();return ok(H['length']+'\x20EVM\x20chain(s)\x20supported:\x20'+H['map'](I=>I['name']+'(chainId='+I['chainId']+')')['join'](',\x20'),H,d);}case'query_supported_tokens':{const I=b['data']??{},J=getBridgeClientForQuery(),K=await J['querySupportedTokens']({'network':I['network']}),L=K['reduce']((M,N)=>M+N['tokens']['length'],0x0);return ok(K['length']+'\x20chain(s),\x20'+L+'\x20token\x20entries:\x20'+K['map'](M=>M['chainName']+'('+M['tokens']['length']+'\x20tokens)')['join'](',\x20'),K,d);}case'query_transfer_list':{const M=b['data']??{},N=getBridgeClientForQuery();let O=await N['queryTransferList']({'onlyActive':M['onlyActive']});M['status']&&(O=O['filter'](Q=>Q['status']===M['status']));M['direction']&&(O=O['filter'](Q=>Q['direction']===M['direction']));M['token']&&(O=O['filter'](Q=>Q['token']===M['token']));M['limit']&&M['limit']>0x0&&(O=O['slice'](0x0,M['limit']));const P=O['filter'](Q=>Q['status']!=='success'&&Q['status']!=='failed')['length'];return ok(O['length']+'\x20transfer\x20record(s)\x20('+P+'\x20in\x20progress)'+(M['status']||M['direction']||M['token']?'\x20(filtered)':''),O,d);}case'query_transfer_status':{const Q=b['data'],R=getBridgeClientForQuery(),S=Q['refresh']!==![];if(S)try{await Promise['race']([R['refreshTransferStatus'](Q['transferId']),new Promise((U,V)=>setTimeout(()=>V(new Error('refresh\x20timeout')),0x3a98))]);}catch{}const T=await R['queryTransferStatus'](Q['transferId']);if(!T)return err('transferId\x20\x27'+Q['transferId']+'\x27\x20not\x20found.\x20'+'Use\x20query_transfer_list\x20to\x20see\x20all\x20valid\x20transferIds.\x20'+'Note:\x20transfer\x20history\x20is\x20persisted\x20in\x20cache.db\x20and\x20restored\x20on\x20MCP\x20restart,\x20'+'so\x20this\x20transferId\x20may\x20never\x20have\x20been\x20created\x20in\x20this\x20environment.',d);return ok('Transfer\x20'+Q['transferId']+':\x20'+T['direction']+'\x20/\x20'+T['step']+'\x20/\x20'+T['status'],T,d);}case'manage_evm_rpc':{const U=b['data'],V=getBridgeClientForQuery(),W=await V['manageEvmRpc']({'op':U['op'],'network':U['network'],'rpcUrls':U['rpcUrls']});return ok('RPC\x20\x27'+U['op']+'\x27\x20operation\x20'+(W['success']?'succeeded':'failed'),W,d);}default:{return err('Unsupported\x20operation_type:\x20'+b['operation_type'],d);}}}catch(X){const Y=X?.['message']??String(X);return err('Bridge\x20operation\x20failed:\x20'+Y,d);}}
@@ -1 +1 @@
1
- import{listServices,getServiceInfo,toggle as a420a,setEnabled as a420b,reset as a420c}from'../../config/index.js';import{judgmentStatus,setJudgmentOverride,clearJudgmentOverride,clearJudgmentOverrides,patchUserJudgmentDoc,readUserJudgmentDocView}from'../../config/judgment.js';import{strictParse}from'../../schema/index.js';import{ConfigOperationInputSchema}from'../../schema/config/index.js';export async function handleConfigOperation(a){const b=strictParse(ConfigOperationInputSchema,a,'config_operation\x20input'),{action:c,service:d,path:e,value:f}=b;let g;switch(c){case'list':g={'action':'list','services':listServices()};break;case'toggle':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20toggle');const h=d,i=getServiceInfo(h);if(!i)throw new Error('Unknown\x20service:\x20'+h+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(h==='confirm_gate'&&i['enabled'])throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');const j=a420a(h);g={'action':'toggle','service':h,'enabled':j,'reminder':i['reminder']};break;}case'disable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20disable');const k=d,l=getServiceInfo(k);if(!l)throw new Error('Unknown\x20service:\x20'+k+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(k==='confirm_gate')throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');a420b(k,![]),g={'action':'disable','service':k,'enabled':![],'reminder':l['reminder']};break;}case'enable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20enable');const m=d,n=getServiceInfo(m);if(!n)throw new Error('Unknown\x20service:\x20'+m+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a420b(m,!![]),g={'action':'enable','service':m,'enabled':!![],'reminder':n['reminder']};break;}case'reset':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20reset');const o=d,p=getServiceInfo(o);if(!p)throw new Error('Unknown\x20service:\x20'+o+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a420c(o),g={'action':'reset','service':o,'enabled':getServiceInfo(o)?.['enabled'],'reminder':p['reminder'],'reset':!![]};break;}case'info':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20info');const q=d,r=getServiceInfo(q);if(!r)throw new Error('Unknown\x20service:\x20'+q+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');g={'action':'info',...r};break;}case'judgment_list':g={'action':'judgment_list',...judgmentStatus()};break;case'judgment_set':{if(!e)throw new Error('\x27path\x27\x20param\x20is\x20required\x20for\x20judgment_set\x20(dotted,\x20e.g.\x20\x27evaluation.weights.trust_reviews\x27)');if(!('value'in b))throw new Error('\x27value\x27\x20param\x20is\x20required\x20for\x20judgment_set');const s=setJudgmentOverride(e,f);if(!s['ok'])throw new Error(s['error']);g={'action':'judgment_set','path':e,'value':f,'applied':!![]};break;}case'judgment_reset':{const t=e?clearJudgmentOverride(e)?0x1:0x0:clearJudgmentOverrides();g={'action':'judgment_reset',...e?{'path':e}:{},'cleared':t};break;}case'judgment_doc_read':{g={'action':'judgment_doc_read',...readUserJudgmentDocView()};break;}case'judgment_doc_patch':{if(!b['patch']||typeof b['patch']!=='object'||Array['isArray'](b['patch']))throw new Error('\x27patch\x27\x20param\x20is\x20required\x20for\x20judgment_doc_patch\x20(a\x20partial\x20judgment\x20document\x20object,\x20e.g.\x20{\x22evaluation\x22:\x20{\x22weights\x22:\x20{…}}})');g={'action':'judgment_doc_patch',...patchUserJudgmentDoc(b['patch'])};break;}default:throw new Error('Unknown\x20config_operation\x20action:\x20'+String(c));}return{'content':[{'type':'text','text':JSON['stringify']({'result':g})}],'structuredContent':{'result':g}};}
1
+ import{listServices,getServiceInfo,toggle as a422a,setEnabled as a422b,reset as a422c}from'../../config/index.js';import{judgmentStatus,setJudgmentOverride,clearJudgmentOverride,clearJudgmentOverrides,patchUserJudgmentDoc,readUserJudgmentDocView}from'../../config/judgment.js';import{strictParse}from'../../schema/index.js';import{ConfigOperationInputSchema}from'../../schema/config/index.js';export async function handleConfigOperation(a){const b=strictParse(ConfigOperationInputSchema,a,'config_operation\x20input'),{action:c,service:d,path:e,value:f}=b;let g;switch(c){case'list':g={'action':'list','services':listServices()};break;case'toggle':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20toggle');const h=d,i=getServiceInfo(h);if(!i)throw new Error('Unknown\x20service:\x20'+h+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(h==='confirm_gate'&&i['enabled'])throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');const j=a422a(h);g={'action':'toggle','service':h,'enabled':j,'reminder':i['reminder']};break;}case'disable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20disable');const k=d,l=getServiceInfo(k);if(!l)throw new Error('Unknown\x20service:\x20'+k+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');if(k==='confirm_gate')throw new Error('confirm_gate\x20cannot\x20be\x20disabled\x20at\x20runtime.\x20'+'Set\x20WOWOK_CONFIRM_GATE=0\x20in\x20the\x20server\x20environment\x20and\x20restart\x20if\x20you\x20really\x20want\x20it\x20off.');a422b(k,![]),g={'action':'disable','service':k,'enabled':![],'reminder':l['reminder']};break;}case'enable':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20enable');const m=d,n=getServiceInfo(m);if(!n)throw new Error('Unknown\x20service:\x20'+m+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a422b(m,!![]),g={'action':'enable','service':m,'enabled':!![],'reminder':n['reminder']};break;}case'reset':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20reset');const o=d,p=getServiceInfo(o);if(!p)throw new Error('Unknown\x20service:\x20'+o+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');a422c(o),g={'action':'reset','service':o,'enabled':getServiceInfo(o)?.['enabled'],'reminder':p['reminder'],'reset':!![]};break;}case'info':{if(!d)throw new Error('\x27service\x27\x20param\x20is\x20required\x20for\x20info');const q=d,r=getServiceInfo(q);if(!r)throw new Error('Unknown\x20service:\x20'+q+'.\x20Use\x20action=\x27list\x27\x20to\x20see\x20all\x20valid\x20services.');g={'action':'info',...r};break;}case'judgment_list':g={'action':'judgment_list',...judgmentStatus()};break;case'judgment_set':{if(!e)throw new Error('\x27path\x27\x20param\x20is\x20required\x20for\x20judgment_set\x20(dotted,\x20e.g.\x20\x27evaluation.weights.trust_reviews\x27)');if(!('value'in b))throw new Error('\x27value\x27\x20param\x20is\x20required\x20for\x20judgment_set');const s=setJudgmentOverride(e,f);if(!s['ok'])throw new Error(s['error']);g={'action':'judgment_set','path':e,'value':f,'applied':!![]};break;}case'judgment_reset':{const t=e?clearJudgmentOverride(e)?0x1:0x0:clearJudgmentOverrides();g={'action':'judgment_reset',...e?{'path':e}:{},'cleared':t};break;}case'judgment_doc_read':{g={'action':'judgment_doc_read',...readUserJudgmentDocView()};break;}case'judgment_doc_patch':{if(!b['patch']||typeof b['patch']!=='object'||Array['isArray'](b['patch']))throw new Error('\x27patch\x27\x20param\x20is\x20required\x20for\x20judgment_doc_patch\x20(a\x20partial\x20judgment\x20document\x20object,\x20e.g.\x20{\x22evaluation\x22:\x20{\x22weights\x22:\x20{…}}})');g={'action':'judgment_doc_patch',...patchUserJudgmentDoc(b['patch'])};break;}default:throw new Error('Unknown\x20config_operation\x20action:\x20'+String(c));}return{'content':[{'type':'text','text':JSON['stringify']({'result':g})}],'structuredContent':{'result':g}};}
@@ -3,3 +3,4 @@ export declare const handleAccountOperation: (args: unknown) => Promise<ToolDisp
3
3
  export declare const handleMarkOperation: (args: unknown) => Promise<ToolDispatchResult>;
4
4
  export declare const handleInfoOperation: (args: unknown) => Promise<ToolDispatchResult>;
5
5
  export declare const handleHistoryOperation: (args: unknown) => Promise<ToolDispatchResult>;
6
+ export declare const handleCacheOperation: (raw: unknown) => Promise<ToolDispatchResult>;
@@ -1 +1 @@
1
- import{wrapLocalHandler}from'../shared.js';import{withFaucetRetry}from'../retry.js';import{strictParse}from'../../schema/index.js';import{AccountOperationSchema,LocalMarkOperationSchema,LocalInfoOperationSchema,LocalHistoryOperationSchema}from'../../schema/index.js';import{account_operation,local_mark_operation,local_info_operation,local_history_operation,GasTokenType,isFundApprovalExempt}from'@wowok/wowok';import{parseAmount,generateFundConfirmation,generateSkillsHint}from'../../knowledge/fund-layer.js';import{buildDataSemantic}from'../../schema/call/semantic.js';function deriveOpType(a,b){for(const c of Object['keys'](b)){if(b[c]!==undefined)return a+'_'+String(c);}return a+'_unknown';}function accountError(a,b){return{'content':[{'type':'text','text':'Error:\x20'+a}],'structuredContent':{'result':{'status':'error','error':a},'semantic':buildDataSemantic(undefined,b,!![],a)}};}function buildAccountContext(a){return{'operation_type':deriveOpType('account',a),'data':a};}async function fundProcessCoinAmount(a,b,c){try{const d=await parseAmount(a,b,c);return{'parsed':d};}catch(f){return{'error':f instanceof Error?f['message']:String(f)};}}async function coinFundGate(a,b,c,d,e,f){const {parsed:g,error:h}=await fundProcessCoinAmount(a,b,c);if(h||!g)return{'blocked':accountError(h??'Amount\x20parsing\x20failed',f)};const i=isFundApprovalExempt(c,b,g['smallestUnit']['toString']());if(!i&&d!==!![]){const j=generateFundConfirmation([{'path':e['amountPath'],'displayAmount':g['displayAmount'],'tokenType':g['tokenType'],'tokenSymbol':g['tokenSymbol'],'decimals':g['decimals'],'smallestUnit':g['smallestUnit']['toString'](),'verified':g['verified'],'source':g['source'],'converted':g['converted'],'context':e['context']}],[]),k=generateSkillsHint(j),l=[j['message'],'',...e['detailLines'],k??'','The\x20'+e['key']+'\x20was\x20NOT\x20executed.\x20If\x20the\x20user\x20consents,\x20re-call\x20with\x20the\x20SAME\x20parameters\x20plus\x20'+e['key']+'.confirmed=true.']['filter'](m=>m!=='')['join']('\x0a');return{'blocked':{'content':[{'type':'text','text':l}],'structuredContent':{'result':{'status':'pending_confirmation','operation':e['operation'],'message':l,'rule_id':e['ruleId']},'semantic':{...buildDataSemantic(undefined,f,!![],'pending\x20user\x20confirmation'),'summary':e['summary']}}}};}return{'parsed':g};}async function executeAccountOperation(a,b){try{const c=await withFaucetRetry(account_operation)(a);return{'content':[{'type':'text','text':JSON['stringify'](c)}],'structuredContent':{'result':{'status':'success','data':c},'semantic':buildDataSemantic(c,b)}};}catch(d){const e=d instanceof Error?d['message']:String(d);return accountError(e,b);}}export const handleAccountOperation=async a=>{let b;try{b=strictParse(AccountOperationSchema,a,'account_operation\x20input');}catch(d){return accountError('Parameter\x20validation\x20failed:\x20'+(d?.['message']??String(d)));}const c=buildAccountContext(b);if(b['transfer']!==undefined){const f=b['transfer'],g=await coinFundGate(f['amount'],f['token_type']??GasTokenType,f['network'],f['confirmed'],{'key':'transfer','amountPath':'transfer.amount','context':'Account\x20token\x20transfer','operation':'account_transfer','ruleId':'account_transfer_fund_movement','summary':'Token\x20transfer\x20blocked\x20pending\x20user\x20confirmation.\x20Re-call\x20with\x20transfer.confirmed=true\x20to\x20proceed.','detailLines':['Recipient:\x20'+(f['name_or_address_to']??'(default\x20account)'),'Sender:\x20'+(f['name_or_address_from']??'(default\x20account)')]},c);if('blocked'in g)return g['blocked'];const h={...b,'transfer':{...f,'amount':g['parsed']['smallestUnit']['toString']()}};return delete h['transfer']['confirmed'],executeAccountOperation(h,c);}if(b['get']!==undefined){const i=b['get'],j=await coinFundGate(i['balance_required'],i['token_type']??GasTokenType,i['network'],i['confirmed'],{'key':'get','amountPath':'get.balance_required','context':'Coin\x20object\x20production\x20(split/merge\x20+\x20self-delivery)','operation':'account_get_coin_object','ruleId':'account_get_fund_movement','summary':'Coin\x20object\x20production\x20blocked\x20pending\x20user\x20confirmation.\x20Re-call\x20with\x20get.confirmed=true\x20to\x20proceed.','detailLines':['Account:\x20'+(i['name_or_address']??'(default\x20account)'),'Effect:\x20splits/merges\x20the\x20account\x27s\x20coins\x20and\x20self-delivers\x20a\x20coin\x20object\x20of\x20at\x20least\x20the\x20required\x20balance;\x20funds\x20never\x20leave\x20the\x20account\x20but\x20GAS\x20IS\x20SPENT.']},c);if('blocked'in j)return j['blocked'];const k={...b,'get':{...i,'balance_required':j['parsed']['smallestUnit']['toString']()}};return delete k['get']['confirmed'],executeAccountOperation(k,c);}return executeAccountOperation(b,c);};export const handleMarkOperation=wrapLocalHandler({'schema':LocalMarkOperationSchema,'operationFn':local_mark_operation,'parseLabel':'local_mark_operation\x20input','buildContext':a=>{const b={'operation_type':deriveOpType('mark',a),'data':a},c=a;return c['add']&&Array['isArray'](c['add']['data'])&&c['add']['data']['length']>0x0&&(b['pre_warnings']=['Cross-network\x20consistency\x20(FIX-011):\x20LocalMark\x20names\x20are\x20scoped\x20per\x20network.\x20'+'When\x20creating\x20marks\x20for\x20the\x20same\x20logical\x20object\x20on\x20different\x20networks\x20'+'(e.g.\x20testnet\x20and\x20mainnet),\x20use\x20the\x20SAME\x20name\x20value\x20to\x20keep\x20name-based\x20'+'references\x20portable.\x20Before\x20creating\x20a\x20mark\x20on\x20mainnet,\x20consider\x20querying\x20'+'testnet\x20via\x20query_local\x20with\x20network=\x27testnet\x27\x20to\x20check\x20for\x20an\x20existing\x20'+'same-named\x20mark\x20and\x20replicate\x20it.']),b;}});export const handleInfoOperation=wrapLocalHandler({'schema':LocalInfoOperationSchema,'operationFn':local_info_operation,'parseLabel':'local_info_operation\x20input','buildContext':a=>({'operation_type':deriveOpType('local_info',a),'data':a})});export const handleHistoryOperation=wrapLocalHandler({'schema':LocalHistoryOperationSchema,'operationFn':local_history_operation,'parseLabel':'local_history_operation\x20input','buildContext':a=>({'operation_type':deriveOpType('local_history',a),'data':a})});
1
+ import{wrapLocalHandler}from'../shared.js';import{withFaucetRetry}from'../retry.js';import{strictParse}from'../../schema/index.js';import{AccountOperationSchema,LocalMarkOperationSchema,LocalInfoOperationSchema,LocalHistoryOperationSchema,LocalCacheOperationSchema}from'../../schema/index.js';import{Cache}from'@wowok/wowok/w/local/cache';import{clearChainScope,resolveChainIdentity}from'@wowok/wowok/w/local/chain-scope';import{account_operation,local_mark_operation,local_info_operation,local_history_operation,GasTokenType,isFundApprovalExempt}from'@wowok/wowok';import{parseAmount,generateFundConfirmation,generateSkillsHint}from'../../knowledge/fund-layer.js';import{buildDataSemantic}from'../../schema/call/semantic.js';function deriveOpType(a,b){for(const c of Object['keys'](b)){if(b[c]!==undefined)return a+'_'+String(c);}return a+'_unknown';}function accountError(a,b){return{'content':[{'type':'text','text':'Error:\x20'+a}],'structuredContent':{'result':{'status':'error','error':a},'semantic':buildDataSemantic(undefined,b,!![],a)}};}function buildAccountContext(a){return{'operation_type':deriveOpType('account',a),'data':a};}async function fundProcessCoinAmount(a,b,c){try{const d=await parseAmount(a,b,c);return{'parsed':d};}catch(f){return{'error':f instanceof Error?f['message']:String(f)};}}async function coinFundGate(a,b,c,d,e,f){const {parsed:g,error:h}=await fundProcessCoinAmount(a,b,c);if(h||!g)return{'blocked':accountError(h??'Amount\x20parsing\x20failed',f)};const i=isFundApprovalExempt(c,b,g['smallestUnit']['toString']());if(!i&&d!==!![]){const j=generateFundConfirmation([{'path':e['amountPath'],'displayAmount':g['displayAmount'],'tokenType':g['tokenType'],'tokenSymbol':g['tokenSymbol'],'decimals':g['decimals'],'smallestUnit':g['smallestUnit']['toString'](),'verified':g['verified'],'source':g['source'],'converted':g['converted'],'context':e['context']}],[]),k=generateSkillsHint(j),l=[j['message'],'',...e['detailLines'],k??'','The\x20'+e['key']+'\x20was\x20NOT\x20executed.\x20If\x20the\x20user\x20consents,\x20re-call\x20with\x20the\x20SAME\x20parameters\x20plus\x20'+e['key']+'.confirmed=true.']['filter'](m=>m!=='')['join']('\x0a');return{'blocked':{'content':[{'type':'text','text':l}],'structuredContent':{'result':{'status':'pending_confirmation','operation':e['operation'],'message':l,'rule_id':e['ruleId']},'semantic':{...buildDataSemantic(undefined,f,!![],'pending\x20user\x20confirmation'),'summary':e['summary']}}}};}return{'parsed':g};}async function executeAccountOperation(a,b){try{const c=await withFaucetRetry(account_operation)(a);return{'content':[{'type':'text','text':JSON['stringify'](c)}],'structuredContent':{'result':{'status':'success','data':c},'semantic':buildDataSemantic(c,b)}};}catch(d){const e=d instanceof Error?d['message']:String(d);return accountError(e,b);}}export const handleAccountOperation=async a=>{let b;try{b=strictParse(AccountOperationSchema,a,'account_operation\x20input');}catch(d){return accountError('Parameter\x20validation\x20failed:\x20'+(d?.['message']??String(d)));}const c=buildAccountContext(b);if(b['transfer']!==undefined){const f=b['transfer'],g=await coinFundGate(f['amount'],f['token_type']??GasTokenType,f['network'],f['confirmed'],{'key':'transfer','amountPath':'transfer.amount','context':'Account\x20token\x20transfer','operation':'account_transfer','ruleId':'account_transfer_fund_movement','summary':'Token\x20transfer\x20blocked\x20pending\x20user\x20confirmation.\x20Re-call\x20with\x20transfer.confirmed=true\x20to\x20proceed.','detailLines':['Recipient:\x20'+(f['name_or_address_to']??'(default\x20account)'),'Sender:\x20'+(f['name_or_address_from']??'(default\x20account)')]},c);if('blocked'in g)return g['blocked'];const h={...b,'transfer':{...f,'amount':g['parsed']['smallestUnit']['toString']()}};return delete h['transfer']['confirmed'],executeAccountOperation(h,c);}if(b['get']!==undefined){const i=b['get'],j=await coinFundGate(i['balance_required'],i['token_type']??GasTokenType,i['network'],i['confirmed'],{'key':'get','amountPath':'get.balance_required','context':'Coin\x20object\x20production\x20(split/merge\x20+\x20self-delivery)','operation':'account_get_coin_object','ruleId':'account_get_fund_movement','summary':'Coin\x20object\x20production\x20blocked\x20pending\x20user\x20confirmation.\x20Re-call\x20with\x20get.confirmed=true\x20to\x20proceed.','detailLines':['Account:\x20'+(i['name_or_address']??'(default\x20account)'),'Effect:\x20splits/merges\x20the\x20account\x27s\x20coins\x20and\x20self-delivers\x20a\x20coin\x20object;\x20funds\x20never\x20leave\x20the\x20account\x20but\x20GAS\x20IS\x20SPENT.','On\x20success\x20the\x20result\x20reports\x20the\x20coin\x27s\x20ACTUAL\x20on-chain\x20balance\x20—\x20check\x20it\x20against\x20the\x20amount\x20you\x20need\x20before\x20relying\x20on\x20it.']},c);if('blocked'in j)return j['blocked'];const k={...b,'get':{...i,'balance_required':j['parsed']['smallestUnit']['toString']()}};return delete k['get']['confirmed'],executeAccountOperation(k,c);}return executeAccountOperation(b,c);};export const handleMarkOperation=wrapLocalHandler({'schema':LocalMarkOperationSchema,'operationFn':local_mark_operation,'parseLabel':'local_mark_operation\x20input','buildContext':a=>{const b={'operation_type':deriveOpType('mark',a),'data':a},c=a;return c['add']&&Array['isArray'](c['add']['data'])&&c['add']['data']['length']>0x0&&(b['pre_warnings']=['Cross-network\x20consistency\x20(FIX-011):\x20LocalMark\x20names\x20are\x20scoped\x20per\x20network.\x20'+'When\x20creating\x20marks\x20for\x20the\x20same\x20logical\x20object\x20on\x20different\x20networks\x20'+'(e.g.\x20testnet\x20and\x20mainnet),\x20use\x20the\x20SAME\x20name\x20value\x20to\x20keep\x20name-based\x20'+'references\x20portable.\x20Before\x20creating\x20a\x20mark\x20on\x20mainnet,\x20consider\x20querying\x20'+'testnet\x20via\x20query_local\x20with\x20network=\x27testnet\x27\x20to\x20check\x20for\x20an\x20existing\x20'+'same-named\x20mark\x20and\x20replicate\x20it.']),b;}});export const handleInfoOperation=wrapLocalHandler({'schema':LocalInfoOperationSchema,'operationFn':local_info_operation,'parseLabel':'local_info_operation\x20input','buildContext':a=>({'operation_type':deriveOpType('local_info',a),'data':a})});export const handleHistoryOperation=wrapLocalHandler({'schema':LocalHistoryOperationSchema,'operationFn':local_history_operation,'parseLabel':'local_history_operation\x20input','buildContext':a=>({'operation_type':deriveOpType('local_history',a),'data':a})});async function readStorageStats(){if(!Cache['hasStorage']())return{'rows':null,'bytes':null};const a=Cache['storage']?.['getStats'];if(typeof a!=='function')return{'rows':null,'bytes':null};try{const b=await a['call'](Cache['storage']);return{'rows':b?.['count']??null,'bytes':b?.['totalBytes']??null};}catch{return{'rows':null,'bytes':null};}}function buildCacheContext(a){return{'operation_type':deriveOpType('cache',a),'data':a};}function cacheSuccess(a,b){return{'content':[{'type':'text','text':JSON['stringify'](a,null,0x2)}],'structuredContent':{'result':{'status':'success','data':a},'semantic':buildDataSemantic(a,b)}};}export const handleCacheOperation=async a=>{let b;try{b=strictParse(LocalCacheOperationSchema,a,'local_cache_operation\x20input');}catch(d){return{'content':[{'type':'text','text':'Error:\x20'+(d instanceof Error?d['message']:String(d))}],'structuredContent':{'result':{'status':'error','error':d instanceof Error?d['message']:String(d),'error_code':'invalid_param','retryable':![],'recovery_hint':'Pass\x20exactly\x20one\x20nested\x20operation:\x20{status:{op:\x27status\x27}},\x20{clear_prefix:{op:\x27clear_prefix\x27,prefix:\x27objectv2\x27}},\x20{clear:{op:\x27clear\x27}},\x20or\x20{refresh_chain_scope:{op:\x27refresh_chain_scope\x27}}.'}}};}const c=buildCacheContext(b);try{if(b['status']){const {rows:f,bytes:g}=await readStorageStats();return cacheSuccess({'op':'status','chain_identity':Cache['chainIdentityOf']()??null,'storage_attached':Cache['hasStorage'](),'memory_entries':Cache['memory']['size'],'storage_rows':f,'storage_bytes':g},c);}if(b['clear_prefix']){const {prefix:h}=b['clear_prefix'];return await Cache['clearPrefix'](h),cacheSuccess({'op':'clear_prefix','prefix':h,'chain_identity':Cache['chainIdentityOf']()??null},c);}if(b['clear'])return await Cache['clear'](),cacheSuccess({'op':'clear','cleared':!![],'chain_identity':Cache['chainIdentityOf']()??null},c);if(b['refresh_chain_scope']){const i=Cache['chainIdentityOf']()??null;clearChainScope();const j=await resolveChainIdentity(b['refresh_chain_scope']['network'])??null;return cacheSuccess({'op':'refresh_chain_scope','previous_chain_identity':i,'chain_identity':j,'changed':j!==null&&j!==i,'resolved':j!==null},c);}return accountError('No\x20cache\x20operation\x20specified',c);}catch(k){const l=k instanceof Error?k['message']:String(k);return{'content':[{'type':'text','text':'Error:\x20'+l}],'structuredContent':{'result':{'status':'error','error':l,'error_code':'unknown_error','retryable':!![],'recovery_hint':'If\x20the\x20cache\x20backend\x20is\x20locked\x20or\x20corrupt,\x20use\x20{clear:\x20{op:\x27clear\x27}}\x20to\x20drop\x20everything,\x20or\x20{refresh_chain_scope:\x20{op:\x27refresh_chain_scope\x27}}\x20if\x20the\x20node\x20was\x20reset.'},'semantic':buildDataSemantic(undefined,c,!![],l)}};}};
@@ -6,11 +6,18 @@ export declare function normalizeAccountOrMark(input: string | {
6
6
  name_or_address?: string;
7
7
  local_mark_first?: boolean;
8
8
  };
9
+ export declare function normalizeOptionalAccountOrMark(input: string | {
10
+ name_or_address?: string;
11
+ local_mark_first?: boolean;
12
+ } | undefined | null): {
13
+ name_or_address?: string;
14
+ local_mark_first?: boolean;
15
+ } | undefined;
9
16
  export declare function normalizeManyAccountOrMark(input: string[] | {
10
17
  entities: any[];
11
18
  check_all_founded?: boolean;
12
- }): {
19
+ } | undefined | null): {
13
20
  entities: any[];
14
21
  check_all_founded?: boolean;
15
- };
22
+ } | undefined;
16
23
  export declare function handleMessengerOperation(args: unknown): Promise<ToolDispatchResult>;
@@ -1 +1 @@
1
- import{strictParse,MessengerOperationInputSchema}from'../../schema/index.js';import{watch_conversations,send_message,send_file,watch_messages,export_attachment,pull_messages,generate_wts,verify_wts,sign_wts,wts2html,proof_message,mark_messages_as_viewed,mark_conversation_as_viewed,blacklist,friendslist,guardlist,settings,LocalInfo}from'@wowok/wowok';import{classifyError,buildDataSemantic}from'../../schema/call/semantic.js';import{classifyCommunicationEvidence}from'../../communication/evidence.js';import{goalEngine}from'../../goal/GoalEngine.js';export function normalizeAccountOrMark(a){if(typeof a==='string')return{'name_or_address':a,'local_mark_first':!![]};return a;}export function normalizeManyAccountOrMark(a){if(Array['isArray'](a))return{'entities':a['map'](b=>typeof b==='string'?{'name_or_address':b,'local_mark_first':!![]}:b),'check_all_founded':!![]};return a;}function communicationEvidencePayload(a,b){const c=b??{};switch(a){case'send_message':case'send_file':{const d=typeof c['messageId']==='string'?c['messageId']:undefined;return{'detail':d?'message\x20'+d:'message\x20sent','data':d?{'message_id':d}:{}};}case'send_required_info':{const e=typeof c['messageId']==='string'?c['messageId']:undefined,f=Array['isArray'](c['sent_fields'])?c['sent_fields']:undefined;return{'detail':'required-info\x20confirmation\x20sent','data':{...e?{'message_id':e}:{},...f?{'sent_fields':f}:{}}};}case'generate_wts':{const g=typeof c['totalMessageCount']==='number'?c['totalMessageCount']:undefined,h=Array['isArray'](c['files'])?c['files']:undefined,i=Array['isArray'](c['htmlFiles'])?c['htmlFiles']:undefined;return{'detail':'WTS\x20evidence\x20packet\x20generated','data':{...g!==undefined?{'message_count':g}:{},...h?{'files':h}:{},...i?{'html_reports':i}:{}}};}case'verify_wts':{return{'detail':'WTS\x20evidence\x20verification','data':{'valid':c['valid']===!![]}};}case'sign_wts':{return{'detail':typeof b==='string'?b:'WTS\x20evidence\x20signed','data':{}};}case'proof_message':{const j=typeof c['proofAddress']==='string'?c['proofAddress']:undefined;return{'detail':j?'proof\x20'+j:'message\x20proofed\x20on-chain','data':j?{'proof_address':j}:{}};}default:return{'detail':a,'data':{}};}}export async function handleMessengerOperation(a){let b;try{b=strictParse(MessengerOperationInputSchema,a,'messenger_operation\x20input');const c=b['operation'];let d;switch(b['operation']){case'watch_conversations':{const g=await watch_conversations(b['filter']);d={'operation':'watch_conversations','result':g};break;}case'send_message':{const h=await send_message(b['from'],normalizeAccountOrMark(b['to']),b['content'],b['options']);if(h['authRequired']){d={'operation':'send_message','result':h};break;}const i=h,j={...i,'merkleData':i['merkleData']?{'leafIndex':i['merkleData']['leafIndex'],'prevRoot':i['merkleData']['prevRoot'],'newRoot':i['merkleData']['newRoot'],'serverSignature':i['merkleData']['serverSignature'],'serverTimestamp':i['merkleData']['serverTimestamp'],'serverPublicKey':i['merkleData']['serverPublicKey']}:undefined};d={'operation':'send_message','result':j};break;}case'send_file':{const k=await send_file(b['from'],normalizeAccountOrMark(b['to']),b['filePath'],b['options']),l=k,m={...l,'merkleData':l['merkleData']?{'leafIndex':l['merkleData']['leafIndex'],'prevRoot':l['merkleData']['prevRoot'],'newRoot':l['merkleData']['newRoot'],'serverSignature':l['merkleData']['serverSignature'],'serverTimestamp':l['merkleData']['serverTimestamp'],'serverPublicKey':l['merkleData']['serverPublicKey']}:undefined};d={'operation':'send_file','result':m};break;}case'send_required_info':{let n=b['content'];const o=[];if(!n){const s=await LocalInfo['Instance']()['list'](),t=b['fields'],u=t&&t['length']>0x0?s['filter'](v=>t['includes'](v['name'])):s;if(u['length']===0x0)throw new Error('No\x20LocalInfo\x20fields\x20available.\x20Add\x20private\x20info\x20first\x20via\x20local_info_operation.');n=u['map'](v=>v['name']+':\x20'+v['default'])['join']('\x0a'),o['push'](...u['map'](v=>v['name']));}const p=await send_message(b['from'],normalizeAccountOrMark(b['to']),n,b['options']),q=p,r={...q,'merkleData':q['merkleData']?{'leafIndex':q['merkleData']['leafIndex'],'prevRoot':q['merkleData']['prevRoot'],'newRoot':q['merkleData']['newRoot'],'serverSignature':q['merkleData']['serverSignature'],'serverTimestamp':q['merkleData']['serverTimestamp'],'serverPublicKey':q['merkleData']['serverPublicKey']}:undefined,'sent_fields':o};d={'operation':'send_required_info','result':r};break;}case'watch_messages':{const v=b['filter']?{...b['filter'],'peerAddress':b['filter']['peerAddress']?normalizeAccountOrMark(b['filter']['peerAddress']):undefined}:undefined,w=await watch_messages(v);d={'operation':'watch_messages','result':w};break;}case'save_attachment':{const x=await export_attachment(b['account'],b['messageId'],{'outputDir':b['outputDir'],'saveAs':b['saveAs']});d={'operation':'save_attachment','result':x};break;}case'generate_wts':{const y=b['params']?{...b['params'],'peerAccount':normalizeAccountOrMark(b['params']['peerAccount'])}:undefined,z=await generate_wts(y);d={'operation':'generate_wts','result':z};break;}case'verify_wts':{const A=await verify_wts(b['wtsFilePath']);d={'operation':'verify_wts','result':A};break;}case'sign_wts':{const B=await sign_wts(b['wtsFilePath'],b['account'],b['outputPath']);d={'operation':'sign_wts','result':B};break;}case'wts2html':{const C=await wts2html(b['wtsPath'],b['options']);d={'operation':'wts2html','result':C};break;}case'proof_message':{const D=await proof_message(b['account'],b['messageId'],b['network']);d={'operation':'proof_message','result':D};break;}case'blacklist':{const E={'account':b['account'],'op':b['blacklist']['op']};'users'in b['blacklist']&&(E['users']=normalizeManyAccountOrMark(b['blacklist']['users']));const F=await blacklist(E);d={'operation':'blacklist','op':b['blacklist']['op'],'result':F['result']};break;}case'friendslist':{const G={'account':b['account'],'op':b['friendslist']['op']};'users'in b['friendslist']&&(G['users']=normalizeManyAccountOrMark(b['friendslist']['users']));const H=await friendslist(G);d={'operation':'friendslist','op':b['friendslist']['op'],'result':H['result']};break;}case'guardlist':{const I=await guardlist({'account':b['account'],...b['guardlist']});d={'operation':'guardlist','op':b['guardlist']['op'],'result':I['result']};break;}case'settings':{const J=await settings({'account':b['account'],...b['settings']});d={'operation':'settings','op':b['settings']['op'],'result':J['result']};break;}case'mark_messages_as_viewed':{const K=await mark_messages_as_viewed(b['messageIds'],b['account']);d={'operation':'mark_messages_as_viewed','result':K};break;}case'mark_conversation_as_viewed':{const L=await mark_conversation_as_viewed(normalizeAccountOrMark(b['peerAddress']),b['account']);d={'operation':'mark_conversation_as_viewed','result':L};break;}case'pull_messages':{const M=await pull_messages(b['account'],b['limit'],{'allAccounts':b['allAccounts'],'accounts':b['accounts'],'concurrency':b['concurrency']});d={'operation':'pull_messages','result':M};break;}default:throw new Error('Unknown\x20messenger\x20operation:\x20'+c);}const e=classifyCommunicationEvidence(c),f=b['goal_id'];if(e&&f){const N=d['result'],{detail:O,data:P}=communicationEvidencePayload(c,N);await goalEngine['recordCommunicationEvidence'](f,{'operation':c,'kind':e['kind'],'title':e['title'],'detail':O,'data':P},b['network']??'default');}return{'content':[{'type':'text','text':JSON['stringify'](d)}],'structuredContent':{'result':d}};}catch(Q){const R=Q instanceof Error?Q['message']:String(Q),S=b?{'operation_type':'messenger_'+b['operation'],'data':b}:undefined,T=classifyError(R),U={'operation':'error','error':R};if(T['error_code']!==undefined)U['error_code']=T['error_code'];if(T['retryable']!==undefined)U['retryable']=T['retryable'];if(T['recovery_hint']!==undefined)U['recovery_hint']=T['recovery_hint'];return{'content':[{'type':'text','text':'Error:\x20'+R}],'structuredContent':{'result':U,'semantic':buildDataSemantic(undefined,S,!![],R)}};}}
1
+ import{strictParse,MessengerOperationInputSchema}from'../../schema/index.js';import{watch_conversations,send_message,send_file,watch_messages,export_attachment,pull_messages,generate_wts,verify_wts,sign_wts,wts2html,proof_message,mark_messages_as_viewed,mark_conversation_as_viewed,blacklist,friendslist,guardlist,settings,LocalInfo}from'@wowok/wowok';import{classifyError,buildDataSemantic}from'../../schema/call/semantic.js';import{classifyCommunicationEvidence}from'../../communication/evidence.js';import{goalEngine}from'../../goal/GoalEngine.js';export function normalizeAccountOrMark(a){if(typeof a==='string')return{'name_or_address':a,'local_mark_first':!![]};return a;}export function normalizeOptionalAccountOrMark(a){if(a===undefined||a===null)return undefined;return normalizeAccountOrMark(a);}export function normalizeManyAccountOrMark(a){if(a===undefined||a===null)return undefined;if(Array['isArray'](a))return{'entities':a['map'](b=>typeof b==='string'?{'name_or_address':b,'local_mark_first':!![]}:b),'check_all_founded':!![]};return a;}function communicationEvidencePayload(a,b){const c=b??{};switch(a){case'send_message':case'send_file':{const d=typeof c['messageId']==='string'?c['messageId']:undefined;return{'detail':d?'message\x20'+d:'message\x20sent','data':d?{'message_id':d}:{}};}case'send_required_info':{const e=typeof c['messageId']==='string'?c['messageId']:undefined,f=Array['isArray'](c['sent_fields'])?c['sent_fields']:undefined;return{'detail':'required-info\x20confirmation\x20sent','data':{...e?{'message_id':e}:{},...f?{'sent_fields':f}:{}}};}case'generate_wts':{const g=typeof c['totalMessageCount']==='number'?c['totalMessageCount']:undefined,h=Array['isArray'](c['files'])?c['files']:undefined,i=Array['isArray'](c['htmlFiles'])?c['htmlFiles']:undefined;return{'detail':'WTS\x20evidence\x20packet\x20generated','data':{...g!==undefined?{'message_count':g}:{},...h?{'files':h}:{},...i?{'html_reports':i}:{}}};}case'verify_wts':{return{'detail':'WTS\x20evidence\x20verification','data':{'valid':c['valid']===!![]}};}case'sign_wts':{return{'detail':typeof b==='string'?b:'WTS\x20evidence\x20signed','data':{}};}case'proof_message':{const j=typeof c['proofAddress']==='string'?c['proofAddress']:undefined;return{'detail':j?'proof\x20'+j:'message\x20proofed\x20on-chain','data':j?{'proof_address':j}:{}};}default:return{'detail':a,'data':{}};}}export async function handleMessengerOperation(a){let b;try{b=strictParse(MessengerOperationInputSchema,a,'messenger_operation\x20input');const c=b['operation'];let d;switch(b['operation']){case'watch_conversations':{const g=await watch_conversations(b['filter']);d={'operation':'watch_conversations','result':g};break;}case'send_message':{const h=await send_message(normalizeOptionalAccountOrMark(b['from']),normalizeAccountOrMark(b['to']),b['content'],b['options']);if(h['authRequired']){d={'operation':'send_message','result':h};break;}const i=h,j={...i,'merkleData':i['merkleData']?{'leafIndex':i['merkleData']['leafIndex'],'prevRoot':i['merkleData']['prevRoot'],'newRoot':i['merkleData']['newRoot'],'serverSignature':i['merkleData']['serverSignature'],'serverTimestamp':i['merkleData']['serverTimestamp'],'serverPublicKey':i['merkleData']['serverPublicKey']}:undefined};d={'operation':'send_message','result':j};break;}case'send_file':{const k=await send_file(normalizeOptionalAccountOrMark(b['from']),normalizeAccountOrMark(b['to']),b['filePath'],b['options']),l=k,m={...l,'merkleData':l['merkleData']?{'leafIndex':l['merkleData']['leafIndex'],'prevRoot':l['merkleData']['prevRoot'],'newRoot':l['merkleData']['newRoot'],'serverSignature':l['merkleData']['serverSignature'],'serverTimestamp':l['merkleData']['serverTimestamp'],'serverPublicKey':l['merkleData']['serverPublicKey']}:undefined};d={'operation':'send_file','result':m};break;}case'send_required_info':{let n=b['content'];const o=[];if(!n){const s=await LocalInfo['Instance']()['list'](),t=b['fields'],u=t&&t['length']>0x0?s['filter'](v=>t['includes'](v['name'])):s;if(u['length']===0x0)throw new Error('No\x20LocalInfo\x20fields\x20available.\x20Add\x20private\x20info\x20first\x20via\x20local_info_operation.');n=u['map'](v=>v['name']+':\x20'+v['default'])['join']('\x0a'),o['push'](...u['map'](v=>v['name']));}const p=await send_message(normalizeOptionalAccountOrMark(b['from']),normalizeAccountOrMark(b['to']),n,b['options']),q=p,r={...q,'merkleData':q['merkleData']?{'leafIndex':q['merkleData']['leafIndex'],'prevRoot':q['merkleData']['prevRoot'],'newRoot':q['merkleData']['newRoot'],'serverSignature':q['merkleData']['serverSignature'],'serverTimestamp':q['merkleData']['serverTimestamp'],'serverPublicKey':q['merkleData']['serverPublicKey']}:undefined,'sent_fields':o};d={'operation':'send_required_info','result':r};break;}case'watch_messages':{const v=b['filter']?{...b['filter'],'peerAddress':b['filter']['peerAddress']?normalizeAccountOrMark(b['filter']['peerAddress']):undefined,'account':b['filter']['account']?normalizeOptionalAccountOrMark(b['filter']['account']):undefined}:undefined,w=await watch_messages(v);d={'operation':'watch_messages','result':w};break;}case'save_attachment':{const x=await export_attachment(normalizeOptionalAccountOrMark(b['account']),b['messageId'],{'outputDir':b['outputDir'],'saveAs':b['saveAs']});d={'operation':'save_attachment','result':x};break;}case'generate_wts':{const y=b['params']?{...b['params'],'peerAccount':normalizeAccountOrMark(b['params']['peerAccount']),'myAccount':normalizeOptionalAccountOrMark(b['params']['myAccount'])}:undefined,z=await generate_wts(y);d={'operation':'generate_wts','result':z};break;}case'verify_wts':{const A=await verify_wts(b['wtsFilePath']);d={'operation':'verify_wts','result':A};break;}case'sign_wts':{const B=await sign_wts(b['wtsFilePath'],normalizeOptionalAccountOrMark(b['account']),b['outputPath']);d={'operation':'sign_wts','result':B};break;}case'wts2html':{const C=await wts2html(b['wtsPath'],b['options']);d={'operation':'wts2html','result':C};break;}case'proof_message':{const D=await proof_message(normalizeOptionalAccountOrMark(b['account']),b['messageId'],b['network']);d={'operation':'proof_message','result':D};break;}case'blacklist':{const E={'account':normalizeOptionalAccountOrMark(b['account']),'op':b['blacklist']['op']};'users'in b['blacklist']&&(E['users']=normalizeManyAccountOrMark(b['blacklist']['users']));const F=await blacklist(E);d={'operation':'blacklist','op':b['blacklist']['op'],'result':F['result']};break;}case'friendslist':{const G={'account':normalizeOptionalAccountOrMark(b['account']),'op':b['friendslist']['op']};'users'in b['friendslist']&&(G['users']=normalizeManyAccountOrMark(b['friendslist']['users']));const H=await friendslist(G);d={'operation':'friendslist','op':b['friendslist']['op'],'result':H['result']};break;}case'guardlist':{const I=await guardlist({'account':normalizeOptionalAccountOrMark(b['account']),...b['guardlist']});d={'operation':'guardlist','op':b['guardlist']['op'],'result':I['result']};break;}case'settings':{const J=await settings({'account':normalizeOptionalAccountOrMark(b['account']),...b['settings']});d={'operation':'settings','op':b['settings']['op'],'result':J['result']};break;}case'mark_messages_as_viewed':{const K=await mark_messages_as_viewed(b['messageIds'],normalizeOptionalAccountOrMark(b['account']));d={'operation':'mark_messages_as_viewed','result':K};break;}case'mark_conversation_as_viewed':{const L=await mark_conversation_as_viewed(normalizeAccountOrMark(b['peerAddress']),normalizeOptionalAccountOrMark(b['account']));d={'operation':'mark_conversation_as_viewed','result':L};break;}case'pull_messages':{const M=await pull_messages(normalizeOptionalAccountOrMark(b['account']),b['limit'],{'allAccounts':b['allAccounts'],'accounts':b['accounts']?.['map'](N=>normalizeAccountOrMark(N)),'concurrency':b['concurrency']});d={'operation':'pull_messages','result':M};break;}default:throw new Error('Unknown\x20messenger\x20operation:\x20'+c);}const e=classifyCommunicationEvidence(c),f=b['goal_id'];if(e&&f){const N=d['result'],{detail:O,data:P}=communicationEvidencePayload(c,N);await goalEngine['recordCommunicationEvidence'](f,{'operation':c,'kind':e['kind'],'title':e['title'],'detail':O,'data':P},b['network']??'default');}return{'content':[{'type':'text','text':JSON['stringify'](d)}],'structuredContent':{'result':d}};}catch(Q){const R=Q instanceof Error?Q['message']:String(Q),S=b?{'operation_type':'messenger_'+b['operation'],'data':b}:undefined,T=classifyError(R),U={'operation':'error','error':R};if(T['error_code']!==undefined)U['error_code']=T['error_code'];if(T['retryable']!==undefined)U['retryable']=T['retryable'];if(T['recovery_hint']!==undefined)U['recovery_hint']=T['recovery_hint'];return{'content':[{'type':'text','text':'Error:\x20'+R}],'structuredContent':{'result':U,'semantic':buildDataSemantic(undefined,S,!![],R)}};}}
@@ -0,0 +1,4 @@
1
+ export declare function isResolvableAddressLiteral(value: string): boolean;
2
+ export declare function resolveNameOrAddress(nameOrAddress: string): Promise<string | undefined>;
3
+ export declare function unresolvableNameMessage(what: string, value: string): string;
4
+ export declare function resolveAddress(nameOrAddress: string, what: string): Promise<string>;
@@ -0,0 +1 @@
1
+ import{GetAccountOrMark_Address,LocalMark}from'@wowok/wowok';const OBJECT_ADDRESS_RE=/^0x[0-9a-fA-F]{32,64}$/;export function isResolvableAddressLiteral(a){return OBJECT_ADDRESS_RE['test'](a['trim']());}export async function resolveNameOrAddress(a){const b=a['trim']();if(b['length']===0x0)return undefined;if(OBJECT_ADDRESS_RE['test'](b))return b;const c=await GetAccountOrMark_Address(b);if(c)return c;return await LocalMark['Instance']()['get_address'](b)??undefined;}export function unresolvableNameMessage(a,b){return'Cannot\x20resolve\x20'+a+'\x20\x27'+b+'\x27.\x20'+'It\x20is\x20neither\x20a\x200x\x20address,\x20nor\x20a\x20name\x20known\x20on\x20this\x20device.\x20'+'Two\x20things\x20resolve\x20names:\x20'+'(1)\x20an\x20ACCOUNT\x20name\x20—\x20registered\x20with\x20account_operation\x20and\x20resolvable\x20from\x20any\x20acting\x20account;\x20'+'(2)\x20a\x20LocalMark\x20object\x20name\x20—\x20registered\x20with\x20local_mark_operation,\x20scoped\x20to\x20this\x20device\x20AND\x20the\x20'+'network\x20AND\x20the\x20account\x20that\x20created\x20the\x20object.\x20'+'Either\x20pass\x20the\x200x\x20address\x20directly,\x20or\x20register\x20the\x20name:\x20'+'list\x20what\x20this\x20device\x20already\x20knows\x20with\x20query_toolkit\x20query_type=\x27account_list\x27\x20and\x20\x27local_mark_list\x27.';}export async function resolveAddress(a,b){const c=await resolveNameOrAddress(a);if(!c)throw new Error(unresolvableNameMessage(b,a));return c;}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1 @@
1
+ import{beforeEach,describe,expect,it,vi}from'vitest';const ACCOUNTS={'abnb_guest':'0xaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa','abnb_host':'0xbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb'};let LOCAL_MARKS={};const SYSTEM_SINGLETONS={'0xaaa':'0x0000000000000000000000000000000000000000000000000000000000000aaa'},BUILTIN_IDS=new Set(['0x5','0xaaa']);function expandBuiltin(a){if(!BUILTIN_IDS['has'](a['toLowerCase']()))return undefined;return SYSTEM_SINGLETONS[a['toLowerCase']()]??'0x'+a['slice'](0x2)['padStart'](0x40,'0');}function resetMarks(){LOCAL_MARKS={'abnb_host/testnet':{'abnb_host_service':'0xcccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccccc'}};}vi['mock']('@wowok/wowok',()=>({'GetAccountOrMark_Address':async a=>{const b=typeof a==='string'?a:a?.['name_or_address'];if(!b)return undefined;if(SYSTEM_SINGLETONS[b['toLowerCase']()])return SYSTEM_SINGLETONS[b['toLowerCase']()];if(/^0x[0-9a-fA-F]{32,64}$/['test'](b))return b;const c=ACCOUNTS[b['toLowerCase']()];if(c)return c;for(const d of Object['values'](LOCAL_MARKS)){if(d[b['toLowerCase']()])return d[b['toLowerCase']()];}return undefined;},'LocalMark':{'Instance':()=>({'get_address':async a=>{if(!a)return undefined;return expandBuiltin(a)??undefined;}})}}));const {isResolvableAddressLiteral,resolveNameOrAddress,resolveAddress,unresolvableNameMessage}=await import('./name-resolution.js');beforeEach(()=>{resetMarks();}),describe('C-8:\x20account\x20names\x20resolve\x20regardless\x20of\x20the\x20acting\x20account',()=>{it('resolves\x20a\x20valid\x20local\x20ACCOUNT\x20name\x20(the\x20reported\x20radar_account\x20failure)',async()=>{expect(await resolveNameOrAddress('abnb_guest'))['toBe'](ACCOUNTS['abnb_guest']);}),it('resolves\x20the\x20same\x20account\x20name\x20for\x20every\x20acting\x20account',async()=>{const a=await resolveNameOrAddress('abnb_guest');LOCAL_MARKS={};const b=await resolveNameOrAddress('abnb_guest');expect(b)['toBe'](a),expect(b)['toBe'](ACCOUNTS['abnb_guest']);}),it('still\x20resolves\x20a\x20full\x200x\x20address\x20unchanged\x20(no\x20lookup\x20at\x20all)',async()=>{const a='0xdddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddddd';expect(await resolveNameOrAddress(a))['toBe'](a);}),it('still\x20resolves\x20a\x20system\x20shorthand\x20(0xaaa)',async()=>{expect(await resolveNameOrAddress('0xaaa'))['toBe'](SYSTEM_SINGLETONS['0xaaa']);}),it('still\x20resolves\x20a\x20LocalMark\x20object\x20name\x20(the\x20caller-scoped\x20plane\x20is\x20kept)',async()=>{expect(await resolveNameOrAddress('abnb_host_service'))['toBe'](LOCAL_MARKS['abnb_host/testnet']['abnb_host_service']);}),it('returns\x20undefined\x20for\x20a\x20name\x20no\x20plane\x20knows',async()=>{expect(await resolveNameOrAddress('nobody_here'))['toBeUndefined']();}),it('returns\x20undefined\x20for\x20empty\x20/\x20whitespace\x20input',async()=>{expect(await resolveNameOrAddress(''))['toBeUndefined'](),expect(await resolveNameOrAddress('\x20\x20\x20'))['toBeUndefined']();});}),describe('C-8:\x20the\x20failure\x20message\x20names\x20the\x20concrete\x20alternatives',()=>{it('does\x20not\x20dead-end\x20—\x20it\x20names\x20both\x20name\x20planes\x20and\x20how\x20to\x20register',()=>{const a=unresolvableNameMessage('radar_account','ghost_account');expect(a)['toContain']('ghost_account'),expect(a)['toContain']('radar_account'),expect(a)['toContain']('account_operation'),expect(a)['toContain']('local_mark_operation'),expect(a)['toContain']('0x\x20address'),expect(a)['toContain']('account_list'),expect(a)['toContain']('local_mark_list');}),it('explains\x20WHY\x20a\x20LocalMark\x20name\x20can\x20be\x20invisible\x20(scoping),\x20not\x20just\x20that\x20it\x20is',()=>{const a=unresolvableNameMessage('service','some_service');expect(a)['toMatch'](/network/i),expect(a)['toMatch'](/account that created/i);}),it('throws\x20an\x20actionable\x20error\x20from\x20resolveAddress\x20for\x20an\x20unknown\x20name',async()=>{await expect(resolveAddress('ghost_account','radar_account'))['rejects']['toThrow'](/account_operation/);}),it('throws\x20for\x20an\x20unknown\x20name\x20in\x20every\x20caller-facing\x20field\x20label',async()=>{for(const a of['radar_account','service','machine','object_address','service_address']){await expect(resolveAddress('ghost',a))['rejects']['toThrow'](new RegExp(a));}});}),describe('C-8:\x20isResolvableAddressLiteral',()=>{it('accepts\x20full\x20object\x20addresses\x20only',()=>{expect(isResolvableAddressLiteral('0x'+'a'['repeat'](0x40)))['toBe'](!![]),expect(isResolvableAddressLiteral('0xaaa'))['toBe'](![]),expect(isResolvableAddressLiteral('abnb_guest'))['toBe'](![]);});}),describe('C-8:\x20no\x20resolver\x20bypasses\x20the\x20canonical\x20name\x20resolution',()=>{const a=['src/playbooks/service-build/participation-radar.ts','src/playbooks/service-build/relationship-profile.ts','src/playbooks/service-build/object-panorama.ts','src/playbooks/service-build/machine-panorama.ts','src/playbooks/service-build/service-panorama.ts','src/playbooks/service-build/service-quote.ts','src/review/index.ts'];it['each'](a)('%s\x20does\x20not\x20hand-roll\x20a\x20LocalMark-only\x20name\x20lookup',async b=>{const {readFileSync:c}=await import('node:fs'),{fileURLToPath:d}=await import('node:url'),{dirname:e,resolve:f}=await import('node:path'),g=f(e(d(import.meta.url)),'../../..'),h=c(f(g,b),'utf8');expect(h)['not']['toContain']('no\x20LocalMark\x20entry\x20found'),expect(h)['toContain']('name-resolution.js');});});