wowok_agent 2.1.39 → 2.2.0

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.
package/dist/index.js CHANGED
@@ -1,2 +1,1238 @@
1
1
  #!/usr/bin/env node
2
- import{z}from'zod';import{McpServer}from'@modelcontextprotocol/sdk/server/mcp.js';import{StdioServerTransport}from'@modelcontextprotocol/sdk/server/stdio.js';import{readFileSync}from'fs';import{resolve}from'path';const packageJson=JSON['parse'](readFileSync(new URL('../package.json',import.meta.url),'utf-8'));import{CallService_DataSchema,CallMachine_DataSchema,MachineNode2File_InputSchema,MachineNode2File_OutputWrappedSchema,CallProgress_DataSchema,CallPermission_DataSchema,CallGuard_DataSchema,Guard2File_InputSchema,Guard2File_OutputWrappedSchema,CallArbitration_DataSchema,CallRepository_DataSchema,CallContact_DataSchema,CallTreasury_DataSchema,CallReward_DataSchema,CallAllocation_DataSchema,CallPersonal_DataSchema,CallPayment_DataSchema,CallDemand_DataSchema,CallOrder_DataSchema,CallEnvSchema,SubmissionCallSchema,strictParse,CallOutputSchema,handleCallResult,createServerConfig,createCapabilitiesConfig,createToolMeta,transformSubmission,getEnvConfig,WipGenerationOptionsSchema,WipToHtmlOptionsSchema,TokenDataFilterSchema,LocalInfoFilterSchema,LocalMarkFilterSchema,AccountFilterSchema,TokenTypeSchema,OnchainEventsInputSchema,OnchainEventsResultSchema,ProtocolInfoQuerySchema,ProtocolInfoResultSchema,WatchQueryOperationsResultSchema,NameOrAddressSchema,AccountOrMark_AddressSchema,ObjectTypeSchema,AccountOperationOutputWrappedSchema,LocalMarkOperationOutputWrappedSchema,LocalInfoOperationOutputWrappedSchema,WipOperationOutputSchema,MessengerOperationOutputSchema,AccountOperationSchema,LocalMarkOperationSchema,LocalInfoOperationSchema,parseMachineNodesFromText,formatNodeErrors as a0a,MessengerOperationInputSchema}from'./schema/index.js';import{CallService,CallMachine,CallProgress,CallPermission,CallGuard,CallArbitration,CallRepository,CallContact,CallTreasury,CallReward,CallAllocation,CallPersonal,CallPayment,CallDemand,CallOrder,gen_passport,guard2file,parseGuardFile,formatGuardParseErrors,machineNode2file,generateNodeComments,generate_wip,verify_wip,sign_wip,wip2html,account_operation,local_mark_operation,local_info_operation,watch_conversations,send_message,send_file,watch_messages,extract_zip_messages,generate_wts,verify_wts,sign_wts,wts2html,proof_message,mark_messages_as_viewed,mark_conversation_as_viewed,query_local_mark_list,query_account_list,query_local_info_list,query_local_token_list,query_account,query_personal,query_objects,query_table,queryProtocolInfo,query_received,queryTableItem_RepositoryData,queryTableItem_PermissionPerm,queryTableItem_RewardRecord,queryTableItem_DemandPresenter,queryTableItem_TreasuryHistory,queryTableItem_MachineNode,queryTableItem_ProgressHistory,queryTableItem_AddressMark,queryTableItem_EntityRegistrar,queryTableItem_EntityLinker,query_events,blacklist,friendslist,guardlist,settings,AmountType}from'wowok';const SERVER_DESCRIPTION='WoWok\x20MCP\x20Server\x20-\x20Making\x20It\x20Easy\x20for\x20AI\x20Agents\x20to\x20Communicate,\x20Collaborate,\x20Trade,\x20and\x20Trust.\x0a\x0a##\x20Token\x20System\x20Overview\x0a\x0a###\x20Default\x20Platform\x20Token:\x20WOW\x0a-\x20Token\x20Type:\x200x2::wow::WOW\x0a-\x20Precision:\x201_000_000_000\x20(9\x20decimal\x20places)\x0a-\x20This\x20is\x20the\x20default\x20token\x20for\x20all\x20operations\x20unless\x20specified\x20otherwise\x0a\x0a###\x20Multi-Token\x20Support\x0aThe\x20platform\x20supports\x20ANY\x20token\x20(e.g.,\x20USDT,\x20USDC,\x20custom\x20tokens).\x20To\x20use\x20non-WOW\x20tokens:\x0a1.\x20Use\x20query_toolkit\x20with\x20query_type=\x27token_list\x27\x20to\x20query\x20available\x20tokens\x20and\x20their\x20precision\x20info\x0a2.\x20Use\x20the\x20token\x27s\x20full\x20type\x20string\x20(e.g.,\x20\x270x2::usdt::USDT\x27)\x20in\x20token_type\x20parameter\x0a3.\x20Each\x20token\x20has\x20its\x20own\x20precision\x20-\x20always\x20verify\x20before\x20operations\x0a\x0a###\x20Token\x20Precision\x20Handling\x0aDifferent\x20tokens\x20have\x20different\x20precisions.\x20ALWAYS\x20query\x20to\x20verify:\x0a-\x20WOW\x20(default):\x201_000_000_000\x20(9\x20decimals)\x0a-\x20Other\x20tokens:\x20Use\x20query_toolkit\x20with\x20query_type=\x27token_list\x27\x20to\x20get\x20actual\x20precision\x0a-\x20Never\x20assume\x20a\x20token\x27s\x20decimal\x20places\x20-\x20always\x20query\x20first\x0a\x0a##\x20CRITICAL:\x20Token\x20Amount\x20Handling\x0a\x0a###\x20Amount\x20Input\x20Rules\x0a1.\x20WITH\x20currency\x20unit\x20(e.g.,\x20\x272WOW\x27,\x20\x2710.5WOW\x27,\x20\x27100USDT\x27):\x0a\x20\x20\x20-\x20Auto-converted\x20using\x20token\x27s\x20precision:\x202WOW\x20->\x202_000_000_000\x0a\x20\x20\x20-\x20Use\x20for:\x20All\x20on-chain\x20token\x20operations\x0a\x20\x20\x20-\x20MUST\x20match\x20the\x20token_type\x20parameter\x0a\x0a2.\x20WITHOUT\x20currency\x20unit\x20(e.g.,\x20\x272\x27,\x20\x27100\x27):\x0a\x20\x20\x20-\x20Used\x20as-is:\x202\x20->\x202\x0a\x20\x20\x20-\x20Use\x20for:\x20Regular\x20numeric\x20parameters\x20(counts,\x20indices,\x20etc.)\x0a\x0a###\x20Multi-Token\x20Operation\x20Examples\x0a-\x20Create\x20USDT-priced\x20Service:\x20token_type=\x270x2::usdt::USDT\x27,\x20amount=\x27100USDT\x27\x0a-\x20Allocate\x20USDC\x20rewards:\x20token_type=\x270x2::usdc::USDC\x27,\x20amount=\x27500USDC\x27\x0a-\x20WOW\x20remains\x20default:\x20omit\x20token_type\x20or\x20use\x20\x270x2::wow::WOW\x27\x0a\x0a###\x20Security\x20Warning\x0aToken\x20amounts\x20are\x20HIGHLY\x20SENSITIVE.\x20Always:\x0a-\x20Confirm\x20user\x27s\x20intent\x20before\x20executing\x20transfers\x0a-\x20Verify\x20token\x20type\x20and\x20amount\x20format\x20(with/without\x20unit)\x0a-\x20Query\x20token\x20precision\x20if\x20unsure\x0a-\x20Double-check\x20large\x20amount\x20transactions\x0a-\x20Never\x20assume\x20decimal\x20places\x20-\x20use\x20explicit\x20token\x20unit\x0a\x0a##\x20Tool\x20Selection\x20Guide\x0a\x0a|\x20User\x20Intent\x20|\x20Correct\x20Tool\x20|\x20Wrong\x20Tool\x20(Avoid)\x20|\x0a|------------|--------------|-------------------|\x0a|\x20Create\x20service\x20listing\x20|\x20onchain_operations\x20(service)\x20|\x20query_toolkit\x20|\x0a|\x20Send\x20coins\x20to\x20address\x20|\x20onchain_operations\x20(payment)\x20|\x20account_operation\x20|\x0a|\x20Check\x20my\x20balance\x20|\x20query_toolkit\x20(account_balance)\x20|\x20onchain_operations\x20|\x0a|\x20Manage\x20local\x20wallet\x20|\x20account_operation\x20|\x20onchain_operations\x20|\x0a|\x20Export\x20Guard\x20for\x20edit\x20|\x20guard2file\x20|\x20query_toolkit\x20|\x0a|\x20Send/Watch\x20encrypted\x20message\x20|\x20messenger_operation\x20|\x20onchain_operations\x20|\x0a|\x20Create\x20workflow\x20template\x20|\x20onchain_operations\x20(machine)\x20|\x20wip_file\x20|\x0a|\x20Store\x20my\x20phone\x20number\x20|\x20local_info_operation\x20|\x20onchain_operations\x20|\x0a|\x20Buy\x20service\x20(create\x20order)\x20|\x20onchain_operations\x20(order)\x20|\x20onchain_operations\x20(service)\x20|\x0a|\x20Manage\x20my\x20orders\x20|\x20onchain_operations\x20(order)\x20|\x20query_toolkit\x20|\x0a|\x20Apply\x20for\x20arbitration\x20|\x20onchain_operations\x20(order)\x20|\x20onchain_operations\x20(arbitration)\x20|\x0a|\x20Create\x20reward\x20pool\x20for\x20marketing\x20|\x20onchain_operations\x20(reward)\x20|\x20onchain_operations\x20(treasury)\x20|\x0a|\x20Claim\x20rewards\x20from\x20pool\x20|\x20onchain_operations\x20(reward)\x20|\x20query_toolkit\x20|\x0a|\x20Create\x20fund\x20allocation\x20plan\x20|\x20onchain_operations\x20(allocation)\x20|\x20onchain_operations\x20(treasury)\x20|\x0a|\x20Execute\x20fund\x20distribution\x20|\x20onchain_operations\x20(allocation)\x20|\x20onchain_operations\x20(payment)\x20|\x0a|\x20Post\x20service\x20demand\x20with\x20reward\x20|\x20onchain_operations\x20(demand)\x20|\x20onchain_operations\x20(service)\x20|\x0a|\x20Submit\x20solution\x20for\x20demand\x20|\x20onchain_operations\x20(demand)\x20|\x20onchain_operations\x20(order)\x20|\x0a|\x20Create\x20team\x20treasury\x20|\x20onchain_operations\x20(treasury)\x20|\x20onchain_operations\x20(allocation)\x20|\x0a|\x20Deposit/Withdraw\x20from\x20treasury\x20|\x20onchain_operations\x20(treasury)\x20|\x20onchain_operations\x20(payment)\x20|\x0a|\x20Create\x20access\x20control\x20rules\x20|\x20onchain_operations\x20(permission)\x20|\x20onchain_operations\x20(guard)\x20|\x0a|\x20Create\x20validation\x20rules\x20(Guard)\x20|\x20onchain_operations\x20(guard)\x20|\x20onchain_operations\x20(permission)\x20|\x0a|\x20Export\x20Guard\x20for\x20editing\x20|\x20guard2file\x20|\x20query_toolkit\x20|\x0a|\x20Export\x20Machine\x20nodes\x20for\x20editing\x20|\x20machineNode2file\x20|\x20query_toolkit\x20|\x0a|\x20Query\x20token\x20list\x20and\x20precision\x20|\x20query_toolkit\x20(token_list)\x20|\x20wowok_buildin_info\x20|\x0a|\x20Watch\x20on-chain\x20events\x20|\x20onchain_events\x20|\x20query_toolkit\x20|\x0a|\x20Generate\x20WIP\x20promise\x20file\x20|\x20wip_file\x20(generate)\x20|\x20messenger_operation\x20|\x0a|\x20Sign\x20WIP\x20file\x20|\x20wip_file\x20(sign)\x20|\x20account_operation\x20(signData)\x20|\x0a|\x20Verify\x20WIP\x20file\x20integrity\x20|\x20wip_file\x20(verify)\x20|\x20query_toolkit\x20|\x0a|\x20Send\x20encrypted\x20file\x20via\x20messenger\x20|\x20messenger_operation\x20(send_file)\x20|\x20wip_file\x20|\x0a|\x20Generate\x20witness\x20timestamp\x20(WTS)\x20|\x20messenger_operation\x20(generate_wts)\x20|\x20wip_file\x20|\x0a|\x20Query\x20protocol\x20constants\x20|\x20wowok_buildin_info\x20|\x20query_toolkit\x20|\x0a|\x20Get\x20documentation\x20URL\x20|\x20documents_and_learn\x20|\x20wowok_buildin_info\x20|\x0a\x0a##\x20Local\x20vs\x20On-chain\x20Operations\x0a\x0a###\x20LOCAL\x20ONLY\x20(Never\x20touch\x20blockchain):\x0a-\x20account_operation\x0a-\x20local_mark_operation\x0a-\x20local_info_operation\x0a\x0a###\x20ON-CHAIN\x20(Blockchain\x20transactions):\x0a-\x20onchain_operations\x0a-\x20messenger_operation\x20(some\x20operations)\x0a-\x20wip_file\x20(sign\x20operation)\x0a\x0a###\x20QUERY\x20(Read-only):\x0a-\x20query_toolkit\x0a-\x20onchain_events\x0a-\x20wowok_buildin_info\x0a-\x20documents_and_learn\x0a-\x20guard2file\x0a-\x20machineNode2file\x0a',server=new McpServer(createServerConfig(packageJson,SERVER_DESCRIPTION),createCapabilitiesConfig());function convertAmountType(a){if(typeof a==='number')return a;const b=a['toUpperCase']();if(b==='GUARDU64IDENTIFIER'||b==='GUARD_U64_IDENTIFIER')return AmountType['GuardU64Identifier'];if(b==='FIXED')return AmountType['Fixed'];return AmountType['Fixed'];}function transformRewardData(a){if(!a)return a;const b={...a};return b['guard_add']&&Array['isArray'](b['guard_add'])&&(b['guard_add']=b['guard_add']['map'](c=>{if(c['amount']&&typeof c['amount']['type']==='string')return{...c,'amount':{...c['amount'],'type':convertAmountType(c['amount']['type'])}};return c;})),b;}const OnchainOperationsSchema=z['discriminatedUnion']('operation_type',[z['object']({'operation_type':z['literal']('service'),'data':CallService_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('đŸĒ\x20Service\x20Object:\x20Create\x20and\x20manage\x20product/service\x20listings\x20with\x20transparent\x20promises,\x20bind\x20workflow\x20templates\x20to\x20order\x20processing,\x20set\x20pricing,\x20issue\x20discount\x20coupons\x20to\x20customers,\x20and\x20establish\x20quality\x20standards,\x20etc..'),z['object']({'operation_type':z['literal']('machine'),'data':CallMachine_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('âš™ī¸\x20Machine\x20Object:\x20Design\x20and\x20deploy\x20automated\x20workflow\x20templates\x20(Machines)\x20that\x20define\x20how\x20services\x20are\x20delivered,\x20etc..'),z['object']({'operation_type':z['literal']('progress'),'data':CallProgress_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('📊\x20Progress\x20Object:\x20Track\x20and\x20manage\x20active\x20workflows\x20in\x20real-time.'),z['object']({'operation_type':z['literal']('repository'),'data':CallRepository_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('đŸ“Ļ\x20Repository\x20Object:\x20Read/write\x20database\x20with\x20consensus\x20field\x20+\x20address\x20as\x20key,\x20strongly-typed\x20data\x20as\x20value.'),z['object']({'operation_type':z['literal']('arbitration'),'data':CallArbitration_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('âš–ī¸\x20Arbitration\x20Object:\x20Access\x20a\x20transparent\x20on-chain\x20arbitration\x20system\x20for\x20resolving\x20order\x20conflicts.'),z['object']({'operation_type':z['literal']('contact'),'data':CallContact_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('đŸ’Ŧ\x20Contact\x20Object:\x20Manage\x20on-chain\x20instant\x20messaging\x20contact\x20profiles.'),z['object']({'operation_type':z['literal']('treasury'),'data':CallTreasury_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('💰\x20Treasury\x20Object:\x20Create\x20and\x20manage\x20treasury\x20for\x20team\x20funds\x20with\x20deposit/withdrawal\x20rules,\x20etc..'),z['object']({'operation_type':z['literal']('reward'),'data':CallReward_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('🎁\x20Reward\x20Object:\x20Create\x20reward\x20pools\x20and\x20set\x20claim\x20conditions\x20by\x20Guard\x20verification.'),z['object']({'operation_type':z['literal']('allocation'),'data':CallAllocation_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('📤\x20Allocation\x20Object:\x20Create\x20distribution\x20plans\x20to\x20auto-distribute\x20funds\x20to\x20multiple\x20recipients.'),z['object']({'operation_type':z['literal']('permission'),'data':CallPermission_DataSchema,'env':CallEnvSchema['optional']()})['describe']('🔐\x20Permission\x20Object:\x20Define\x20who\x20can\x20perform\x20which\x20operations\x20on\x20WoWok\x20objects.\x20Important\x20Note:\x20If\x20needed,\x20you\x20should\x20first\x20query\x20\x27guard\x20instructions\x27\x20through\x20the\x20\x27wowok_buildin_info\x27\x20tool.'),z['object']({'operation_type':z['literal']('guard'),'data':CallGuard_DataSchema,'env':CallEnvSchema['optional']()})['describe']('đŸ›Ąī¸\x20Guard\x20Object:\x20Create\x20immutable\x20programmable\x20validation\x20rules\x20that\x20return\x20boolean\x20results.\x20Set\x20\x27namedNew\x27\x20to\x20name\x20the\x20new\x20Guard.\x20Use\x20root.type=\x27node\x27\x20for\x20direct\x20node\x20tree\x20or\x20root.type=\x27file\x27\x20to\x20load\x20from\x20file.\x20Use\x20\x27wowok_buildin_info\x27\x20tool\x20with\x20query=\x27guard\x20instructions\x27\x20for\x20all\x20available\x20operations.'),z['object']({'operation_type':z['literal']('personal'),'data':CallPersonal_DataSchema,'env':CallEnvSchema['optional']()})['describe']('🆔\x20Public\x20Identity\x20Profile:\x20Establish\x20and\x20manage\x20your\x20on-chain\x20public\x20identity.\x20âš ī¸\x20CRITICAL:\x20Everything\x20here\x20is\x20PERMANENTLY\x20PUBLIC\x20on\x20the\x20blockchain!'),z['object']({'operation_type':z['literal']('payment'),'data':CallPayment_DataSchema,'env':CallEnvSchema['optional']()})['describe']('💰\x20Payment\x20Object:\x20Send\x20instant,\x20irreversible\x20coin\x20transfers\x20to\x20any\x20wallet\x20address.'),z['object']({'operation_type':z['literal']('demand'),'data':CallDemand_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('đŸŽ¯\x20Demand\x20Object:\x20Post\x20service\x20requests\x20with\x20reward\x20pools\x20on-chain.'),z['object']({'operation_type':z['literal']('order'),'data':CallOrder_DataSchema,'env':CallEnvSchema['optional'](),'submission':SubmissionCallSchema['optional']()})['describe']('đŸ“Ļ\x20Order\x20Object:\x20Manage\x20the\x20order\x20lifecycle,\x20Including\x20operating\x20order\x20arbitration\x20(Arb\x20Object\x20associated\x20with\x20the\x20order),\x20advancing\x20progress\x20(Progress\x20Object\x20associated\x20with\x20the\x20order),\x20extracting\x20order\x20refunds/payments,\x20setting\x20agents,\x20etc.'),z['object']({'operation_type':z['literal']('gen_passport'),'guard':z['string']()['describe']('Guard\x20object\x20ID\x20to\x20verify\x20and\x20generate\x20passport\x20from'),'info':SubmissionCallSchema['optional']()['describe']('Optional\x20submission\x20data.\x20If\x20not\x20provided,\x20will\x20attempt\x20to\x20get\x20existing\x20submissions\x20from\x20the\x20guard.'),'env':CallEnvSchema['optional']()})['describe']('🛂\x20Generate\x20Verified\x20Passport\x20Object:\x20Create\x20immutable\x20verified\x20credentials\x20after\x20Guard\x20validation\x20passes.')]),WipOperationsSchema=z['discriminatedUnion']('type',[z['object']({'type':z['literal']('generate'),'options':WipGenerationOptionsSchema['describe']('WIP\x20generation\x20options'),'outputPath':z['string']()['describe']('Output\x20file\x20path\x20(.wip\x20file).\x20If\x20file\x20exists,\x20it\x20will\x20be\x20overwritten')})['describe']('Generate\x20WIP\x20file\x20from\x20markdown\x20text\x20and\x20optional\x20images'),z['object']({'type':z['literal']('verify'),'wipFilePath':z['string']()['describe']('WIP\x20file\x20path\x20to\x20verify.\x20Supports:\x201)\x20Local\x20file\x20path\x20(e.g.,\x20\x27/path/to/file.wip\x27,\x20\x27C:\x5cUsers\x5cname\x5cdoc.wip\x27),\x202)\x20Network\x20URL\x20(e.g.,\x20\x27https://example.com/doc.wip\x27,\x20\x27http://site.com/file.wip\x27),\x203)\x20Data\x20URL\x20(e.g.,\x20\x27data:application/json;base64,eyJ3aXAiOi...\x27)'),'hash_equal':z['string']()['optional']()['describe']('Optional\x20expected\x20hash\x20value.\x20If\x20provided,\x20the\x20function\x20will\x20first\x20verify\x20if\x20the\x20file\x27s\x20hash\x20matches\x20this\x20value.\x20If\x20not\x20matched,\x20returns\x20hash\x20mismatch\x20error.'),'requireSignature':z['boolean']()['optional']()['describe']('Optional\x20flag\x20to\x20require\x20digital\x20signature.\x20If\x20true,\x20verification\x20will\x20fail\x20if\x20WIP\x20file\x20has\x20no\x20signature')})['describe']('Verify\x20WIP\x20file\x20integrity\x20and\x20signatures'),z['object']({'type':z['literal']('sign'),'wipFilePath':z['string']()['describe']('WIP\x20file\x20path\x20to\x20sign.\x20Supports:\x201)\x20Local\x20file\x20path\x20(e.g.,\x20\x27/path/to/file.wip\x27),\x202)\x20Network\x20URL\x20(e.g.,\x20\x27https://example.com/doc.wip\x27).\x20The\x20file\x20will\x20be\x20loaded,\x20validated,\x20and\x20signed'),'account':z['string']()['optional']()['describe']('Signing\x20account\x20(account\x20name\x20or\x20address).\x20If\x20not\x20specified,\x20uses\x20default\x20account'),'outputPath':z['string']()['optional']()['describe']('Output\x20file\x20path.\x20If\x20not\x20specified,\x20adds\x20\x27signed_\x27\x20prefix\x20to\x20original\x20file\x20name\x20(e.g.,\x20\x27doc.wip\x27\x20becomes\x20\x27signed_doc.wip\x27)')})['describe']('Sign\x20WIP\x20file\x20with\x20account'),z['object']({'type':z['literal']('wip2html'),'wipPath':z['string']()['describe']('WIP\x20file\x20path\x20or\x20directory\x20path.\x20Supports:\x201)\x20Single\x20WIP\x20file\x20(e.g.,\x20\x27/path/to/file.wip\x27),\x202)\x20Directory\x20containing\x20.wip\x20files\x20(e.g.,\x20\x27/path/to/wips/\x27),\x203)\x20Network\x20URL\x20(e.g.,\x20\x27https://example.com/doc.wip\x27).\x20When\x20directory\x20is\x20provided,\x20all\x20.wip\x20files\x20in\x20the\x20directory\x20will\x20be\x20converted\x20to\x20HTML'),'options':WipToHtmlOptionsSchema['optional']()['describe']('Conversion\x20options')})['describe']('Convert\x20WIP\x20file\x20to\x20HTML\x20format')]),WatchQueryOperationsSchema=z['discriminatedUnion']('query_type',[z['object']({'query_type':z['literal']('local_mark_list'),'filter':LocalMarkFilterSchema['optional']()['describe']('Local\x20mark\x20filter')})['describe']('Query\x20local\x20ID/USER\x20address\x20book\x20with\x20optional\x20filter'),z['object']({'query_type':z['literal']('account_list'),'filter':AccountFilterSchema['optional']()['describe']('Account\x20filter')})['describe']('Query\x20account\x20list\x20with\x20optional\x20filter'),z['object']({'query_type':z['literal']('local_info_list'),'filter':LocalInfoFilterSchema['optional']()['describe']('Local\x20info\x20filter')})['describe']('Query\x20local\x20info\x20list\x20with\x20optional\x20filter'),z['object']({'query_type':z['literal']('token_list'),'filter':TokenDataFilterSchema['optional']()})['describe']('Query\x20token\x20list\x20with\x20optional\x20filter'),z['object']({'query_type':z['literal']('account_balance'),'name_or_address':NameOrAddressSchema['optional']()['describe']('Account\x20name\x20or\x20address.\x20Use\x20empty\x20string\x20\x27\x27\x20for\x20the\x20default\x20account.\x20Defaults\x20to\x20\x27\x27\x20if\x20omitted.'),'token_type':TokenTypeSchema['optional']()['describe']('Token\x20type;\x20default\x20token\x20type\x20is\x200x2::wow::WOW')})['describe']('Query\x20account\x20balance\x20or\x20coin\x20objects\x20by\x20the\x20token\x20type'),z['object']({'query_type':z['literal']('onchain_personal_profile'),'account':NameOrAddressSchema['optional']()['describe']('Account\x20name\x20or\x20ID\x20to\x20query.\x20Use\x20empty\x20string\x20\x27\x27\x20for\x20the\x20default\x20account.')})['describe']('Query\x20PUBLIC\x20on-chain\x20personal\x20profile\x20for\x20any\x20account\x20address'),z['object']({'query_type':z['literal']('onchain_objects'),'objects':z['array'](NameOrAddressSchema)['describe']('List\x20of\x20object\x20IDs\x20to\x20query')})['describe']('Query\x20on-chain\x20objects'),z['object']({'query_type':z['literal']('onchain_table'),'parent':NameOrAddressSchema,'object_type':ObjectTypeSchema})['describe']('Query\x20on-chain\x20table\x20data\x20of\x20the\x20specified\x20object'),z['object']({'query_type':z['literal']('onchain_table_item_repository_data'),'parent':NameOrAddressSchema['describe']('Parent\x20object\x20ID\x20of\x20the\x20data\x20table\x20to\x20query'),'name':z['string']()['describe']('Name\x20of\x20the\x20record\x20to\x20query'),'entity':z['union']([AccountOrMark_AddressSchema,z['number']()])['describe']('ID\x20or\x20address\x20of\x20the\x20entity;\x20or\x20address\x20that\x20number\x20is\x20casted\x20to')})['describe']('Query\x20repository\x20data\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_table_item_permission_perm'),'parent':NameOrAddressSchema['describe']('Parent\x20object\x20ID\x20of\x20the\x20data\x20table\x20to\x20query'),'address':z['union']([AccountOrMark_AddressSchema,z['string']()])['describe']('User\x20ID\x20or\x20address,\x20or\x20Guard\x20ID\x20in\x20the\x20permission\x20perm\x20table')})['describe']('Query\x20permission\x20perm\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_table_item_entity_registrar'),'address':z['union']([AccountOrMark_AddressSchema,z['string']()])['describe']('User\x20ID\x20or\x20address\x20of\x20the\x20entity')})['describe']('Query\x20entity\x20registrar\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_table_item_entity_linker'),'address':z['union']([AccountOrMark_AddressSchema,z['string']()])['describe']('ID\x20or\x20address\x20that\x20the\x20registrar\x20votes\x20are\x20attached\x20to')})['describe']('Query\x20entity\x20linker\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_table_item_reward_record'),'parent':NameOrAddressSchema['describe']('Parent\x20object\x20ID\x20of\x20the\x20data\x20table\x20to\x20query'),'address':AccountOrMark_AddressSchema['describe']('User\x20ID\x20or\x20address\x20that\x20claims\x20the\x20reward')})['describe']('Query\x20reward\x20record\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_table_item_demand_presenter'),'parent':NameOrAddressSchema['describe']('Parent\x20object\x20ID\x20of\x20the\x20data\x20table\x20to\x20query'),'address':AccountOrMark_AddressSchema['describe']('User\x20ID\x20or\x20address\x20of\x20the\x20Demand\x20presenter')})['describe']('Query\x20demand\x20presenter\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_table_item_treasury_history'),'parent':NameOrAddressSchema['describe']('Parent\x20object\x20ID\x20of\x20the\x20data\x20table\x20to\x20query'),'address':AccountOrMark_AddressSchema['describe']('ID\x20of\x20the\x20payment\x20that\x20the\x20treasury\x20record\x20is\x20attached\x20to')})['describe']('Query\x20treasury\x20record\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_table_item_machine_node'),'parent':NameOrAddressSchema['describe']('Parent\x20object\x20ID\x20of\x20the\x20data\x20table\x20to\x20query'),'key':z['string']()['describe']('String\x20key\x20of\x20the\x20node\x20name\x20to\x20query')})['describe']('Query\x20machine\x20node\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_table_item_progress_history'),'parent':NameOrAddressSchema['describe']('Parent\x20object\x20ID\x20of\x20the\x20data\x20table\x20to\x20query'),'u64':z['union']([z['number'](),z['string']()])['describe']('U64\x20value\x20of\x20the\x20record\x20to\x20query')})['describe']('Query\x20progress\x20history\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_table_item_address_mark'),'parent':NameOrAddressSchema['describe']('Parent\x20object\x20ID\x20of\x20the\x20data\x20table\x20to\x20query'),'address':AccountOrMark_AddressSchema['describe']('ID\x20or\x20address\x20that\x20the\x20mark\x20name\x20and\x20tags\x20are\x20attached\x20to')})['describe']('Query\x20address\x20mark\x20table\x20item'),z['object']({'query_type':z['literal']('onchain_received'),'object':z['string']()['describe']('Object\x20ID\x20to\x20query'),'all_type':z['boolean']()['optional']()['describe']('Whether\x20to\x20query\x20all\x20types\x20of\x20received\x20objects')})['describe']('Query\x20on-chain\x20received\x20balance,\x20payments,\x20and\x20NFTs')]);async function handleOnchainOperations(a){console['log']('===\x20handleOnchainOperations\x20==='),console['log']('args:',JSON['stringify'](a,null,0x2));try{const b=strictParse(OnchainOperationsSchema,a,'onchain_operations\x20input');console['log']('validated:',JSON['stringify'](b,null,0x2));const c=getEnvConfig(b['env']);switch(b['operation_type']){case'service':{const d=new CallService(b['data']),f=b['submission']?await d['call_with_submission'](c,await transformSubmission(b['submission'])):await d['call'](c);return handleCallResult(f);}case'machine':{if(b['data']['node']&&typeof b['data']['node']==='object'&&'json_or_markdown_file'in b['data']['node']){const i=b['data']['node']['json_or_markdown_file'];let j;try{const l=resolve(i);j=readFileSync(l,'utf-8');}catch(m){throw new Error('Failed\x20to\x20read\x20file\x20\x27'+i+'\x27:\x20'+m['message']);}const k=parseMachineNodesFromText(j);if(!k['success']){const n=a0a(k['errors']);throw new Error('Machine\x20node\x20validation\x20failed\x20for\x20file\x20\x27'+i+'\x27:\x0a\x0a'+n);}if(!k['data'])throw new Error('No\x20nodes\x20found\x20in\x20file\x20\x27'+i+'\x27');b['data']['node']={'op':'set','nodes':k['data'],'bReplace':!![]};}const g=new CallMachine(b['data']),h=b['submission']?await g['call_with_submission'](c,await transformSubmission(b['submission'])):await g['call'](c);return handleCallResult(h);}case'progress':{const o=new CallProgress(b['data']),p=b['submission']?await o['call_with_submission'](c,await transformSubmission(b['submission'])):await o['call'](c);return handleCallResult(p);}case'repository':{const q=new CallRepository(b['data']),r=b['submission']?await q['call_with_submission'](c,await transformSubmission(b['submission'])):await q['call'](c);return handleCallResult(r);}case'arbitration':{const s=new CallArbitration(b['data']),t=b['submission']?await s['call_with_submission'](c,await transformSubmission(b['submission'])):await s['call'](c);return handleCallResult(t);}case'contact':{const u=new CallContact(b['data']),v=b['submission']?await u['call_with_submission'](c,await transformSubmission(b['submission'])):await u['call'](c);return handleCallResult(v);}case'treasury':{const w=new CallTreasury(b['data']),x=b['submission']?await w['call_with_submission'](c,await transformSubmission(b['submission'])):await w['call'](c);return handleCallResult(x);}case'reward':{const y=transformRewardData(b['data']),A=new CallReward(y),B=b['submission']?await A['call_with_submission'](c,await transformSubmission(b['submission'])):await A['call'](c);return handleCallResult(B);}case'allocation':{const C=new CallAllocation(b['data']),D=b['submission']?await C['call_with_submission'](c,await transformSubmission(b['submission'])):await C['call'](c);return handleCallResult(D);}case'permission':{const E=new CallPermission(b['data']),F=await E['call'](c);return handleCallResult(F);}case'guard':{const G=b['data'];if(G['root']?.['type']==='file'){const J=resolve(G['root']['file_path']);let K;try{K=readFileSync(J,'utf-8');}catch(N){throw new Error('Failed\x20to\x20read\x20Guard\x20definition\x20file\x20\x27'+G['root']['file_path']+'\x27:\x20'+N['message']);}const L=parseGuardFile(K,G['root']['format']);if(!L['success']){const O=formatGuardParseErrors(L['errors']);throw new Error('Guard\x20validation\x20failed\x20for\x20file\x20\x27'+G['root']['file_path']+'\x27:\x0a\x0a'+O);}const M=L['data'];G['root']={'type':'node','node':M['root']},M['table']!==undefined&&G['table']===undefined&&(G['table']=M['table']),M['description']!==undefined&&G['description']===undefined&&(G['description']=M['description']),M['rely']!==undefined&&G['rely']===undefined&&(G['rely']=M['rely']),M['namedNew']!==undefined&&G['namedNew']===undefined&&(G['namedNew']=M['namedNew']);}if(G['root']&&typeof G['root']==='object'){const P=G['root'];P['type']==='node'&&P['node']&&(G['root']=P['node']);}if(!G['table']||G['table']['length']===0x0)throw new Error('Guard\x20\x27table\x27\x20field\x20is\x20required\x20and\x20cannot\x20be\x20empty');if(!G['root'])throw new Error('Guard\x20\x27root\x27\x20field\x20is\x20required');const H=new CallGuard(G),I=await H['call'](c);return handleCallResult(I);}case'personal':{const Q=U=>{const V={...U};if(U['mark']){const W=X=>{if(typeof X==='string')return{'name_or_address':X,'local_mark_first':!![]};return X;};if(U['mark']['op']==='add'&&U['mark']['data'])V['mark']={...U['mark'],'data':U['mark']['data']['map'](X=>({...X,'address':W(X['address'])}))};else{if(U['mark']['op']==='remove'&&U['mark']['data'])V['mark']={...U['mark'],'data':U['mark']['data']['map'](X=>({...X,'address':W(X['address'])}))};else{if(U['mark']['op']==='clear'&&U['mark']['address']){const X=U['mark']['address'];Array['isArray'](X)&&X['every'](Y=>typeof Y==='string')&&(V['mark']={...U['mark'],'address':{'entities':X['map'](Y=>({'name_or_address':Y,'local_mark_first':!![]}))}});}else U['mark']['op']==='transfer'&&U['mark']['to']&&(V['mark']={...U['mark'],'to':W(U['mark']['to'])});}}}return V;},R=Q(b['data']),S=new CallPersonal(R),T=await S['call'](c);return handleCallResult(T);}case'payment':{const U=new CallPayment(b['data']),V=await U['call'](c);return handleCallResult(V);}case'demand':{const W=new CallDemand(b['data']),X=b['submission']?await W['call_with_submission'](c,await transformSubmission(b['submission'])):await W['call'](c);return handleCallResult(X);}case'order':{const Y=new CallOrder(b['data']),Z=b['submission']?await Y['call_with_submission'](c,await transformSubmission(b['submission'])):await Y['call'](c);return handleCallResult(Z);}case'gen_passport':{const a0=await gen_passport(c,b['guard'],b['info']);return handleCallResult(a0);}}throw new Error('Unknown\x20on-chain\x20operation\x20type:\x20'+b['operation_type']);}catch(a1){const a2=a1 instanceof Error?a1['message']:String(a1);return{'content':[{'type':'text','text':'Error:\x20'+a2}],'structuredContent':{'message':'Error:\x20'+a2,'result':{'type':'error','error':a2}}};}}async function handleAccountOperation(a){try{const b=strictParse(AccountOperationSchema,a,'account_operation\x20input'),c=await account_operation(b);return{'content':[{'type':'text','text':JSON['stringify'](c)}],'structuredContent':{'result':{'status':'success','data':c}}};}catch(d){const e=d instanceof Error?d['message']:String(d);return{'content':[{'type':'text','text':'Error:\x20'+e}],'structuredContent':{'result':{'status':'error','error':e}}};}}async function handleMarkOperation(a){try{const b=strictParse(LocalMarkOperationSchema,a,'local_mark_operation\x20input'),c=await local_mark_operation(b);return{'content':[{'type':'text','text':JSON['stringify'](c)}],'structuredContent':{'result':{'status':'success','data':c}}};}catch(d){const e=d instanceof Error?d['message']:String(d);return{'content':[{'type':'text','text':'Error:\x20'+e}],'structuredContent':{'result':{'status':'error','error':e}}};}}async function handleInfoOperation(a){try{const b=strictParse(LocalInfoOperationSchema,a,'local_info_operation\x20input'),c=await local_info_operation(b);return{'content':[{'type':'text','text':JSON['stringify'](c)}],'structuredContent':{'result':{'status':'success','data':c}}};}catch(d){const e=d instanceof Error?d['message']:String(d);return{'content':[{'type':'text','text':'Error:\x20'+e}],'structuredContent':{'result':{'status':'error','error':e}}};}}async function handleWipOperations(a){const b=strictParse(WipOperationsSchema,a,'wip_file\x20input');let c;switch(b['type']){case'generate':{const d=await generate_wip(b['options'],b['outputPath']);c={'result':{'type':'generate','filePath':d}};break;}case'verify':{const e=await verify_wip(b['wipFilePath'],b['hash_equal'],b['requireSignature']);c={'result':{'type':'verify',...e}};break;}case'sign':{const f=await sign_wip(b['wipFilePath'],b['account'],b['outputPath']);c={'result':{'type':'sign','filePath':f}};break;}case'wip2html':{const g=await wip2html(b['wipPath'],b['options']);let h={'type':'wip2html'};if(typeof g==='string')h['html']=g;else Array['isArray'](g)?h['files']=g:h['html']=String(g);c={'result':h};break;}default:throw new Error('Unknown\x20WIP\x20operation\x20type');}return{'content':[{'type':'text','text':JSON['stringify'](c)}],'structuredContent':c};}async function handleWatchQueryOperations(a){const b=strictParse(WatchQueryOperationsSchema,a,'watch_and_query\x20input');let c;switch(b['query_type']){case'local_mark_list':{const d=await query_local_mark_list(b['filter']||{});c={'query_type':'local_mark_list','result':d};break;}case'account_list':{const e=await query_account_list(b['filter']);c={'query_type':'account_list','result':e};break;}case'local_info_list':{const f=await query_local_info_list(b['filter']);c={'query_type':'local_info_list','result':f};break;}case'token_list':{const g=await query_local_token_list(b['filter']||{});c={'query_type':'token_list','result':g};break;}case'account_balance':{const h=await query_account({'name_or_address':b['name_or_address'],'token_type':b['token_type'],'balance':!![]});c={'query_type':'account_balance','result':h};break;}case'onchain_personal_profile':{const i=await query_personal({'account':b['account']});c={'query_type':'onchain_personal_profile','result':i};break;}case'onchain_objects':{const j=await query_objects({'objects':b['objects']});j&&j['objects']&&Array['isArray'](j['objects'])&&(j['objects']=j['objects']['map'](k=>{if(k&&k['data']&&k['data']['type']==='Guard'&&k['data']['root'])try{const l=generateNodeComments(k['data']['root']);return{...k,'_guard_node_comments':l};}catch(m){return k;}return k;}));c={'query_type':'onchain_objects','result':j};break;}case'onchain_table':{const k=await query_table({'parent':b['parent'],'object_type':b['object_type']});c={'query_type':'onchain_table','result':k};break;}case'onchain_table_item_repository_data':{const l=await queryTableItem_RepositoryData({'parent':b['parent'],'name':b['name'],'entity':b['entity']});c={'query_type':'onchain_table_item_repository_data','result':l};break;}case'onchain_table_item_permission_perm':{const m=await queryTableItem_PermissionPerm({'parent':b['parent'],'address':b['address']});c={'query_type':'onchain_table_item_permission_perm','result':m};break;}case'onchain_table_item_reward_record':{const n=await queryTableItem_RewardRecord({'parent':b['parent'],'address':b['address']});c={'query_type':'onchain_table_item_reward_record','result':n};break;}case'onchain_table_item_demand_presenter':{const o=await queryTableItem_DemandPresenter({'parent':b['parent'],'address':b['address']});c={'query_type':'onchain_table_item_demand_presenter','result':o};break;}case'onchain_table_item_treasury_history':{const p=await queryTableItem_TreasuryHistory({'parent':b['parent'],'address':b['address']});c={'query_type':'onchain_table_item_treasury_history','result':p};break;}case'onchain_table_item_machine_node':{const q=await queryTableItem_MachineNode({'parent':b['parent'],'key':b['key']});c={'query_type':'onchain_table_item_machine_node','result':q};break;}case'onchain_table_item_progress_history':{const r=await queryTableItem_ProgressHistory({'parent':b['parent'],'u64':b['u64']});c={'query_type':'onchain_table_item_progress_history','result':r};break;}case'onchain_table_item_address_mark':{const s=await queryTableItem_AddressMark({'parent':b['parent'],'address':b['address']});c={'query_type':'onchain_table_item_address_mark','result':s};break;}case'onchain_table_item_entity_registrar':{const t=await queryTableItem_EntityRegistrar({'address':b['address']});c={'query_type':'onchain_table_item_entity_registrar','result':t};break;}case'onchain_table_item_entity_linker':{const u=await queryTableItem_EntityLinker({'address':b['address']});c={'query_type':'onchain_table_item_entity_linker','result':u};break;}case'onchain_received':{const v=await query_received({'object':b['object'],'all_type':b['all_type']});c={'query_type':'onchain_received','result':v};break;}default:throw new Error('Unknown\x20watch\x20query\x20type.\x20Valid\x20query_types\x20are:\x20\x22local_mark_list\x22,\x20\x22account_list\x22,\x20\x22local_info_list\x22,\x20\x22token_list\x22,\x20\x22account_balance\x22,\x20\x22onchain_personal_profile\x22,\x20\x22onchain_objects\x22,\x20\x22onchain_table\x22,\x20\x22onchain_table_item_repository_data\x22,\x20\x22onchain_table_item_permission_perm\x22,\x20\x22onchain_table_item_reward_record\x22,\x20\x22onchain_table_item_demand_presenter\x22,\x20\x22onchain_table_item_treasury_history\x22,\x20\x22onchain_table_item_machine_node\x22,\x20\x22onchain_table_item_progress_history\x22,\x20\x22onchain_table_item_address_mark\x22,\x20\x22onchain_table_item_entity_registrar\x22,\x20\x22onchain_table_item_entity_linker\x22,\x20\x22onchain_received\x22');}return{'content':[{'type':'text','text':JSON['stringify']({'result':c})}],'structuredContent':{'result':c}};}async function handleWowokInfo(a){const b=strictParse(ProtocolInfoQuerySchema,a,'wowok_buildin_info\x20input'),c=await queryProtocolInfo(b);return{'content':[{'type':'text','text':JSON['stringify']({'result':c})}],'structuredContent':{'result':c}};}async function handleOnchainEvents(a){const b=strictParse(OnchainEventsInputSchema,a,'onchain_events\x20input'),c=await query_events({'type':b['type'],'cursor':b['cursor']??null,'limit':b['limit']??null,'order':b['order']??null,'no_cache':b['no_cache'],'network':b['network']});return{'content':[{'type':'text','text':JSON['stringify']({'result':c})}],'structuredContent':{'result':c}};}function normalizeAccountOrMark(a){if(typeof a==='string')return{'name_or_address':a,'local_mark_first':!![]};return a;}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;}async function handleMessengerOperation(a){const b=strictParse(MessengerOperationInputSchema,a,'messenger_operation\x20input');let c;switch(b['operation']){case'watch_conversations':{const d=await watch_conversations(b['filter']);c={'operation':'watch_conversations','result':d};break;}case'send_message':{const e=await send_message(b['from'],normalizeAccountOrMark(b['to']),b['content'],b['options']),f={...e,'merkleData':e['merkleData']?{'leafIndex':e['merkleData']['leafIndex'],'prevRoot':e['merkleData']['prevRoot'],'newRoot':e['merkleData']['newRoot'],'serverSignature':e['merkleData']['serverSignature'],'serverTimestamp':e['merkleData']['serverTimestamp'],'serverPublicKey':e['merkleData']['serverPublicKey']}:undefined};c={'operation':'send_message','result':f};break;}case'send_file':{const g=await send_file(b['from'],normalizeAccountOrMark(b['to']),b['filePath'],b['options']),h={...g,'merkleData':g['merkleData']?{'leafIndex':g['merkleData']['leafIndex'],'prevRoot':g['merkleData']['prevRoot'],'newRoot':g['merkleData']['newRoot'],'serverSignature':g['merkleData']['serverSignature'],'serverTimestamp':g['merkleData']['serverTimestamp'],'serverPublicKey':g['merkleData']['serverPublicKey']}:undefined};c={'operation':'send_file','result':h};break;}case'watch_messages':{const i=b['filter']?{...b['filter'],'peerAddress':b['filter']['peerAddress']?normalizeAccountOrMark(b['filter']['peerAddress']):undefined}:undefined,j=await watch_messages(i);c={'operation':'watch_messages','result':j};break;}case'extract_zip_messages':{const k=await extract_zip_messages(b['account'],b['messages'],b['outputDir']);c={'operation':'extract_zip_messages','result':k};break;}case'generate_wts':{const l=b['params']?{...b['params'],'peerAccount':normalizeAccountOrMark(b['params']['peerAccount'])}:undefined,m=await generate_wts(l);c={'operation':'generate_wts','result':m};break;}case'verify_wts':{const n=await verify_wts(b['wtsFilePath']);c={'operation':'verify_wts','result':n};break;}case'sign_wts':{const o=await sign_wts(b['wtsFilePath'],b['account'],b['outputPath']);c={'operation':'sign_wts','result':o};break;}case'wts2html':{const p=await wts2html(b['wtsPath'],b['options']);c={'operation':'wts2html','result':p};break;}case'proof_message':{const q=await proof_message(b['account'],b['messageId'],b['network']);c={'operation':'proof_message','result':q};break;}case'blacklist':{const r={'account':b['account'],'op':b['blacklist']['op']};'users'in b['blacklist']&&(r['users']=normalizeManyAccountOrMark(b['blacklist']['users']));const s=await blacklist(r);c={'operation':'blacklist','op':b['blacklist']['op'],'result':s['result']};break;}case'friendslist':{const t={'account':b['account'],'op':b['friendslist']['op']};'users'in b['friendslist']&&(t['users']=normalizeManyAccountOrMark(b['friendslist']['users']));const u=await friendslist(t);c={'operation':'friendslist','op':b['friendslist']['op'],'result':u['result']};break;}case'guardlist':{const v=await guardlist({'account':b['account'],...b['guardlist']});c={'operation':'guardlist','op':b['guardlist']['op'],'result':v['result']};break;}case'settings':{const w=await settings({'account':b['account'],...b['settings']});c={'operation':'settings','op':b['settings']['op'],'result':w['result']};break;}case'mark_messages_as_viewed':{const x=await mark_messages_as_viewed(b['messageIds'],b['account']);c={'operation':'mark_messages_as_viewed','result':x};break;}case'mark_conversation_as_viewed':{const y=await mark_conversation_as_viewed(normalizeAccountOrMark(b['peerAddress']),b['account']);c={'operation':'mark_conversation_as_viewed','result':y};break;}default:throw new Error('Unknown\x20messenger\x20operation:\x20'+b['operation']);}return{'content':[{'type':'text','text':JSON['stringify'](c)}],'structuredContent':{'result':c}};}async function handleGuard2File(a){const b=strictParse(Guard2File_InputSchema,a,'guard2file\x20input'),c=getEnvConfig(b['env']);try{await guard2file(b['guard'],b['file_path'],b['format']||'json',c['network']);const d={'result':{'status':'success','data':{'file_path':resolve(b['file_path']),'format':b['format']||'json','guard_object':b['guard']}}};return{'content':[{'type':'text','text':JSON['stringify'](d)}],'structuredContent':d};}catch(e){const f={'result':{'status':'error','error':e['message']}};return{'content':[{'type':'text','text':JSON['stringify'](f)}],'structuredContent':f};}}async function handleMachineNode2File(a){const b=strictParse(MachineNode2File_InputSchema,a,'machineNode2file\x20input'),c=getEnvConfig(b['env']);try{await machineNode2file(b['machine'],b['file_path'],b['format']||'json',c['network']);const d={'result':{'status':'success','data':{'file_path':resolve(b['file_path']),'format':b['format']||'json','machine_object':b['machine'],'node_count':0x0}}};return{'content':[{'type':'text','text':JSON['stringify'](d)}],'structuredContent':d};}catch(e){const f={'result':{'status':'error','error':e['message']}};return{'content':[{'type':'text','text':JSON['stringify'](f)}],'structuredContent':f};}}export{OnchainOperationsSchema,WipOperationsSchema,WatchQueryOperationsSchema,AccountOperationSchema,LocalMarkOperationSchema,LocalInfoOperationSchema,ProtocolInfoQuerySchema,CallOutputSchema,MessengerOperationInputSchema,MessengerOperationOutputSchema};async function main(){server['registerTool']('onchain_operations',{'title':'â›“ī¸\x20On-chain\x20Operations','description':'On-chain\x20operations\x20for\x20WoWok\x20object:\x20service\x20(marketplace\x20listings),\x20machine\x20(workflow\x20templates),\x20progress\x20(order\x20tracking),\x20repository\x20(on-chain\x20database),\x20arbitration\x20(dispute\x20resolution),\x20contact\x20(IM\x20management),\x20treasury\x20(team\x20funds),\x20reward\x20(incentive\x20pools),\x20allocation\x20(auto-distribution),\x20permission\x20(access\x20control),\x20guard\x20(programmable\x20trust\x20rules),\x20personal\x20(public\x20profile),\x20payment\x20(direct\x20coin\x20transfers),\x20demand\x20(service\x20requests),\x20order\x20(order\x20management),\x20gen_passport\x20(verified\x20credentials).','inputSchema':OnchainOperationsSchema,'outputSchema':CallOutputSchema,'annotations':{'readOnlyHint':![],'destructiveHint':!![],'idempotentHint':![],'openWorldHint':!![]},'_meta':createToolMeta('operation',['service','machine','progress','repository','arbitration','contact','treasury','reward','allocation','permission','guard','personal','payment','demand','order','gen_passport','on-chain','blockchain'])},handleOnchainOperations),server['registerTool']('account_operation',{'title':'🔒\x20LOCAL\x20ONLY:\x20Account\x20-\x20Wallet\x20Management','description':'🔒\x20100%\x20LOCAL,\x20NEVER\x20ON-CHAIN\x20🔒\x20Manage\x20WoWok\x20accounts\x20locally\x20on\x20device:\x20generate,\x20suspend,\x20resume,\x20faucet-test,\x20operate\x20assets,\x20sign\x20data,\x20etc.','inputSchema':AccountOperationSchema,'outputSchema':AccountOperationOutputWrappedSchema,'annotations':{'readOnlyHint':![],'destructiveHint':!![],'idempotentHint':!![],'openWorldHint':![]},'_meta':createToolMeta('operation',['account','local','private','wallet','off-chain'])},handleAccountOperation),server['registerTool']('local_mark_operation',{'title':'🔒\x20LOCAL\x20ONLY:\x20LocalMark\x20-\x20Address\x20Book\x20Management','description':'100%\x20LOCAL,\x20NEVER\x20ON-CHAIN\x20🔒\x20Manage\x20ID\x20names\x20and\x20tags\x20stored\x20ONLY\x20on\x20your\x20local\x20device\x20for\x20easy\x20identification\x20of\x20user\x20address\x20or\x20object\x20IDs\x20by\x20name.','inputSchema':LocalMarkOperationSchema,'outputSchema':LocalMarkOperationOutputWrappedSchema,'annotations':{'readOnlyHint':![],'destructiveHint':!![],'idempotentHint':!![],'openWorldHint':![]},'_meta':createToolMeta('operation',['mark','local','private','address-book','off-chain'])},handleMarkOperation),server['registerTool']('local_info_operation',{'title':'🔒\x20LOCAL\x20ONLY:\x20LocalInfo\x20-\x20Private\x20Data\x20Management','description':'100%\x20LOCAL,\x20NEVER\x20ON-CHAIN\x20🔒\x20Manage\x20sensitive\x20personal\x20information\x20stored\x20ONLY\x20on\x20your\x20device:\x20delivery\x20addresses,\x20phone\x20numbers,\x20contacts.','inputSchema':LocalInfoOperationSchema,'outputSchema':LocalInfoOperationOutputWrappedSchema,'annotations':{'readOnlyHint':![],'destructiveHint':!![],'idempotentHint':!![],'openWorldHint':![]},'_meta':createToolMeta('operation',['info','local','private','data-management','off-chain'])},handleInfoOperation),server['registerTool']('wip_file',{'title':'🤝\x20Witness\x20Information\x20Promise\x20File\x20Operations','description':'generate\x20(create\x20WIP\x20files\x20from\x20markdown\x20and\x20images),\x20verify\x20(integrity\x20check),\x20sign\x20(add\x20signatures),\x20or\x20wip2html\x20(convert\x20to\x20HTML).','inputSchema':WipOperationsSchema,'outputSchema':z['object']({'result':WipOperationOutputSchema}),'annotations':{'readOnlyHint':![],'destructiveHint':![],'idempotentHint':![],'openWorldHint':![]},'_meta':createToolMeta('operation',['wip','promise','file-generation','verification','signature','local'])},handleWipOperations),server['registerTool']('messenger_operation',{'title':'đŸ’Ŧ\x20Messenger\x20Operations','description':'WoWok\x20encrypted\x20messenger\x20operations:\x20watch\x20conversations\x20(with\x20unread\x20filtering,\x20preview\x20messages),\x20send\x20message,\x20send\x20file,\x20watch\x20messages\x20(with\x20viewed\x20status\x20filtering),\x20extract\x20zip\x20messages,\x20generate\x20WTS,\x20verify\x20WTS,\x20sign\x20WTS,\x20WTS\x20to\x20HTML,\x20proof\x20message\x20on-chain,\x20manage\x20blacklist,\x20friendslist,\x20guardlist,\x20settings,\x20mark\x20messages\x20as\x20viewed,\x20and\x20mark\x20conversation\x20as\x20viewed.','inputSchema':MessengerOperationInputSchema,'outputSchema':MessengerOperationOutputSchema,'annotations':{'readOnlyHint':![],'destructiveHint':!![],'idempotentHint':![],'openWorldHint':!![]},'_meta':createToolMeta('operation',['messenger','message','file','wts','blacklist','friendslist','guardlist','settings','proof','communication'])},handleMessengerOperation),server['registerTool']('guard2file',{'title':'📄\x20Guard\x20to\x20File\x20-\x20Export\x20Guard\x20Definition','description':'Export\x20a\x20Guard\x20object\x27s\x20definition\x20from\x20the\x20blockchain\x20to\x20a\x20local\x20JSON\x20or\x20Markdown\x20file\x20for\x20editing\x20and\x20creating\x20new\x20Guard\x20objects.\x20Note:\x20To\x20query\x20on-chain\x20object\x20information,\x20use\x20the\x20\x27query_toolkit\x27\x20tool\x20instead.','inputSchema':Guard2File_InputSchema,'outputSchema':Guard2File_OutputWrappedSchema,'annotations':{'readOnlyHint':!![],'destructiveHint':![],'idempotentHint':!![],'openWorldHint':!![]},'_meta':createToolMeta('generate\x20file',['guard','export','file','json','markdown','on-chain'])},handleGuard2File),server['registerTool']('machineNode2file',{'title':'âš™ī¸\x20Machine\x20Node\x20to\x20File\x20-\x20Export\x20Machine\x20Node\x20Definition','description':'Export\x20a\x20Machine\x20object\x27s\x20node\x20definition\x20from\x20the\x20blockchain\x20to\x20a\x20local\x20JSON\x20or\x20Markdown\x20file\x20for\x20editing\x20and\x20creating\x20new\x20Machine\x20objects.\x20Note:\x20To\x20query\x20on-chain\x20object\x20information,\x20use\x20the\x20\x27query_toolkit\x27\x20tool\x20instead.','inputSchema':MachineNode2File_InputSchema,'outputSchema':MachineNode2File_OutputWrappedSchema,'annotations':{'readOnlyHint':!![],'destructiveHint':![],'idempotentHint':!![],'openWorldHint':!![]},'_meta':createToolMeta('generate\x20file',['machine','export','file','json','markdown','on-chain','workflow'])},handleMachineNode2File),server['registerTool']('query_toolkit',{'title':'🔍\x20Data\x20Query\x20Toolkit','description':'WOWOK\x20data\x20query\x20toolkit:\x20Query\x20local\x20naming\x20info\x20(accounts,\x20names,\x20Object\x20IDs),\x20and\x20query\x20on-chain\x20WOWOK\x20objects,\x20table\x20items,\x20events,\x20received\x20tokens,\x20user\x20profile,\x20etc.','inputSchema':WatchQueryOperationsSchema,'outputSchema':WatchQueryOperationsResultSchema,'annotations':{'readOnlyHint':!![],'destructiveHint':![],'idempotentHint':!![],'openWorldHint':!![]},'_meta':createToolMeta('query',['watch','query','on-chain','local','events','objects','tables','tokens','balance','profile'])},handleWatchQueryOperations),server['registerTool']('onchain_events',{'title':'📅\x20Watch\x20On-chain\x20Events','description':'Watch\x20on-chain\x20WOWOK\x20events\x20by\x20type.\x20Supports\x20arbitration\x20events,\x20new\x20order\x20events,\x20progress\x20events,\x20demand\x20presentation\x20events,\x20demand\x20feedback\x20events,\x20and\x20new\x20entity\x20registration\x20events.\x20Use\x20pagination\x20cursor\x20for\x20fetching\x20large\x20result\x20sets.','inputSchema':OnchainEventsInputSchema,'outputSchema':OnchainEventsResultSchema,'annotations':{'readOnlyHint':!![],'destructiveHint':![],'idempotentHint':!![],'openWorldHint':!![]},'_meta':createToolMeta('watch\x20events',['events','on-chain','arbitration','order','progress','demand','entity'])},handleOnchainEvents),server['registerTool']('wowok_buildin_info',{'title':'â„šī¸\x20WoWok\x20Build-in\x20Information','description':'Query\x20WoWok\x20protocol\x20information:\x20\x27constants\x27,\x20\x27built-in\x20permissions\x27,\x20\x27guard\x20instructions\x27,\x20\x27current\x20network\x27,\x20or\x20\x27value\x20types\x27.','inputSchema':ProtocolInfoQuerySchema,'outputSchema':ProtocolInfoResultSchema,'annotations':{'readOnlyHint':!![],'destructiveHint':![],'idempotentHint':!![],'openWorldHint':!![]},'_meta':createToolMeta('WoWok\x20info',['build-in','constants','permissions','guard','network','value-types'])},handleWowokInfo),server['registerTool']('documents_and_learn',{'title':'📚\x20Documents\x20and\x20Learn','description':'Access\x20WoWok\x20documentation\x20and\x20learning\x20resources.\x20Provides\x20official\x20documentation\x20URL\x20for\x20users\x20and\x20AI\x20to\x20get\x20more\x20information\x20about\x20WoWok\x20protocol,\x20components,\x20and\x20usage.','inputSchema':z['object']({'topic':z['string']()['optional']()['describe']('Optional\x20topic\x20to\x20search\x20for\x20in\x20documentation\x20(e.g.,\x20\x27guard\x27,\x20\x27service\x27,\x20\x27messenger\x27,\x20\x27stage-01-introduction\x27)')}),'outputSchema':z['object']({'documentation_url':z['string']()['describe']('Official\x20WoWok\x20documentation\x20URL\x20on\x20GitHub'),'topic':z['string']()['optional']()['describe']('Requested\x20topic\x20if\x20specified'),'original_topic':z['string']()['optional']()['describe']('Original\x20topic\x20input\x20by\x20user\x20(before\x20normalization)'),'message':z['string']()['describe']('Welcome\x20message\x20with\x20documentation\x20information.\x20Always\x20included\x20in\x20response.')}),'annotations':{'readOnlyHint':!![],'destructiveHint':![],'idempotentHint':!![],'openWorldHint':!![]},'_meta':createToolMeta('documentation',['docs','learn','tutorial','guide','help','reference'])},async b=>{const c='https://github.com/wowok-ai/docs/blob/main/docs';if(!b['topic']){const g=c,h='Welcome\x20to\x20WoWok\x20Documentation!\x20Access\x20comprehensive\x20guides,\x20tutorials,\x20and\x20API\x20references\x20at:\x20'+g;return{'content':[{'type':'text','text':h}],'structuredContent':{'documentation_url':g,'message':h}};}const d=b['topic']['toLowerCase']()['trim'](),e=c+'/'+d+'.md',f='Documentation\x20for\x20\x22'+d+'\x22\x0aGitHub\x20URL:\x20'+e;return{'content':[{'type':'text','text':f}],'structuredContent':{'documentation_url':e,'topic':d,'original_topic':b['topic'],'message':f}};});const a=new StdioServerTransport();await server['connect'](a),process['on']('SIGINT',async()=>{await server['close'](),process['exit'](0x0);});}main()['catch'](console['error']);
2
+ import { z } from "zod";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { readFileSync } from "fs";
6
+ import { resolve } from "path";
7
+ const packageJson = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf-8"));
8
+ import { CallService_DataSchema, CallMachine_DataSchema, MachineNode2File_InputSchema, MachineNode2File_OutputWrappedSchema, CallProgress_DataSchema, CallPermission_DataSchema, CallGuard_DataSchema, Guard2File_InputSchema, Guard2File_OutputWrappedSchema, CallArbitration_DataSchema, CallRepository_DataSchema, CallContact_DataSchema, CallTreasury_DataSchema, CallReward_DataSchema, CallAllocation_DataSchema, CallPersonal_DataSchema, CallPayment_DataSchema, CallDemand_DataSchema, CallOrder_DataSchema, CallEnvSchema, SubmissionCallSchema, strictParse, CallOutputSchema, handleCallResult, createServerConfig, createCapabilitiesConfig, createToolMeta, transformSubmission, getEnvConfig, WipGenerationOptionsSchema, WipToHtmlOptionsSchema, TokenDataFilterSchema, LocalInfoFilterSchema, LocalMarkFilterSchema, AccountFilterSchema, TokenTypeSchema, OnchainEventsInputSchema, OnchainEventsResultSchema, ProtocolInfoQuerySchema, ProtocolInfoResultSchema, WatchQueryOperationsResultSchema, NameOrAddressSchema, AccountOrMark_AddressSchema, ObjectTypeSchema, AccountOperationOutputWrappedSchema, LocalMarkOperationOutputWrappedSchema, LocalInfoOperationOutputWrappedSchema, WipOperationOutputSchema, MessengerOperationOutputSchema, AccountOperationSchema, LocalMarkOperationSchema, LocalInfoOperationSchema, parseMachineNodesFromText, formatNodeErrors as formatMachineNodeErrors, MessengerOperationInputSchema, } from "./schema/index.js";
9
+ import { CallService, CallMachine, CallProgress, CallPermission, CallGuard, CallArbitration, CallRepository, CallContact, CallTreasury, CallReward, CallAllocation, CallPersonal, CallPayment, CallDemand, CallOrder, gen_passport, guard2file, parseGuardFile, formatGuardParseErrors, machineNode2file, generateNodeComments, generate_wip, verify_wip, sign_wip, wip2html, account_operation, local_mark_operation, local_info_operation, watch_conversations, send_message, send_file, watch_messages, extract_zip_messages, generate_wts, verify_wts, sign_wts, wts2html, proof_message, mark_messages_as_viewed, mark_conversation_as_viewed, query_local_mark_list, query_account_list, query_local_info_list, query_local_token_list, query_account, query_personal, query_objects, query_table, queryProtocolInfo, query_received, queryTableItem_RepositoryData, queryTableItem_PermissionPerm, queryTableItem_RewardRecord, queryTableItem_DemandPresenter, queryTableItem_TreasuryHistory, queryTableItem_MachineNode, queryTableItem_ProgressHistory, queryTableItem_AddressMark, queryTableItem_EntityRegistrar, queryTableItem_EntityLinker, query_events, blacklist, friendslist, guardlist, settings, AmountType, } from "wowok";
10
+ const SERVER_DESCRIPTION = `WoWok MCP Server - Making It Easy for AI Agents to Communicate, Collaborate, Trade, and Trust.
11
+
12
+ ## Token System Overview
13
+
14
+ ### Default Platform Token: WOW
15
+ - Token Type: 0x2::wow::WOW
16
+ - Precision: 1_000_000_000 (9 decimal places)
17
+ - This is the default token for all operations unless specified otherwise
18
+
19
+ ### Multi-Token Support
20
+ The platform supports ANY token (e.g., USDT, USDC, custom tokens). To use non-WOW tokens:
21
+ 1. Use query_toolkit with query_type='token_list' to query available tokens and their precision info
22
+ 2. Use the token's full type string (e.g., '0x2::usdt::USDT') in token_type parameter
23
+ 3. Each token has its own precision - always verify before operations
24
+
25
+ ### Token Precision Handling
26
+ Different tokens have different precisions. ALWAYS query to verify:
27
+ - WOW (default): 1_000_000_000 (9 decimals)
28
+ - Other tokens: Use query_toolkit with query_type='token_list' to get actual precision
29
+ - Never assume a token's decimal places - always query first
30
+
31
+ ## CRITICAL: Token Amount Handling
32
+
33
+ ### Amount Input Rules
34
+ 1. WITH currency unit (e.g., '2WOW', '10.5WOW', '100USDT'):
35
+ - Auto-converted using token's precision: 2WOW -> 2_000_000_000
36
+ - Use for: All on-chain token operations
37
+ - MUST match the token_type parameter
38
+
39
+ 2. WITHOUT currency unit (e.g., '2', '100'):
40
+ - Used as-is: 2 -> 2
41
+ - Use for: Regular numeric parameters (counts, indices, etc.)
42
+
43
+ ### Multi-Token Operation Examples
44
+ - Create USDT-priced Service: token_type='0x2::usdt::USDT', amount='100USDT'
45
+ - Allocate USDC rewards: token_type='0x2::usdc::USDC', amount='500USDC'
46
+ - WOW remains default: omit token_type or use '0x2::wow::WOW'
47
+
48
+ ### Security Warning
49
+ Token amounts are HIGHLY SENSITIVE. Always:
50
+ - Confirm user's intent before executing transfers
51
+ - Verify token type and amount format (with/without unit)
52
+ - Query token precision if unsure
53
+ - Double-check large amount transactions
54
+ - Never assume decimal places - use explicit token unit
55
+
56
+ ## Tool Selection Guide
57
+
58
+ | User Intent | Correct Tool | Wrong Tool (Avoid) |
59
+ |------------|--------------|-------------------|
60
+ | Create service listing | onchain_operations (service) | query_toolkit |
61
+ | Send coins to address | onchain_operations (payment) | account_operation |
62
+ | Check my balance | query_toolkit (account_balance) | onchain_operations |
63
+ | Manage local wallet | account_operation | onchain_operations |
64
+ | Export Guard for edit | guard2file | query_toolkit |
65
+ | Send/Watch encrypted message | messenger_operation | onchain_operations |
66
+ | Create workflow template | onchain_operations (machine) | wip_file |
67
+ | Store my phone number | local_info_operation | onchain_operations |
68
+ | Buy service (create order) | onchain_operations (order) | onchain_operations (service) |
69
+ | Manage my orders | onchain_operations (order) | query_toolkit |
70
+ | Apply for arbitration | onchain_operations (order) | onchain_operations (arbitration) |
71
+ | Create reward pool for marketing | onchain_operations (reward) | onchain_operations (treasury) |
72
+ | Claim rewards from pool | onchain_operations (reward) | query_toolkit |
73
+ | Create fund allocation plan | onchain_operations (allocation) | onchain_operations (treasury) |
74
+ | Execute fund distribution | onchain_operations (allocation) | onchain_operations (payment) |
75
+ | Post service demand with reward | onchain_operations (demand) | onchain_operations (service) |
76
+ | Submit solution for demand | onchain_operations (demand) | onchain_operations (order) |
77
+ | Create team treasury | onchain_operations (treasury) | onchain_operations (allocation) |
78
+ | Deposit/Withdraw from treasury | onchain_operations (treasury) | onchain_operations (payment) |
79
+ | Create access control rules | onchain_operations (permission) | onchain_operations (guard) |
80
+ | Create validation rules (Guard) | onchain_operations (guard) | onchain_operations (permission) |
81
+ | Export Guard for editing | guard2file | query_toolkit |
82
+ | Export Machine nodes for editing | machineNode2file | query_toolkit |
83
+ | Query token list and precision | query_toolkit (token_list) | wowok_buildin_info |
84
+ | Watch on-chain events | onchain_events | query_toolkit |
85
+ | Generate WIP promise file | wip_file (generate) | messenger_operation |
86
+ | Sign WIP file | wip_file (sign) | account_operation (signData) |
87
+ | Verify WIP file integrity | wip_file (verify) | query_toolkit |
88
+ | Send encrypted file via messenger | messenger_operation (send_file) | wip_file |
89
+ | Generate witness timestamp (WTS) | messenger_operation (generate_wts) | wip_file |
90
+ | Query protocol constants | wowok_buildin_info | query_toolkit |
91
+ | Get documentation URL | documents_and_learn | wowok_buildin_info |
92
+
93
+ ## Local vs On-chain Operations
94
+
95
+ ### LOCAL ONLY (Never touch blockchain):
96
+ - account_operation
97
+ - local_mark_operation
98
+ - local_info_operation
99
+
100
+ ### ON-CHAIN (Blockchain transactions):
101
+ - onchain_operations
102
+ - messenger_operation (some operations)
103
+ - wip_file (sign operation)
104
+
105
+ ### QUERY (Read-only):
106
+ - query_toolkit
107
+ - onchain_events
108
+ - wowok_buildin_info
109
+ - documents_and_learn
110
+ - guard2file
111
+ - machineNode2file
112
+ `;
113
+ const server = new McpServer(createServerConfig(packageJson, SERVER_DESCRIPTION), createCapabilitiesConfig());
114
+ function convertAmountType(type) {
115
+ if (typeof type === "number")
116
+ return type;
117
+ const upperType = type.toUpperCase();
118
+ if (upperType === "GUARDU64IDENTIFIER" || upperType === "GUARD_U64_IDENTIFIER") {
119
+ return AmountType.GuardU64Identifier;
120
+ }
121
+ if (upperType === "FIXED") {
122
+ return AmountType.Fixed;
123
+ }
124
+ return AmountType.Fixed;
125
+ }
126
+ function transformRewardData(data) {
127
+ if (!data)
128
+ return data;
129
+ const transformed = { ...data };
130
+ if (transformed.guard_add && Array.isArray(transformed.guard_add)) {
131
+ transformed.guard_add = transformed.guard_add.map((guard) => {
132
+ if (guard.amount && typeof guard.amount.type === "string") {
133
+ return {
134
+ ...guard,
135
+ amount: {
136
+ ...guard.amount,
137
+ type: convertAmountType(guard.amount.type)
138
+ }
139
+ };
140
+ }
141
+ return guard;
142
+ });
143
+ }
144
+ return transformed;
145
+ }
146
+ const OnchainOperationsSchema = z.discriminatedUnion("operation_type", [
147
+ z.object({
148
+ operation_type: z.literal("service"),
149
+ data: CallService_DataSchema,
150
+ env: CallEnvSchema.optional(),
151
+ submission: SubmissionCallSchema.optional(),
152
+ }).describe("đŸĒ Service Object: Create and manage product/service listings with transparent promises, bind workflow templates to order processing, set pricing, issue discount coupons to customers, and establish quality standards, etc.."),
153
+ z.object({
154
+ operation_type: z.literal("machine"),
155
+ data: CallMachine_DataSchema,
156
+ env: CallEnvSchema.optional(),
157
+ submission: SubmissionCallSchema.optional(),
158
+ }).describe("âš™ī¸ Machine Object: Design and deploy automated workflow templates (Machines) that define how services are delivered, etc.."),
159
+ z.object({
160
+ operation_type: z.literal("progress"),
161
+ data: CallProgress_DataSchema,
162
+ env: CallEnvSchema.optional(),
163
+ submission: SubmissionCallSchema.optional(),
164
+ }).describe("📊 Progress Object: Track and manage active workflows in real-time."),
165
+ z.object({
166
+ operation_type: z.literal("repository"),
167
+ data: CallRepository_DataSchema,
168
+ env: CallEnvSchema.optional(),
169
+ submission: SubmissionCallSchema.optional(),
170
+ }).describe("đŸ“Ļ Repository Object: Read/write database with consensus field + address as key, strongly-typed data as value."),
171
+ z.object({
172
+ operation_type: z.literal("arbitration"),
173
+ data: CallArbitration_DataSchema,
174
+ env: CallEnvSchema.optional(),
175
+ submission: SubmissionCallSchema.optional(),
176
+ }).describe("âš–ī¸ Arbitration Object: Access a transparent on-chain arbitration system for resolving order conflicts."),
177
+ z.object({
178
+ operation_type: z.literal("contact"),
179
+ data: CallContact_DataSchema,
180
+ env: CallEnvSchema.optional(),
181
+ submission: SubmissionCallSchema.optional(),
182
+ }).describe("đŸ’Ŧ Contact Object: Manage on-chain instant messaging contact profiles."),
183
+ z.object({
184
+ operation_type: z.literal("treasury"),
185
+ data: CallTreasury_DataSchema,
186
+ env: CallEnvSchema.optional(),
187
+ submission: SubmissionCallSchema.optional(),
188
+ }).describe("💰 Treasury Object: Create and manage treasury for team funds with deposit/withdrawal rules, etc.."),
189
+ z.object({
190
+ operation_type: z.literal("reward"),
191
+ data: CallReward_DataSchema,
192
+ env: CallEnvSchema.optional(),
193
+ submission: SubmissionCallSchema.optional(),
194
+ }).describe("🎁 Reward Object: Create reward pools and set claim conditions by Guard verification."),
195
+ z.object({
196
+ operation_type: z.literal("allocation"),
197
+ data: CallAllocation_DataSchema,
198
+ env: CallEnvSchema.optional(),
199
+ submission: SubmissionCallSchema.optional(),
200
+ }).describe("📤 Allocation Object: Create distribution plans to auto-distribute funds to multiple recipients."),
201
+ z.object({
202
+ operation_type: z.literal("permission"),
203
+ data: CallPermission_DataSchema,
204
+ env: CallEnvSchema.optional(),
205
+ }).describe("🔐 Permission Object: Define who can perform which operations on WoWok objects. Important Note: If needed, you should first query 'guard instructions' through the 'wowok_buildin_info' tool."),
206
+ z.object({
207
+ operation_type: z.literal("guard"),
208
+ data: CallGuard_DataSchema,
209
+ env: CallEnvSchema.optional(),
210
+ }).describe("đŸ›Ąī¸ Guard Object: Create immutable programmable validation rules that return boolean results. Set 'namedNew' to name the new Guard. Use root.type='node' for direct node tree or root.type='file' to load from file. Use 'wowok_buildin_info' tool with query='guard instructions' for all available operations."),
211
+ z.object({
212
+ operation_type: z.literal("personal"),
213
+ data: CallPersonal_DataSchema,
214
+ env: CallEnvSchema.optional(),
215
+ }).describe("🆔 Public Identity Profile: Establish and manage your on-chain public identity. âš ī¸ CRITICAL: Everything here is PERMANENTLY PUBLIC on the blockchain!"),
216
+ z.object({
217
+ operation_type: z.literal("payment"),
218
+ data: CallPayment_DataSchema,
219
+ env: CallEnvSchema.optional(),
220
+ }).describe("💰 Payment Object: Send instant, irreversible coin transfers to any wallet address."),
221
+ z.object({
222
+ operation_type: z.literal("demand"),
223
+ data: CallDemand_DataSchema,
224
+ env: CallEnvSchema.optional(),
225
+ submission: SubmissionCallSchema.optional(),
226
+ }).describe("đŸŽ¯ Demand Object: Post service requests with reward pools on-chain."),
227
+ z.object({
228
+ operation_type: z.literal("order"),
229
+ data: CallOrder_DataSchema,
230
+ env: CallEnvSchema.optional(),
231
+ submission: SubmissionCallSchema.optional(),
232
+ }).describe("đŸ“Ļ Order Object: Manage the order lifecycle, Including operating order arbitration (Arb Object associated with the order), advancing progress (Progress Object associated with the order), extracting order refunds/payments, setting agents, etc."),
233
+ z.object({
234
+ operation_type: z.literal("gen_passport"),
235
+ guard: z.string().describe("Guard object ID to verify and generate passport from"),
236
+ info: SubmissionCallSchema.optional().describe("Optional submission data. If not provided, will attempt to get existing submissions from the guard."),
237
+ env: CallEnvSchema.optional(),
238
+ }).describe("🛂 Generate Verified Passport Object: Create immutable verified credentials after Guard validation passes."),
239
+ ]);
240
+ const WipOperationsSchema = z.discriminatedUnion("type", [
241
+ z.object({
242
+ type: z.literal("generate"),
243
+ options: WipGenerationOptionsSchema.describe("WIP generation options"),
244
+ outputPath: z.string().describe("Output file path (.wip file). If file exists, it will be overwritten"),
245
+ }).describe("Generate WIP file from markdown text and optional images"),
246
+ z.object({
247
+ type: z.literal("verify"),
248
+ wipFilePath: z.string().describe("WIP file path to verify. Supports: 1) Local file path (e.g., '/path/to/file.wip', 'C:\\Users\\name\\doc.wip'), 2) Network URL (e.g., 'https://example.com/doc.wip', 'http://site.com/file.wip'), 3) Data URL (e.g., 'data:application/json;base64,eyJ3aXAiOi...')"),
249
+ hash_equal: z.string().optional().describe("Optional expected hash value. If provided, the function will first verify if the file's hash matches this value. If not matched, returns hash mismatch error."),
250
+ requireSignature: z.boolean().optional().describe("Optional flag to require digital signature. If true, verification will fail if WIP file has no signature"),
251
+ }).describe("Verify WIP file integrity and signatures"),
252
+ z.object({
253
+ type: z.literal("sign"),
254
+ wipFilePath: z.string().describe("WIP file path to sign. Supports: 1) Local file path (e.g., '/path/to/file.wip'), 2) Network URL (e.g., 'https://example.com/doc.wip'). The file will be loaded, validated, and signed"),
255
+ account: z.string().optional().describe("Signing account (account name or address). If not specified, uses default account"),
256
+ outputPath: z.string().optional().describe("Output file path. If not specified, adds 'signed_' prefix to original file name (e.g., 'doc.wip' becomes 'signed_doc.wip')"),
257
+ }).describe("Sign WIP file with account"),
258
+ z.object({
259
+ type: z.literal("wip2html"),
260
+ wipPath: z.string().describe("WIP file path or directory path. Supports: 1) Single WIP file (e.g., '/path/to/file.wip'), 2) Directory containing .wip files (e.g., '/path/to/wips/'), 3) Network URL (e.g., 'https://example.com/doc.wip'). When directory is provided, all .wip files in the directory will be converted to HTML"),
261
+ options: WipToHtmlOptionsSchema.optional().describe("Conversion options"),
262
+ }).describe("Convert WIP file to HTML format"),
263
+ ]);
264
+ const WatchQueryOperationsSchema = z.discriminatedUnion("query_type", [
265
+ z.object({
266
+ query_type: z.literal("local_mark_list"),
267
+ filter: LocalMarkFilterSchema.optional().describe("Local mark filter"),
268
+ }).describe("Query local ID/USER address book with optional filter"),
269
+ z.object({
270
+ query_type: z.literal("account_list"),
271
+ filter: AccountFilterSchema.optional().describe("Account filter"),
272
+ }).describe("Query account list with optional filter"),
273
+ z.object({
274
+ query_type: z.literal("local_info_list"),
275
+ filter: LocalInfoFilterSchema.optional().describe("Local info filter"),
276
+ }).describe("Query local info list with optional filter"),
277
+ z.object({
278
+ query_type: z.literal("token_list"),
279
+ filter: TokenDataFilterSchema.optional(),
280
+ }).describe("Query token list with optional filter"),
281
+ z.object({
282
+ query_type: z.literal("account_balance"),
283
+ name_or_address: NameOrAddressSchema.optional().describe("Account name or address. Use empty string '' for the default account. Defaults to '' if omitted."),
284
+ token_type: TokenTypeSchema.optional().describe("Token type; default token type is 0x2::wow::WOW"),
285
+ }).describe("Query account balance or coin objects by the token type"),
286
+ z.object({
287
+ query_type: z.literal("onchain_personal_profile"),
288
+ account: NameOrAddressSchema.optional().describe("Account name or ID to query. Use empty string '' for the default account."),
289
+ }).describe("Query PUBLIC on-chain personal profile for any account address"),
290
+ z.object({
291
+ query_type: z.literal("onchain_objects"),
292
+ objects: z.array(NameOrAddressSchema).describe("List of object IDs to query"),
293
+ }).describe("Query on-chain objects"),
294
+ z.object({
295
+ query_type: z.literal("onchain_table"),
296
+ parent: NameOrAddressSchema,
297
+ object_type: ObjectTypeSchema,
298
+ }).describe("Query on-chain table data of the specified object"),
299
+ z.object({
300
+ query_type: z.literal("onchain_table_item_repository_data"),
301
+ parent: NameOrAddressSchema.describe("Parent object ID of the data table to query"),
302
+ name: z.string().describe("Name of the record to query"),
303
+ entity: z.union([AccountOrMark_AddressSchema, z.number()]).describe("ID or address of the entity; or address that number is casted to"),
304
+ }).describe("Query repository data table item"),
305
+ z.object({
306
+ query_type: z.literal("onchain_table_item_permission_perm"),
307
+ parent: NameOrAddressSchema.describe("Parent object ID of the data table to query"),
308
+ address: z.union([AccountOrMark_AddressSchema, z.string()]).describe("User ID or address, or Guard ID in the permission perm table"),
309
+ }).describe("Query permission perm table item"),
310
+ z.object({
311
+ query_type: z.literal("onchain_table_item_entity_registrar"),
312
+ address: z.union([AccountOrMark_AddressSchema, z.string()]).describe("User ID or address of the entity"),
313
+ }).describe("Query entity registrar table item"),
314
+ z.object({
315
+ query_type: z.literal("onchain_table_item_entity_linker"),
316
+ address: z.union([AccountOrMark_AddressSchema, z.string()]).describe("ID or address that the registrar votes are attached to"),
317
+ }).describe("Query entity linker table item"),
318
+ z.object({
319
+ query_type: z.literal("onchain_table_item_reward_record"),
320
+ parent: NameOrAddressSchema.describe("Parent object ID of the data table to query"),
321
+ address: AccountOrMark_AddressSchema.describe("User ID or address that claims the reward"),
322
+ }).describe("Query reward record table item"),
323
+ z.object({
324
+ query_type: z.literal("onchain_table_item_demand_presenter"),
325
+ parent: NameOrAddressSchema.describe("Parent object ID of the data table to query"),
326
+ address: AccountOrMark_AddressSchema.describe("User ID or address of the Demand presenter"),
327
+ }).describe("Query demand presenter table item"),
328
+ z.object({
329
+ query_type: z.literal("onchain_table_item_treasury_history"),
330
+ parent: NameOrAddressSchema.describe("Parent object ID of the data table to query"),
331
+ address: AccountOrMark_AddressSchema.describe("ID of the payment that the treasury record is attached to"),
332
+ }).describe("Query treasury record table item"),
333
+ z.object({
334
+ query_type: z.literal("onchain_table_item_machine_node"),
335
+ parent: NameOrAddressSchema.describe("Parent object ID of the data table to query"),
336
+ key: z.string().describe("String key of the node name to query"),
337
+ }).describe("Query machine node table item"),
338
+ z.object({
339
+ query_type: z.literal("onchain_table_item_progress_history"),
340
+ parent: NameOrAddressSchema.describe("Parent object ID of the data table to query"),
341
+ u64: z.union([z.number(), z.string()]).describe("U64 value of the record to query"),
342
+ }).describe("Query progress history table item"),
343
+ z.object({
344
+ query_type: z.literal("onchain_table_item_address_mark"),
345
+ parent: NameOrAddressSchema.describe("Parent object ID of the data table to query"),
346
+ address: AccountOrMark_AddressSchema.describe("ID or address that the mark name and tags are attached to"),
347
+ }).describe("Query address mark table item"),
348
+ z.object({
349
+ query_type: z.literal("onchain_received"),
350
+ object: z.string().describe("Object ID to query"),
351
+ all_type: z.boolean().optional().describe("Whether to query all types of received objects"),
352
+ }).describe("Query on-chain received balance, payments, and NFTs"),
353
+ ]);
354
+ async function handleOnchainOperations(args) {
355
+ console.log("=== handleOnchainOperations ===");
356
+ console.log("args:", JSON.stringify(args, null, 2));
357
+ try {
358
+ const validated = strictParse(OnchainOperationsSchema, args, "onchain_operations input");
359
+ console.log("validated:", JSON.stringify(validated, null, 2));
360
+ const env = getEnvConfig(validated.env);
361
+ switch (validated.operation_type) {
362
+ case "service": {
363
+ const callService = new CallService(validated.data);
364
+ const result = validated.submission
365
+ ? await callService.call_with_submission(env, await transformSubmission(validated.submission))
366
+ : await callService.call(env);
367
+ return handleCallResult(result);
368
+ }
369
+ case "machine": {
370
+ if (validated.data.node && typeof validated.data.node === 'object' && 'json_or_markdown_file' in validated.data.node) {
371
+ const filePathStr = validated.data.node.json_or_markdown_file;
372
+ let fileContent;
373
+ try {
374
+ const filePath = resolve(filePathStr);
375
+ fileContent = readFileSync(filePath, 'utf-8');
376
+ }
377
+ catch (e) {
378
+ throw new Error(`Failed to read file '${filePathStr}': ${e.message}`);
379
+ }
380
+ const parseResult = parseMachineNodesFromText(fileContent);
381
+ if (!parseResult.success) {
382
+ const errorMessages = formatMachineNodeErrors(parseResult.errors);
383
+ throw new Error(`Machine node validation failed for file '${filePathStr}':\n\n${errorMessages}`);
384
+ }
385
+ if (!parseResult.data) {
386
+ throw new Error(`No nodes found in file '${filePathStr}'`);
387
+ }
388
+ validated.data.node = {
389
+ op: "set",
390
+ nodes: parseResult.data,
391
+ bReplace: true
392
+ };
393
+ }
394
+ const callMachine = new CallMachine(validated.data);
395
+ const result = validated.submission
396
+ ? await callMachine.call_with_submission(env, await transformSubmission(validated.submission))
397
+ : await callMachine.call(env);
398
+ return handleCallResult(result);
399
+ }
400
+ case "progress": {
401
+ const callProgress = new CallProgress(validated.data);
402
+ const result = validated.submission
403
+ ? await callProgress.call_with_submission(env, await transformSubmission(validated.submission))
404
+ : await callProgress.call(env);
405
+ return handleCallResult(result);
406
+ }
407
+ case "repository": {
408
+ const callRepository = new CallRepository(validated.data);
409
+ const result = validated.submission
410
+ ? await callRepository.call_with_submission(env, await transformSubmission(validated.submission))
411
+ : await callRepository.call(env);
412
+ return handleCallResult(result);
413
+ }
414
+ case "arbitration": {
415
+ const callArbitration = new CallArbitration(validated.data);
416
+ const result = validated.submission
417
+ ? await callArbitration.call_with_submission(env, await transformSubmission(validated.submission))
418
+ : await callArbitration.call(env);
419
+ return handleCallResult(result);
420
+ }
421
+ case "contact": {
422
+ const callContact = new CallContact(validated.data);
423
+ const result = validated.submission
424
+ ? await callContact.call_with_submission(env, await transformSubmission(validated.submission))
425
+ : await callContact.call(env);
426
+ return handleCallResult(result);
427
+ }
428
+ case "treasury": {
429
+ const callTreasury = new CallTreasury(validated.data);
430
+ const result = validated.submission
431
+ ? await callTreasury.call_with_submission(env, await transformSubmission(validated.submission))
432
+ : await callTreasury.call(env);
433
+ return handleCallResult(result);
434
+ }
435
+ case "reward": {
436
+ const transformedData = transformRewardData(validated.data);
437
+ const callReward = new CallReward(transformedData);
438
+ const result = validated.submission
439
+ ? await callReward.call_with_submission(env, await transformSubmission(validated.submission))
440
+ : await callReward.call(env);
441
+ return handleCallResult(result);
442
+ }
443
+ case "allocation": {
444
+ const callAllocation = new CallAllocation(validated.data);
445
+ const result = validated.submission
446
+ ? await callAllocation.call_with_submission(env, await transformSubmission(validated.submission))
447
+ : await callAllocation.call(env);
448
+ return handleCallResult(result);
449
+ }
450
+ case "permission": {
451
+ const callPermission = new CallPermission(validated.data);
452
+ const result = await callPermission.call(env);
453
+ return handleCallResult(result);
454
+ }
455
+ case "guard": {
456
+ const validatedData = validated.data;
457
+ if (validatedData.root?.type === "file") {
458
+ const filePath = resolve(validatedData.root.file_path);
459
+ let fileContent;
460
+ try {
461
+ fileContent = readFileSync(filePath, 'utf-8');
462
+ }
463
+ catch (e) {
464
+ throw new Error(`Failed to read Guard definition file '${validatedData.root.file_path}': ${e.message}`);
465
+ }
466
+ const parseResult = parseGuardFile(fileContent, validatedData.root.format);
467
+ if (!parseResult.success) {
468
+ const errorMessages = formatGuardParseErrors(parseResult.errors);
469
+ throw new Error(`Guard validation failed for file '${validatedData.root.file_path}':\n\n${errorMessages}`);
470
+ }
471
+ const fileData = parseResult.data;
472
+ validatedData.root = { type: "node", node: fileData.root };
473
+ if (fileData.table !== undefined && validatedData.table === undefined) {
474
+ validatedData.table = fileData.table;
475
+ }
476
+ if (fileData.description !== undefined && validatedData.description === undefined) {
477
+ validatedData.description = fileData.description;
478
+ }
479
+ if (fileData.rely !== undefined && validatedData.rely === undefined) {
480
+ validatedData.rely = fileData.rely;
481
+ }
482
+ if (fileData.namedNew !== undefined && validatedData.namedNew === undefined) {
483
+ validatedData.namedNew = fileData.namedNew;
484
+ }
485
+ }
486
+ if (validatedData.root && typeof validatedData.root === 'object') {
487
+ const rootObj = validatedData.root;
488
+ if (rootObj.type === 'node' && rootObj.node) {
489
+ validatedData.root = rootObj.node;
490
+ }
491
+ }
492
+ if (!validatedData.table || validatedData.table.length === 0) {
493
+ throw new Error("Guard 'table' field is required and cannot be empty");
494
+ }
495
+ if (!validatedData.root) {
496
+ throw new Error("Guard 'root' field is required");
497
+ }
498
+ const callGuard = new CallGuard(validatedData);
499
+ const result = await callGuard.call(env);
500
+ return handleCallResult(result);
501
+ }
502
+ case "personal": {
503
+ const transformPersonalData = (data) => {
504
+ const result = { ...data };
505
+ if (data.mark) {
506
+ const transformAddress = (addr) => {
507
+ if (typeof addr === 'string') {
508
+ return { name_or_address: addr, local_mark_first: true };
509
+ }
510
+ return addr;
511
+ };
512
+ if (data.mark.op === 'add' && data.mark.data) {
513
+ result.mark = {
514
+ ...data.mark,
515
+ data: data.mark.data.map((item) => ({
516
+ ...item,
517
+ address: transformAddress(item.address)
518
+ }))
519
+ };
520
+ }
521
+ else if (data.mark.op === 'remove' && data.mark.data) {
522
+ result.mark = {
523
+ ...data.mark,
524
+ data: data.mark.data.map((item) => ({
525
+ ...item,
526
+ address: transformAddress(item.address)
527
+ }))
528
+ };
529
+ }
530
+ else if (data.mark.op === 'clear' && data.mark.address) {
531
+ const addr = data.mark.address;
532
+ if (Array.isArray(addr) && addr.every((a) => typeof a === 'string')) {
533
+ result.mark = {
534
+ ...data.mark,
535
+ address: {
536
+ entities: addr.map((a) => ({ name_or_address: a, local_mark_first: true }))
537
+ }
538
+ };
539
+ }
540
+ }
541
+ else if (data.mark.op === 'transfer' && data.mark.to) {
542
+ result.mark = {
543
+ ...data.mark,
544
+ to: transformAddress(data.mark.to)
545
+ };
546
+ }
547
+ }
548
+ return result;
549
+ };
550
+ const transformedData = transformPersonalData(validated.data);
551
+ const callPersonal = new CallPersonal(transformedData);
552
+ const result = await callPersonal.call(env);
553
+ return handleCallResult(result);
554
+ }
555
+ case "payment": {
556
+ const callPayment = new CallPayment(validated.data);
557
+ const result = await callPayment.call(env);
558
+ return handleCallResult(result);
559
+ }
560
+ case "demand": {
561
+ const callDemand = new CallDemand(validated.data);
562
+ const result = validated.submission
563
+ ? await callDemand.call_with_submission(env, await transformSubmission(validated.submission))
564
+ : await callDemand.call(env);
565
+ return handleCallResult(result);
566
+ }
567
+ case "order": {
568
+ const callOrder = new CallOrder(validated.data);
569
+ const result = validated.submission
570
+ ? await callOrder.call_with_submission(env, await transformSubmission(validated.submission))
571
+ : await callOrder.call(env);
572
+ return handleCallResult(result);
573
+ }
574
+ case "gen_passport": {
575
+ const result = await gen_passport(env, validated.guard, validated.info);
576
+ return handleCallResult(result);
577
+ }
578
+ }
579
+ throw new Error(`Unknown on-chain operation type: ${validated.operation_type}`);
580
+ }
581
+ catch (error) {
582
+ const errorMessage = error instanceof Error ? error.message : String(error);
583
+ return {
584
+ content: [{ type: "text", text: `Error: ${errorMessage}` }],
585
+ structuredContent: {
586
+ message: `Error: ${errorMessage}`,
587
+ result: {
588
+ type: "error",
589
+ error: errorMessage,
590
+ },
591
+ },
592
+ };
593
+ }
594
+ }
595
+ async function handleAccountOperation(args) {
596
+ try {
597
+ const validated = strictParse(AccountOperationSchema, args, "account_operation input");
598
+ const result = await account_operation(validated);
599
+ return {
600
+ content: [{ type: "text", text: JSON.stringify(result) }],
601
+ structuredContent: {
602
+ result: {
603
+ status: "success",
604
+ data: result,
605
+ },
606
+ },
607
+ };
608
+ }
609
+ catch (error) {
610
+ const errorMessage = error instanceof Error ? error.message : String(error);
611
+ return {
612
+ content: [{ type: "text", text: `Error: ${errorMessage}` }],
613
+ structuredContent: {
614
+ result: {
615
+ status: "error",
616
+ error: errorMessage,
617
+ },
618
+ },
619
+ };
620
+ }
621
+ }
622
+ async function handleMarkOperation(args) {
623
+ try {
624
+ const validated = strictParse(LocalMarkOperationSchema, args, "local_mark_operation input");
625
+ const result = await local_mark_operation(validated);
626
+ return {
627
+ content: [{ type: "text", text: JSON.stringify(result) }],
628
+ structuredContent: {
629
+ result: {
630
+ status: "success",
631
+ data: result,
632
+ },
633
+ },
634
+ };
635
+ }
636
+ catch (error) {
637
+ const errorMessage = error instanceof Error ? error.message : String(error);
638
+ return {
639
+ content: [{ type: "text", text: `Error: ${errorMessage}` }],
640
+ structuredContent: {
641
+ result: {
642
+ status: "error",
643
+ error: errorMessage,
644
+ },
645
+ },
646
+ };
647
+ }
648
+ }
649
+ async function handleInfoOperation(args) {
650
+ try {
651
+ const validated = strictParse(LocalInfoOperationSchema, args, "local_info_operation input");
652
+ const result = await local_info_operation(validated);
653
+ return {
654
+ content: [{ type: "text", text: JSON.stringify(result) }],
655
+ structuredContent: {
656
+ result: {
657
+ status: "success",
658
+ data: result,
659
+ },
660
+ },
661
+ };
662
+ }
663
+ catch (error) {
664
+ const errorMessage = error instanceof Error ? error.message : String(error);
665
+ return {
666
+ content: [{ type: "text", text: `Error: ${errorMessage}` }],
667
+ structuredContent: {
668
+ result: {
669
+ status: "error",
670
+ error: errorMessage,
671
+ },
672
+ },
673
+ };
674
+ }
675
+ }
676
+ async function handleWipOperations(args) {
677
+ const validated = strictParse(WipOperationsSchema, args, "wip_file input");
678
+ let structuredContent;
679
+ switch (validated.type) {
680
+ case "generate": {
681
+ const result = await generate_wip(validated.options, validated.outputPath);
682
+ structuredContent = { result: { type: "generate", filePath: result } };
683
+ break;
684
+ }
685
+ case "verify": {
686
+ const result = await verify_wip(validated.wipFilePath, validated.hash_equal, validated.requireSignature);
687
+ structuredContent = { result: { type: "verify", ...result } };
688
+ break;
689
+ }
690
+ case "sign": {
691
+ const result = await sign_wip(validated.wipFilePath, validated.account, validated.outputPath);
692
+ structuredContent = { result: { type: "sign", filePath: result } };
693
+ break;
694
+ }
695
+ case "wip2html": {
696
+ const result = await wip2html(validated.wipPath, validated.options);
697
+ let output = { type: "wip2html" };
698
+ if (typeof result === "string") {
699
+ output.html = result;
700
+ }
701
+ else if (Array.isArray(result)) {
702
+ output.files = result;
703
+ }
704
+ else {
705
+ output.html = String(result);
706
+ }
707
+ structuredContent = { result: output };
708
+ break;
709
+ }
710
+ default:
711
+ throw new Error("Unknown WIP operation type");
712
+ }
713
+ return {
714
+ content: [{ type: "text", text: JSON.stringify(structuredContent) }],
715
+ structuredContent,
716
+ };
717
+ }
718
+ async function handleWatchQueryOperations(args) {
719
+ const validated = strictParse(WatchQueryOperationsSchema, args, "watch_and_query input");
720
+ let result;
721
+ switch (validated.query_type) {
722
+ case "local_mark_list": {
723
+ const queryResult = await query_local_mark_list(validated.filter || {});
724
+ result = { query_type: "local_mark_list", result: queryResult };
725
+ break;
726
+ }
727
+ case "account_list": {
728
+ const queryResult = await query_account_list(validated.filter);
729
+ result = { query_type: "account_list", result: queryResult };
730
+ break;
731
+ }
732
+ case "local_info_list": {
733
+ const queryResult = await query_local_info_list(validated.filter);
734
+ result = { query_type: "local_info_list", result: queryResult };
735
+ break;
736
+ }
737
+ case "token_list": {
738
+ const queryResult = await query_local_token_list(validated.filter || {});
739
+ result = { query_type: "token_list", result: queryResult };
740
+ break;
741
+ }
742
+ case "account_balance": {
743
+ const queryResult = await query_account({ name_or_address: validated.name_or_address, token_type: validated.token_type, balance: true });
744
+ result = { query_type: "account_balance", result: queryResult };
745
+ break;
746
+ }
747
+ case "onchain_personal_profile": {
748
+ const queryResult = await query_personal({ account: validated.account });
749
+ result = { query_type: "onchain_personal_profile", result: queryResult };
750
+ break;
751
+ }
752
+ case "onchain_objects": {
753
+ const queryResult = await query_objects({ objects: validated.objects });
754
+ if (queryResult && queryResult.objects && Array.isArray(queryResult.objects)) {
755
+ queryResult.objects = queryResult.objects.map((obj) => {
756
+ if (obj && obj.data && obj.data.type === "Guard" && obj.data.root) {
757
+ try {
758
+ const nodeComments = generateNodeComments(obj.data.root);
759
+ return {
760
+ ...obj,
761
+ _guard_node_comments: nodeComments
762
+ };
763
+ }
764
+ catch (e) {
765
+ return obj;
766
+ }
767
+ }
768
+ return obj;
769
+ });
770
+ }
771
+ result = { query_type: "onchain_objects", result: queryResult };
772
+ break;
773
+ }
774
+ case "onchain_table": {
775
+ const queryResult = await query_table({ parent: validated.parent, object_type: validated.object_type });
776
+ result = { query_type: "onchain_table", result: queryResult };
777
+ break;
778
+ }
779
+ case "onchain_table_item_repository_data": {
780
+ const queryResult = await queryTableItem_RepositoryData({ parent: validated.parent, name: validated.name, entity: validated.entity });
781
+ result = { query_type: "onchain_table_item_repository_data", result: queryResult };
782
+ break;
783
+ }
784
+ case "onchain_table_item_permission_perm": {
785
+ const queryResult = await queryTableItem_PermissionPerm({ parent: validated.parent, address: validated.address });
786
+ result = { query_type: "onchain_table_item_permission_perm", result: queryResult };
787
+ break;
788
+ }
789
+ case "onchain_table_item_reward_record": {
790
+ const queryResult = await queryTableItem_RewardRecord({ parent: validated.parent, address: validated.address });
791
+ result = { query_type: "onchain_table_item_reward_record", result: queryResult };
792
+ break;
793
+ }
794
+ case "onchain_table_item_demand_presenter": {
795
+ const queryResult = await queryTableItem_DemandPresenter({ parent: validated.parent, address: validated.address });
796
+ result = { query_type: "onchain_table_item_demand_presenter", result: queryResult };
797
+ break;
798
+ }
799
+ case "onchain_table_item_treasury_history": {
800
+ const queryResult = await queryTableItem_TreasuryHistory({ parent: validated.parent, address: validated.address });
801
+ result = { query_type: "onchain_table_item_treasury_history", result: queryResult };
802
+ break;
803
+ }
804
+ case "onchain_table_item_machine_node": {
805
+ const queryResult = await queryTableItem_MachineNode({ parent: validated.parent, key: validated.key });
806
+ result = { query_type: "onchain_table_item_machine_node", result: queryResult };
807
+ break;
808
+ }
809
+ case "onchain_table_item_progress_history": {
810
+ const queryResult = await queryTableItem_ProgressHistory({ parent: validated.parent, u64: validated.u64 });
811
+ result = { query_type: "onchain_table_item_progress_history", result: queryResult };
812
+ break;
813
+ }
814
+ case "onchain_table_item_address_mark": {
815
+ const queryResult = await queryTableItem_AddressMark({ parent: validated.parent, address: validated.address });
816
+ result = { query_type: "onchain_table_item_address_mark", result: queryResult };
817
+ break;
818
+ }
819
+ case "onchain_table_item_entity_registrar": {
820
+ const queryResult = await queryTableItem_EntityRegistrar({ address: validated.address });
821
+ result = { query_type: "onchain_table_item_entity_registrar", result: queryResult };
822
+ break;
823
+ }
824
+ case "onchain_table_item_entity_linker": {
825
+ const queryResult = await queryTableItem_EntityLinker({ address: validated.address });
826
+ result = { query_type: "onchain_table_item_entity_linker", result: queryResult };
827
+ break;
828
+ }
829
+ case "onchain_received": {
830
+ const queryResult = await query_received({ object: validated.object, all_type: validated.all_type });
831
+ result = { query_type: "onchain_received", result: queryResult };
832
+ break;
833
+ }
834
+ default:
835
+ throw new Error(`Unknown watch query type. Valid query_types are: "local_mark_list", "account_list", "local_info_list", "token_list", "account_balance", "onchain_personal_profile", "onchain_objects", "onchain_table", "onchain_table_item_repository_data", "onchain_table_item_permission_perm", "onchain_table_item_reward_record", "onchain_table_item_demand_presenter", "onchain_table_item_treasury_history", "onchain_table_item_machine_node", "onchain_table_item_progress_history", "onchain_table_item_address_mark", "onchain_table_item_entity_registrar", "onchain_table_item_entity_linker", "onchain_received"`);
836
+ }
837
+ return {
838
+ content: [{ type: "text", text: JSON.stringify({ result }) }],
839
+ structuredContent: { result },
840
+ };
841
+ }
842
+ async function handleWowokInfo(args) {
843
+ const validated = strictParse(ProtocolInfoQuerySchema, args, "wowok_buildin_info input");
844
+ const queryResult = await queryProtocolInfo(validated);
845
+ return {
846
+ content: [{ type: "text", text: JSON.stringify({ result: queryResult }) }],
847
+ structuredContent: { result: queryResult },
848
+ };
849
+ }
850
+ async function handleOnchainEvents(args) {
851
+ const validated = strictParse(OnchainEventsInputSchema, args, "onchain_events input");
852
+ const queryResult = await query_events({
853
+ type: validated.type,
854
+ cursor: validated.cursor ?? null,
855
+ limit: validated.limit ?? null,
856
+ order: validated.order ?? null,
857
+ no_cache: validated.no_cache,
858
+ network: validated.network,
859
+ });
860
+ return {
861
+ content: [{ type: "text", text: JSON.stringify({ result: queryResult }) }],
862
+ structuredContent: { result: queryResult },
863
+ };
864
+ }
865
+ function normalizeAccountOrMark(input) {
866
+ if (typeof input === 'string') {
867
+ return { name_or_address: input, local_mark_first: true };
868
+ }
869
+ return input;
870
+ }
871
+ function normalizeManyAccountOrMark(input) {
872
+ if (Array.isArray(input)) {
873
+ return {
874
+ entities: input.map(item => typeof item === 'string' ? { name_or_address: item, local_mark_first: true } : item),
875
+ check_all_founded: true
876
+ };
877
+ }
878
+ return input;
879
+ }
880
+ async function handleMessengerOperation(args) {
881
+ const validated = strictParse(MessengerOperationInputSchema, args, "messenger_operation input");
882
+ let result;
883
+ switch (validated.operation) {
884
+ case "watch_conversations": {
885
+ const conversations = await watch_conversations(validated.filter);
886
+ result = { operation: "watch_conversations", result: conversations };
887
+ break;
888
+ }
889
+ case "send_message": {
890
+ const sendResult = await send_message(validated.from, normalizeAccountOrMark(validated.to), validated.content, validated.options);
891
+ const filteredResult = {
892
+ ...sendResult,
893
+ merkleData: sendResult.merkleData ? {
894
+ leafIndex: sendResult.merkleData.leafIndex,
895
+ prevRoot: sendResult.merkleData.prevRoot,
896
+ newRoot: sendResult.merkleData.newRoot,
897
+ serverSignature: sendResult.merkleData.serverSignature,
898
+ serverTimestamp: sendResult.merkleData.serverTimestamp,
899
+ serverPublicKey: sendResult.merkleData.serverPublicKey,
900
+ } : undefined,
901
+ };
902
+ result = { operation: "send_message", result: filteredResult };
903
+ break;
904
+ }
905
+ case "send_file": {
906
+ const sendResult = await send_file(validated.from, normalizeAccountOrMark(validated.to), validated.filePath, validated.options);
907
+ const filteredResult = {
908
+ ...sendResult,
909
+ merkleData: sendResult.merkleData ? {
910
+ leafIndex: sendResult.merkleData.leafIndex,
911
+ prevRoot: sendResult.merkleData.prevRoot,
912
+ newRoot: sendResult.merkleData.newRoot,
913
+ serverSignature: sendResult.merkleData.serverSignature,
914
+ serverTimestamp: sendResult.merkleData.serverTimestamp,
915
+ serverPublicKey: sendResult.merkleData.serverPublicKey,
916
+ } : undefined,
917
+ };
918
+ result = { operation: "send_file", result: filteredResult };
919
+ break;
920
+ }
921
+ case "watch_messages": {
922
+ const filter = validated.filter ? {
923
+ ...validated.filter,
924
+ peerAddress: validated.filter.peerAddress ? normalizeAccountOrMark(validated.filter.peerAddress) : undefined
925
+ } : undefined;
926
+ const messages = await watch_messages(filter);
927
+ result = { operation: "watch_messages", result: messages };
928
+ break;
929
+ }
930
+ case "extract_zip_messages": {
931
+ const extractedPaths = await extract_zip_messages(validated.account, validated.messages, validated.outputDir);
932
+ result = { operation: "extract_zip_messages", result: extractedPaths };
933
+ break;
934
+ }
935
+ case "generate_wts": {
936
+ const params = validated.params ? {
937
+ ...validated.params,
938
+ peerAccount: normalizeAccountOrMark(validated.params.peerAccount)
939
+ } : undefined;
940
+ const wtsResult = await generate_wts(params);
941
+ result = { operation: "generate_wts", result: wtsResult };
942
+ break;
943
+ }
944
+ case "verify_wts": {
945
+ const verifyResult = await verify_wts(validated.wtsFilePath);
946
+ result = { operation: "verify_wts", result: verifyResult };
947
+ break;
948
+ }
949
+ case "sign_wts": {
950
+ const signedPath = await sign_wts(validated.wtsFilePath, validated.account, validated.outputPath);
951
+ result = { operation: "sign_wts", result: signedPath };
952
+ break;
953
+ }
954
+ case "wts2html": {
955
+ const htmlResult = await wts2html(validated.wtsPath, validated.options);
956
+ result = { operation: "wts2html", result: htmlResult };
957
+ break;
958
+ }
959
+ case "proof_message": {
960
+ const proofResult = await proof_message(validated.account, validated.messageId, validated.network);
961
+ result = { operation: "proof_message", result: proofResult };
962
+ break;
963
+ }
964
+ case "blacklist": {
965
+ const blacklistParams = {
966
+ account: validated.account,
967
+ op: validated.blacklist.op
968
+ };
969
+ if ('users' in validated.blacklist) {
970
+ blacklistParams.users = normalizeManyAccountOrMark(validated.blacklist.users);
971
+ }
972
+ const blacklistResult = await blacklist(blacklistParams);
973
+ result = { operation: "blacklist", op: validated.blacklist.op, result: blacklistResult.result };
974
+ break;
975
+ }
976
+ case "friendslist": {
977
+ const friendslistParams = {
978
+ account: validated.account,
979
+ op: validated.friendslist.op
980
+ };
981
+ if ('users' in validated.friendslist) {
982
+ friendslistParams.users = normalizeManyAccountOrMark(validated.friendslist.users);
983
+ }
984
+ const friendslistResult = await friendslist(friendslistParams);
985
+ result = { operation: "friendslist", op: validated.friendslist.op, result: friendslistResult.result };
986
+ break;
987
+ }
988
+ case "guardlist": {
989
+ const guardlistResult = await guardlist({
990
+ account: validated.account,
991
+ ...validated.guardlist
992
+ });
993
+ result = { operation: "guardlist", op: validated.guardlist.op, result: guardlistResult.result };
994
+ break;
995
+ }
996
+ case "settings": {
997
+ const settingsResult = await settings({
998
+ account: validated.account,
999
+ ...validated.settings
1000
+ });
1001
+ result = { operation: "settings", op: validated.settings.op, result: settingsResult.result };
1002
+ break;
1003
+ }
1004
+ case "mark_messages_as_viewed": {
1005
+ const markedCount = await mark_messages_as_viewed(validated.messageIds, validated.account);
1006
+ result = { operation: "mark_messages_as_viewed", result: markedCount };
1007
+ break;
1008
+ }
1009
+ case "mark_conversation_as_viewed": {
1010
+ const markedCount = await mark_conversation_as_viewed(normalizeAccountOrMark(validated.peerAddress), validated.account);
1011
+ result = { operation: "mark_conversation_as_viewed", result: markedCount };
1012
+ break;
1013
+ }
1014
+ default:
1015
+ throw new Error(`Unknown messenger operation: ${validated.operation}`);
1016
+ }
1017
+ return {
1018
+ content: [{ type: "text", text: JSON.stringify(result) }],
1019
+ structuredContent: { result },
1020
+ };
1021
+ }
1022
+ async function handleGuard2File(args) {
1023
+ const validated = strictParse(Guard2File_InputSchema, args, "guard2file input");
1024
+ const env = getEnvConfig(validated.env);
1025
+ try {
1026
+ await guard2file(validated.guard, validated.file_path, validated.format || "json", env.network);
1027
+ const result = {
1028
+ result: {
1029
+ status: "success",
1030
+ data: {
1031
+ file_path: resolve(validated.file_path),
1032
+ format: validated.format || "json",
1033
+ guard_object: validated.guard,
1034
+ },
1035
+ },
1036
+ };
1037
+ return {
1038
+ content: [{ type: "text", text: JSON.stringify(result) }],
1039
+ structuredContent: result,
1040
+ };
1041
+ }
1042
+ catch (error) {
1043
+ const result = {
1044
+ result: {
1045
+ status: "error",
1046
+ error: error.message,
1047
+ },
1048
+ };
1049
+ return {
1050
+ content: [{ type: "text", text: JSON.stringify(result) }],
1051
+ structuredContent: result,
1052
+ };
1053
+ }
1054
+ }
1055
+ async function handleMachineNode2File(args) {
1056
+ const validated = strictParse(MachineNode2File_InputSchema, args, "machineNode2file input");
1057
+ const env = getEnvConfig(validated.env);
1058
+ try {
1059
+ await machineNode2file(validated.machine, validated.file_path, validated.format || "json", env.network);
1060
+ const result = {
1061
+ result: {
1062
+ status: "success",
1063
+ data: {
1064
+ file_path: resolve(validated.file_path),
1065
+ format: validated.format || "json",
1066
+ machine_object: validated.machine,
1067
+ node_count: 0,
1068
+ },
1069
+ },
1070
+ };
1071
+ return {
1072
+ content: [{ type: "text", text: JSON.stringify(result) }],
1073
+ structuredContent: result,
1074
+ };
1075
+ }
1076
+ catch (error) {
1077
+ const result = {
1078
+ result: {
1079
+ status: "error",
1080
+ error: error.message,
1081
+ },
1082
+ };
1083
+ return {
1084
+ content: [{ type: "text", text: JSON.stringify(result) }],
1085
+ structuredContent: result,
1086
+ };
1087
+ }
1088
+ }
1089
+ export { OnchainOperationsSchema, WipOperationsSchema, WatchQueryOperationsSchema, AccountOperationSchema, LocalMarkOperationSchema, LocalInfoOperationSchema, ProtocolInfoQuerySchema, CallOutputSchema, MessengerOperationInputSchema, MessengerOperationOutputSchema };
1090
+ async function main() {
1091
+ server.registerTool("onchain_operations", {
1092
+ title: "â›“ī¸ On-chain Operations",
1093
+ description: "On-chain operations for WoWok object: service (marketplace listings), machine (workflow templates), progress (order tracking), repository (on-chain database), arbitration (dispute resolution), contact (IM management), treasury (team funds), reward (incentive pools), allocation (auto-distribution), permission (access control), guard (programmable trust rules), personal (public profile), payment (direct coin transfers), demand (service requests), order (order management), gen_passport (verified credentials).",
1094
+ inputSchema: OnchainOperationsSchema,
1095
+ outputSchema: CallOutputSchema,
1096
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
1097
+ _meta: createToolMeta("operation", ["service", "machine", "progress", "repository", "arbitration", "contact", "treasury", "reward", "allocation", "permission", "guard", "personal", "payment", "demand", "order", "gen_passport", "on-chain", "blockchain"]),
1098
+ }, handleOnchainOperations);
1099
+ server.registerTool("account_operation", {
1100
+ title: "🔒 LOCAL ONLY: Account - Wallet Management",
1101
+ description: "🔒 100% LOCAL, NEVER ON-CHAIN 🔒 Manage WoWok accounts locally on device: generate, suspend, resume, faucet-test, operate assets, sign data, etc.",
1102
+ inputSchema: AccountOperationSchema,
1103
+ outputSchema: AccountOperationOutputWrappedSchema,
1104
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
1105
+ _meta: createToolMeta("operation", ["account", "local", "private", "wallet", "off-chain"]),
1106
+ }, handleAccountOperation);
1107
+ server.registerTool("local_mark_operation", {
1108
+ title: "🔒 LOCAL ONLY: LocalMark - Address Book Management",
1109
+ description: "100% LOCAL, NEVER ON-CHAIN 🔒 Manage ID names and tags stored ONLY on your local device for easy identification of user address or object IDs by name.",
1110
+ inputSchema: LocalMarkOperationSchema,
1111
+ outputSchema: LocalMarkOperationOutputWrappedSchema,
1112
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
1113
+ _meta: createToolMeta("operation", ["mark", "local", "private", "address-book", "off-chain"]),
1114
+ }, handleMarkOperation);
1115
+ server.registerTool("local_info_operation", {
1116
+ title: "🔒 LOCAL ONLY: LocalInfo - Private Data Management",
1117
+ description: "100% LOCAL, NEVER ON-CHAIN 🔒 Manage sensitive personal information stored ONLY on your device: delivery addresses, phone numbers, contacts.",
1118
+ inputSchema: LocalInfoOperationSchema,
1119
+ outputSchema: LocalInfoOperationOutputWrappedSchema,
1120
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: true, openWorldHint: false },
1121
+ _meta: createToolMeta("operation", ["info", "local", "private", "data-management", "off-chain"]),
1122
+ }, handleInfoOperation);
1123
+ server.registerTool("wip_file", {
1124
+ title: "🤝 Witness Information Promise File Operations",
1125
+ description: "generate (create WIP files from markdown and images), verify (integrity check), sign (add signatures), or wip2html (convert to HTML).",
1126
+ inputSchema: WipOperationsSchema,
1127
+ outputSchema: z.object({
1128
+ result: WipOperationOutputSchema,
1129
+ }),
1130
+ annotations: { readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false },
1131
+ _meta: createToolMeta("operation", ["wip", "promise", "file-generation", "verification", "signature", "local"]),
1132
+ }, handleWipOperations);
1133
+ server.registerTool("messenger_operation", {
1134
+ title: "đŸ’Ŧ Messenger Operations",
1135
+ description: "WoWok encrypted messenger operations: watch conversations (with unread filtering, preview messages), send message, send file, watch messages (with viewed status filtering), extract zip messages, generate WTS, verify WTS, sign WTS, WTS to HTML, proof message on-chain, manage blacklist, friendslist, guardlist, settings, mark messages as viewed, and mark conversation as viewed.",
1136
+ inputSchema: MessengerOperationInputSchema,
1137
+ outputSchema: MessengerOperationOutputSchema,
1138
+ annotations: { readOnlyHint: false, destructiveHint: true, idempotentHint: false, openWorldHint: true },
1139
+ _meta: createToolMeta("operation", ["messenger", "message", "file", "wts", "blacklist", "friendslist", "guardlist", "settings", "proof", "communication"]),
1140
+ }, handleMessengerOperation);
1141
+ server.registerTool("guard2file", {
1142
+ title: "📄 Guard to File - Export Guard Definition",
1143
+ description: "Export a Guard object's definition from the blockchain to a local JSON or Markdown file for editing and creating new Guard objects. Note: To query on-chain object information, use the 'query_toolkit' tool instead.",
1144
+ inputSchema: Guard2File_InputSchema,
1145
+ outputSchema: Guard2File_OutputWrappedSchema,
1146
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
1147
+ _meta: createToolMeta("generate file", ["guard", "export", "file", "json", "markdown", "on-chain"]),
1148
+ }, handleGuard2File);
1149
+ server.registerTool("machineNode2file", {
1150
+ title: "âš™ī¸ Machine Node to File - Export Machine Node Definition",
1151
+ description: "Export a Machine object's node definition from the blockchain to a local JSON or Markdown file for editing and creating new Machine objects. Note: To query on-chain object information, use the 'query_toolkit' tool instead.",
1152
+ inputSchema: MachineNode2File_InputSchema,
1153
+ outputSchema: MachineNode2File_OutputWrappedSchema,
1154
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
1155
+ _meta: createToolMeta("generate file", ["machine", "export", "file", "json", "markdown", "on-chain", "workflow"]),
1156
+ }, handleMachineNode2File);
1157
+ server.registerTool("query_toolkit", {
1158
+ title: "🔍 Data Query Toolkit",
1159
+ description: "WOWOK data query toolkit: Query local naming info (accounts, names, Object IDs), and query on-chain WOWOK objects, table items, events, received tokens, user profile, etc.",
1160
+ inputSchema: WatchQueryOperationsSchema,
1161
+ outputSchema: WatchQueryOperationsResultSchema,
1162
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
1163
+ _meta: createToolMeta("query", ["watch", "query", "on-chain", "local", "events", "objects", "tables", "tokens", "balance", "profile"]),
1164
+ }, handleWatchQueryOperations);
1165
+ server.registerTool("onchain_events", {
1166
+ title: "📅 Watch On-chain Events",
1167
+ description: "Watch on-chain WOWOK events by type. Supports arbitration events, new order events, progress events, demand presentation events, demand feedback events, and new entity registration events. Use pagination cursor for fetching large result sets.",
1168
+ inputSchema: OnchainEventsInputSchema,
1169
+ outputSchema: OnchainEventsResultSchema,
1170
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
1171
+ _meta: createToolMeta("watch events", ["events", "on-chain", "arbitration", "order", "progress", "demand", "entity"]),
1172
+ }, handleOnchainEvents);
1173
+ server.registerTool("wowok_buildin_info", {
1174
+ title: "â„šī¸ WoWok Build-in Information",
1175
+ description: "Query WoWok protocol information: 'constants', 'built-in permissions', 'guard instructions', 'current network', or 'value types'.",
1176
+ inputSchema: ProtocolInfoQuerySchema,
1177
+ outputSchema: ProtocolInfoResultSchema,
1178
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
1179
+ _meta: createToolMeta("WoWok info", ["build-in", "constants", "permissions", "guard", "network", "value-types"]),
1180
+ }, handleWowokInfo);
1181
+ server.registerTool("documents_and_learn", {
1182
+ title: "📚 Documents and Learn",
1183
+ description: "Access WoWok documentation and learning resources. Provides official documentation URL for users and AI to get more information about WoWok protocol, components, and usage.",
1184
+ inputSchema: z.object({
1185
+ topic: z.string().optional().describe("Optional topic to search for in documentation (e.g., 'guard', 'service', 'messenger', 'stage-01-introduction')"),
1186
+ }),
1187
+ outputSchema: z.object({
1188
+ documentation_url: z.string().describe("Official WoWok documentation URL on GitHub"),
1189
+ topic: z.string().optional().describe("Requested topic if specified"),
1190
+ original_topic: z.string().optional().describe("Original topic input by user (before normalization)"),
1191
+ message: z.string().describe("Welcome message with documentation information. Always included in response."),
1192
+ }),
1193
+ annotations: { readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: true },
1194
+ _meta: createToolMeta("documentation", ["docs", "learn", "tutorial", "guide", "help", "reference"]),
1195
+ }, async (args) => {
1196
+ const GITHUB_BASE_URL = "https://github.com/wowok-ai/docs/blob/main/docs";
1197
+ if (!args.topic) {
1198
+ const url = GITHUB_BASE_URL;
1199
+ const message = `Welcome to WoWok Documentation! Access comprehensive guides, tutorials, and API references at: ${url}`;
1200
+ return {
1201
+ content: [
1202
+ {
1203
+ type: "text",
1204
+ text: message,
1205
+ },
1206
+ ],
1207
+ structuredContent: {
1208
+ documentation_url: url,
1209
+ message: message,
1210
+ },
1211
+ };
1212
+ }
1213
+ const normalizedTopic = args.topic.toLowerCase().trim();
1214
+ const url = `${GITHUB_BASE_URL}/${normalizedTopic}.md`;
1215
+ const message = `Documentation for "${normalizedTopic}"\nGitHub URL: ${url}`;
1216
+ return {
1217
+ content: [
1218
+ {
1219
+ type: "text",
1220
+ text: message,
1221
+ },
1222
+ ],
1223
+ structuredContent: {
1224
+ documentation_url: url,
1225
+ topic: normalizedTopic,
1226
+ original_topic: args.topic,
1227
+ message: message,
1228
+ },
1229
+ };
1230
+ });
1231
+ const transport = new StdioServerTransport();
1232
+ await server.connect(transport);
1233
+ process.on("SIGINT", async () => {
1234
+ await server.close();
1235
+ process.exit(0);
1236
+ });
1237
+ }
1238
+ main().catch(console.error);